diff --git a/README.md b/README.md index 6597b42a..bd7603bf 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Choices.js [![Actions Status](https://github.com/jshjohnson/Choices/workflows/Build%20and%20test/badge.svg)](https://github.com/jshjohnson/Choices/actions) [![Actions Status](https://github.com/jshjohnson/Choices/workflows/Bundle%20size%20checks/badge.svg)](https://github.com/jshjohnson/Choices/actions) [![npm](https://img.shields.io/npm/v/choices.js.svg)](https://www.npmjs.com/package/choices.js) -A vanilla, lightweight (~20.8kb gzipped 🎉), configurable select box/text input plugin. Similar to Select2 and Selectize but without the jQuery dependency. +A vanilla, lightweight (~19.9kb gzipped 🎉), configurable select box/text input plugin. Similar to Select2 and Selectize but without the jQuery dependency. [Demo](https://choices-js.github.io/Choices/) diff --git a/package-lock.json b/package-lock.json index 04ef2a84..4e6db4ee 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,8 +9,7 @@ "version": "11.0.0-rc5", "license": "MIT", "dependencies": { - "fuse.js": "^7.0.0", - "redux": "^4.2.0" + "fuse.js": "^7.0.0" }, "devDependencies": { "@babel/cli": "^7.24.8", @@ -1887,6 +1886,7 @@ "version": "7.25.0", "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.25.0.tgz", "integrity": "sha512-7dRy4DwXwtzBrPbZflqxnvfxLF8kdZXPkhymtDeFoFqE6ldzjQFgYTtYIFARcLEYDrqfBfYcZt1WqFxRoyC9Rw==", + "dev": true, "license": "MIT", "dependencies": { "regenerator-runtime": "^0.14.0" @@ -12241,15 +12241,6 @@ "node": ">=8.10.0" } }, - "node_modules/redux": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/redux/-/redux-4.2.1.tgz", - "integrity": "sha512-LAUYz4lc+Do8/g7aeRa8JkyDErK6ekstQaqWQrNRW//MY1TvCEpMtpTWvlQ+FPbWCx+Xixu/6SHt5N0HR+SB4w==", - "license": "MIT", - "dependencies": { - "@babel/runtime": "^7.9.2" - } - }, "node_modules/regenerate": { "version": "1.4.2", "resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.4.2.tgz", @@ -12274,6 +12265,7 @@ "version": "0.14.1", "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz", "integrity": "sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==", + "dev": true, "license": "MIT" }, "node_modules/regenerator-transform": { diff --git a/package.json b/package.json index 88ff66b9..4ca9dcf4 100644 --- a/package.json +++ b/package.json @@ -131,8 +131,7 @@ "vitest": "^2.0.5" }, "dependencies": { - "fuse.js": "^7.0.0", - "redux": "^4.2.0" + "fuse.js": "^7.0.0" }, "npmName": "choices.js", "npmFileMap": [ diff --git a/public/assets/scripts/choices.js b/public/assets/scripts/choices.js index b4cc7f5e..f837f450 100644 --- a/public/assets/scripts/choices.js +++ b/public/assets/scripts/choices.js @@ -105,14 +105,6 @@ highlighted: highlighted, }); }; - var clearAll = function () { return ({ - type: "CLEAR_ALL" /* ActionType.CLEAR_ALL */, - }); }; - var setTxn = function (txn) { return ({ - type: "SET_TRANSACTION" /* ActionType.SET_TRANSACTION */, - txn: txn, - }); }; - /* eslint-disable @typescript-eslint/no-explicit-any */ var getRandomNumber = function (min, max) { return Math.floor(Math.random() * (max - min) + min); @@ -240,9 +232,6 @@ }); return element.dispatchEvent(event); }; - var cloneObject = function (obj) { - return obj !== undefined ? JSON.parse(JSON.stringify(obj)) : undefined; - }; /** * Returns an array of keys present on the first but missing on the second object */ @@ -980,447 +969,85 @@ var ObjectsInConfig = ['fuseOptions', 'classNames']; - /** - * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js - * - * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes - * during build. - * @param {number} code - */ - function formatProdErrorMessage(code) { - return "Minified Redux error #" + code + "; visit https://redux.js.org/Errors?code=" + code + " for the full message or " + 'use the non-minified dev environment for full errors. '; - } - - // Inlined version of the `symbol-observable` polyfill - var $$observable = function () { - return typeof Symbol === 'function' && Symbol.observable || '@@observable'; - }(); - - /** - * These are private action types reserved by Redux. - * For any unknown actions, you must return the current state. - * If the current state is undefined, you must return the initial state. - * Do not reference these action types directly in your code. - */ - var randomString = function randomString() { - return Math.random().toString(36).substring(7).split('').join('.'); - }; - var ActionTypes = { - INIT: "@@redux/INIT" + randomString(), - REPLACE: "@@redux/REPLACE" + randomString(), - PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() { - return "@@redux/PROBE_UNKNOWN_ACTION" + randomString(); - } - }; - - /** - * @param {any} obj The object to inspect. - * @returns {boolean} True if the argument appears to be a plain object. - */ - function isPlainObject(obj) { - if (typeof obj !== 'object' || obj === null) return false; - var proto = obj; - while (Object.getPrototypeOf(proto) !== null) { - proto = Object.getPrototypeOf(proto); - } - return Object.getPrototypeOf(obj) === proto; - } - - /** - * @deprecated - * - * **We recommend using the `configureStore` method - * of the `@reduxjs/toolkit` package**, which replaces `createStore`. - * - * Redux Toolkit is our recommended approach for writing Redux logic today, - * including store setup, reducers, data fetching, and more. - * - * **For more details, please read this Redux docs page:** - * **https://redux.js.org/introduction/why-rtk-is-redux-today** - * - * `configureStore` from Redux Toolkit is an improved version of `createStore` that - * simplifies setup and helps avoid common bugs. - * - * You should not be using the `redux` core package by itself today, except for learning purposes. - * The `createStore` method from the core `redux` package will not be removed, but we encourage - * all users to migrate to using Redux Toolkit for all Redux code. - * - * If you want to use `createStore` without this visual deprecation warning, use - * the `legacy_createStore` import instead: - * - * `import { legacy_createStore as createStore} from 'redux'` - * - */ - - function createStore(reducer, preloadedState, enhancer) { - var _ref2; - if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') { - throw new Error(formatProdErrorMessage(0) ); - } - if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { - enhancer = preloadedState; - preloadedState = undefined; - } - if (typeof enhancer !== 'undefined') { - if (typeof enhancer !== 'function') { - throw new Error(formatProdErrorMessage(1) ); - } - return enhancer(createStore)(reducer, preloadedState); - } - if (typeof reducer !== 'function') { - throw new Error(formatProdErrorMessage(2) ); - } - var currentReducer = reducer; - var currentState = preloadedState; - var currentListeners = []; - var nextListeners = currentListeners; - var isDispatching = false; - /** - * This makes a shallow copy of currentListeners so we can use - * nextListeners as a temporary list while dispatching. - * - * This prevents any bugs around consumers calling - * subscribe/unsubscribe in the middle of a dispatch. - */ - - function ensureCanMutateNextListeners() { - if (nextListeners === currentListeners) { - nextListeners = currentListeners.slice(); - } - } - /** - * Reads the state tree managed by the store. - * - * @returns {any} The current state tree of your application. - */ - - function getState() { - if (isDispatching) { - throw new Error(formatProdErrorMessage(3) ); - } - return currentState; - } - /** - * Adds a change listener. It will be called any time an action is dispatched, - * and some part of the state tree may potentially have changed. You may then - * call `getState()` to read the current state tree inside the callback. - * - * You may call `dispatch()` from a change listener, with the following - * caveats: - * - * 1. The subscriptions are snapshotted just before every `dispatch()` call. - * If you subscribe or unsubscribe while the listeners are being invoked, this - * will not have any effect on the `dispatch()` that is currently in progress. - * However, the next `dispatch()` call, whether nested or not, will use a more - * recent snapshot of the subscription list. - * - * 2. The listener should not expect to see all state changes, as the state - * might have been updated multiple times during a nested `dispatch()` before - * the listener is called. It is, however, guaranteed that all subscribers - * registered before the `dispatch()` started will be called with the latest - * state by the time it exits. - * - * @param {Function} listener A callback to be invoked on every dispatch. - * @returns {Function} A function to remove this change listener. - */ - - function subscribe(listener) { - if (typeof listener !== 'function') { - throw new Error(formatProdErrorMessage(4) ); - } - if (isDispatching) { - throw new Error(formatProdErrorMessage(5) ); - } - var isSubscribed = true; - ensureCanMutateNextListeners(); - nextListeners.push(listener); - return function unsubscribe() { - if (!isSubscribed) { - return; - } - if (isDispatching) { - throw new Error(formatProdErrorMessage(6) ); - } - isSubscribed = false; - ensureCanMutateNextListeners(); - var index = nextListeners.indexOf(listener); - nextListeners.splice(index, 1); - currentListeners = null; - }; - } - /** - * Dispatches an action. It is the only way to trigger a state change. - * - * The `reducer` function, used to create the store, will be called with the - * current state tree and the given `action`. Its return value will - * be considered the **next** state of the tree, and the change listeners - * will be notified. - * - * The base implementation only supports plain object actions. If you want to - * dispatch a Promise, an Observable, a thunk, or something else, you need to - * wrap your store creating function into the corresponding middleware. For - * example, see the documentation for the `redux-thunk` package. Even the - * middleware will eventually dispatch plain object actions using this method. - * - * @param {Object} action A plain object representing “what changed”. It is - * a good idea to keep actions serializable so you can record and replay user - * sessions, or use the time travelling `redux-devtools`. An action must have - * a `type` property which may not be `undefined`. It is a good idea to use - * string constants for action types. - * - * @returns {Object} For convenience, the same action object you dispatched. - * - * Note that, if you use a custom middleware, it may wrap `dispatch()` to - * return something else (for example, a Promise you can await). - */ - - function dispatch(action) { - if (!isPlainObject(action)) { - throw new Error(formatProdErrorMessage(7) ); - } - if (typeof action.type === 'undefined') { - throw new Error(formatProdErrorMessage(8) ); - } - if (isDispatching) { - throw new Error(formatProdErrorMessage(9) ); - } - try { - isDispatching = true; - currentState = currentReducer(currentState, action); - } finally { - isDispatching = false; - } - var listeners = currentListeners = nextListeners; - for (var i = 0; i < listeners.length; i++) { - var listener = listeners[i]; - listener(); - } - return action; - } - /** - * Replaces the reducer currently used by the store to calculate the state. - * - * You might need this if your app implements code splitting and you want to - * load some of the reducers dynamically. You might also need this if you - * implement a hot reloading mechanism for Redux. - * - * @param {Function} nextReducer The reducer for the store to use instead. - * @returns {void} - */ - - function replaceReducer(nextReducer) { - if (typeof nextReducer !== 'function') { - throw new Error(formatProdErrorMessage(10) ); - } - currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT. - // Any reducers that existed in both the new and old rootReducer - // will receive the previous state. This effectively populates - // the new state tree with any relevant data from the old one. - - dispatch({ - type: ActionTypes.REPLACE - }); - } - /** - * Interoperability point for observable/reactive libraries. - * @returns {observable} A minimal observable of state changes. - * For more information, see the observable proposal: - * https://github.com/tc39/proposal-observable - */ - - function observable() { - var _ref; - var outerSubscribe = subscribe; - return _ref = { - /** - * The minimal observable subscription method. - * @param {Object} observer Any object that can be used as an observer. - * The observer object should have a `next` method. - * @returns {subscription} An object with an `unsubscribe` method that can - * be used to unsubscribe the observable from the store, and prevent further - * emission of values from the observable. - */ - subscribe: function subscribe(observer) { - if (typeof observer !== 'object' || observer === null) { - throw new Error(formatProdErrorMessage(11) ); - } - function observeState() { - if (observer.next) { - observer.next(getState()); - } - } - observeState(); - var unsubscribe = outerSubscribe(observeState); - return { - unsubscribe: unsubscribe - }; - } - }, _ref[$$observable] = function () { - return this; - }, _ref; - } // When a store is created, an "INIT" action is dispatched so that every - // reducer returns their initial state. This effectively populates - // the initial state tree. - - dispatch({ - type: ActionTypes.INIT - }); - return _ref2 = { - dispatch: dispatch, - subscribe: subscribe, - getState: getState, - replaceReducer: replaceReducer - }, _ref2[$$observable] = observable, _ref2; - } - function assertReducerShape(reducers) { - Object.keys(reducers).forEach(function (key) { - var reducer = reducers[key]; - var initialState = reducer(undefined, { - type: ActionTypes.INIT - }); - if (typeof initialState === 'undefined') { - throw new Error(formatProdErrorMessage(12) ); - } - if (typeof reducer(undefined, { - type: ActionTypes.PROBE_UNKNOWN_ACTION() - }) === 'undefined') { - throw new Error(formatProdErrorMessage(13) ); - } - }); - } - /** - * Turns an object whose values are different reducer functions, into a single - * reducer function. It will call every child reducer, and gather their results - * into a single state object, whose keys correspond to the keys of the passed - * reducer functions. - * - * @param {Object} reducers An object whose values correspond to different - * reducer functions that need to be combined into one. One handy way to obtain - * it is to use ES6 `import * as reducers` syntax. The reducers may never return - * undefined for any action. Instead, they should return their initial state - * if the state passed to them was undefined, and the current state for any - * unrecognized action. - * - * @returns {Function} A reducer function that invokes every reducer inside the - * passed object, and builds a state object with the same shape. - */ - - function combineReducers(reducers) { - var reducerKeys = Object.keys(reducers); - var finalReducers = {}; - for (var i = 0; i < reducerKeys.length; i++) { - var key = reducerKeys[i]; - if (typeof reducers[key] === 'function') { - finalReducers[key] = reducers[key]; - } - } - var finalReducerKeys = Object.keys(finalReducers); // This is used to make sure we don't warn about the same - var shapeAssertionError; - try { - assertReducerShape(finalReducers); - } catch (e) { - shapeAssertionError = e; - } - return function combination(state, action) { - if (state === void 0) { - state = {}; - } - if (shapeAssertionError) { - throw shapeAssertionError; - } - var hasChanged = false; - var nextState = {}; - for (var _i = 0; _i < finalReducerKeys.length; _i++) { - var _key = finalReducerKeys[_i]; - var reducer = finalReducers[_key]; - var previousStateForKey = state[_key]; - var nextStateForKey = reducer(previousStateForKey, action); - if (typeof nextStateForKey === 'undefined') { - action && action.type; - throw new Error(formatProdErrorMessage(14) ); - } - nextState[_key] = nextStateForKey; - hasChanged = hasChanged || nextStateForKey !== previousStateForKey; - } - hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length; - return hasChanged ? nextState : state; - }; - } - - function items(state, action) { - if (state === void 0) { state = []; } - if (action === void 0) { action = {}; } + function items(s, action) { + var state = s; + var update = false; switch (action.type) { case "ADD_ITEM" /* ActionType.ADD_ITEM */: { var item = action.item; - if (!item.id) { - return state; + if (item.id) { + item.selected = true; + var el = item.element; + if (el) { + el.selected = true; + el.setAttribute('selected', ''); + } + update = true; + state.push(item); + state.forEach(function (obj) { + // eslint-disable-next-line no-param-reassign + obj.highlighted = false; + }); } - item.selected = true; - var el = item.element; - if (el) { - el.selected = true; - el.setAttribute('selected', ''); - } - return __spreadArray(__spreadArray([], state, true), [item], false).map(function (obj) { - var choice = obj; - choice.highlighted = false; - return choice; - }); + break; } case "REMOVE_ITEM" /* ActionType.REMOVE_ITEM */: { var item_1 = action.item; - if (!item_1.id) { - return state; + if (item_1.id) { + item_1.selected = false; + var el = item_1.element; + if (el) { + el.selected = false; + el.removeAttribute('selected'); + } + update = true; + state = state.filter(function (choice) { return choice.id !== item_1.id; }); } - item_1.selected = false; - var el = item_1.element; - if (el) { - el.selected = false; - el.removeAttribute('selected'); - } - return state.filter(function (choice) { return choice.id !== item_1.id; }); + break; } case "REMOVE_CHOICE" /* ActionType.REMOVE_CHOICE */: { var choice_1 = action.choice; - return state.filter(function (item) { return item.id !== choice_1.id; }); + update = true; + state = state.filter(function (item) { return item.id !== choice_1.id; }); + break; } case "HIGHLIGHT_ITEM" /* ActionType.HIGHLIGHT_ITEM */: { var highlightItemAction_1 = action; - return state.map(function (obj) { + update = true; + state.forEach(function (obj) { var item = obj; if (item.id === highlightItemAction_1.item.id) { item.highlighted = highlightItemAction_1.highlighted; } - return item; }); - } - default: { - return state; + break; } } + return { state: state, update: update }; } - function groups(state, action) { - if (state === void 0) { state = []; } - if (action === void 0) { action = {}; } + function groups(s, action) { + var state = s; + var update = false; switch (action.type) { case "ADD_GROUP" /* ActionType.ADD_GROUP */: { var addGroupAction = action; - return __spreadArray(__spreadArray([], state, true), [addGroupAction.group], false); + update = true; + state.push(addGroupAction.group); + break; } case "CLEAR_CHOICES" /* ActionType.CLEAR_CHOICES */: { - return []; - } - default: { - return state; + update = true; + state = []; + break; } } + return { state: state, update: update }; } - function choices(state, action) { - if (state === void 0) { state = []; } - if (action === void 0) { action = {}; } + function choices(s, action) { + var state = s; + var update = false; switch (action.type) { case "ADD_CHOICE" /* ActionType.ADD_CHOICE */: { var choice = action.choice; @@ -1429,36 +1056,41 @@ A selected choice has been added to the passed input's value (added as an item) An active choice appears within the choice dropdown */ - return __spreadArray(__spreadArray([], state, true), [choice], false); + state.push(choice); + update = true; + break; } case "REMOVE_CHOICE" /* ActionType.REMOVE_CHOICE */: { var choice_1 = action.choice; - return state.filter(function (obj) { return obj.id !== choice_1.id; }); + update = true; + state = state.filter(function (obj) { return obj.id !== choice_1.id; }); + break; } case "ADD_ITEM" /* ActionType.ADD_ITEM */: { var item = action.item; // trigger a rebuild of the choices list as the item can not be added multiple times if (item.id && item.selected) { - return __spreadArray([], state, true); + update = true; } - return state; + break; } case "REMOVE_ITEM" /* ActionType.REMOVE_ITEM */: { var item = action.item; // trigger a rebuild of the choices list as the item can be added if (item.id && !item.selected) { - return __spreadArray([], state, true); + update = true; } - return state; + break; } case "FILTER_CHOICES" /* ActionType.FILTER_CHOICES */: { var results = action.results; + update = true; // avoid O(n^2) algorithm complexity when searching/filtering choices var scoreLookup_1 = []; results.forEach(function (result) { scoreLookup_1[result.item.id] = result; }); - return state.map(function (obj) { + state.forEach(function (obj) { var choice = obj; var result = scoreLookup_1[choice.id]; if (result !== undefined) { @@ -1471,102 +1103,110 @@ choice.rank = 0; choice.active = false; } - return choice; }); + break; } case "ACTIVATE_CHOICES" /* ActionType.ACTIVATE_CHOICES */: { var active_1 = action.active; - return state.map(function (obj) { + update = true; + state.forEach(function (obj) { var choice = obj; choice.active = active_1; return choice; }); + break; } case "CLEAR_CHOICES" /* ActionType.CLEAR_CHOICES */: { - return []; - } - default: { - return state; + update = true; + state = []; + break; } } + return { state: state, update: update }; } - var general = function (state, action) { - if (state === void 0) { state = 0; } - if (action === void 0) { action = {}; } - switch (action.type) { - case "SET_TRANSACTION" /* ActionType.SET_TRANSACTION */: { - if (action.txn) { - return state + 1; - } - return Math.max(0, state - 1); - } - default: { - return state; - } - } - }; - - var defaultState = { - groups: [], - items: [], - choices: [], - txn: 0, - }; - var appReducer = combineReducers({ - items: items, + var reducers = { groups: groups, + items: items, choices: choices, - txn: general, - }); - var rootReducer = function (passedState, action) { - var state = passedState; - // If we are clearing all items, groups and options we reassign - // state and then pass that state to our proper reducer. This isn't - // mutating our actual state - // See: http://stackoverflow.com/a/35641992 - if (action.type === "CLEAR_ALL" /* ActionType.CLEAR_ALL */) { - // preserve the txn state as to allow withTxn to work - var paused = state.txn; - state = cloneObject(defaultState); - state.txn = paused; - } - return appReducer(state, action); }; - - /* eslint-disable @typescript-eslint/no-explicit-any */ var Store = /** @class */ (function () { function Store() { - this._store = createStore(rootReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && - window.__REDUX_DEVTOOLS_EXTENSION__()); + this._store = this.defaultState; + this._listeners = []; + this._txn = 0; } - /** - * Subscribe store to function call (wrapped Redux method) - */ - Store.prototype.subscribe = function (onChange) { - this._store.subscribe(onChange); + Object.defineProperty(Store.prototype, "defaultState", { + // eslint-disable-next-line class-methods-use-this + get: function () { + return { + groups: [], + items: [], + choices: [], + }; + }, + enumerable: false, + configurable: true + }); + // eslint-disable-next-line class-methods-use-this + Store.prototype.changeSet = function (init) { + return { + groups: init, + items: init, + choices: init, + }; + }; + Store.prototype.resetStore = function () { + this._store = this.defaultState; + var changes = this.changeSet(true); + this._listeners.forEach(function (l) { return l(changes); }); + }; + Store.prototype.subscribe = function (onChange) { + this._listeners.push(onChange); }; - /** - * Dispatch event to store (wrapped Redux method) - */ Store.prototype.dispatch = function (action) { - this._store.dispatch(action); + var state = this._store; + var hasChanges = false; + var changes = this._outstandingChanges || this.changeSet(false); + Object.keys(reducers).forEach(function (key) { + var stateUpdate = reducers[key](state[key], action); + if (stateUpdate.update) { + hasChanges = true; + changes[key] = true; + state[key] = stateUpdate.state; + } + }); + if (hasChanges) { + if (this._txn) { + this._outstandingChanges = changes; + } + else { + this._listeners.forEach(function (l) { return l(changes); }); + } + } }; Store.prototype.withTxn = function (func) { - this._store.dispatch(setTxn(true)); + this._txn++; try { func(); } finally { - this._store.dispatch(setTxn(false)); + this._txn = Math.max(0, this._txn - 1); + if (!this._txn) { + var changeSet_1 = this._outstandingChanges; + if (changeSet_1) { + this._outstandingChanges = undefined; + this._listeners.forEach(function (l) { return l(changeSet_1); }); + } + } } }; Object.defineProperty(Store.prototype, "state", { /** - * Get store object (wrapping Redux method) + * Get store object */ get: function () { - return this._store.getState(); + return this._store; }, enumerable: false, configurable: true @@ -1636,10 +1276,10 @@ * Get active groups from store */ get: function () { - var _a = this, groups = _a.groups, choices = _a.choices; - return groups.filter(function (group) { + var _this = this; + return this.state.groups.filter(function (group) { var isActive = group.active && !group.disabled; - var hasActiveOptions = choices.some(function (choice) { return choice.active && !choice.disabled; }); + var hasActiveOptions = _this.state.choices.some(function (choice) { return choice.active && !choice.disabled; }); return isActive && hasActiveOptions; }, []); }, @@ -1647,7 +1287,7 @@ configurable: true }); Store.prototype.inTxn = function () { - return this.state.txn > 0; + return this._txn > 0; }; /** * Get single choice by it's ID @@ -3734,9 +3374,6 @@ } this.initialised = false; this._store = new Store(); - this._initialState = defaultState; - this._currentState = defaultState; - this._prevState = defaultState; this._currentValue = ''; this.config.searchEnabled = (!this._isTextElement && this.config.searchEnabled) || @@ -3819,8 +3456,7 @@ this._createTemplates(); this._createElements(); this._createStructure(); - this._store.subscribe(this._render); - this._render(); + this._initStore(); this._addEventListeners(); var shouldDisable = (this._isTextElement && !this.config.addItems) || this.passedElement.element.hasAttribute('disabled') || @@ -3844,6 +3480,7 @@ this.passedElement.reveal(); this.containerOuter.unwrap(this.passedElement.element); this.clearStore(); + this._store._listeners = []; this._stopSearch(); this._templates = templates; this.initialised = false; @@ -4249,7 +3886,7 @@ return this; }; Choices.prototype.clearStore = function () { - this._store.dispatch(clearAll()); + this._store.resetStore(); this._lastAddedChoiceId = 0; this._lastAddedGroupId = 0; // @todo integrate with Store @@ -4278,15 +3915,12 @@ } } }; - Choices.prototype._render = function () { + Choices.prototype._render = function (changes) { if (this._store.inTxn()) { return; } - this._currentState = this._store.state; - var shouldRenderItems = this._currentState.items !== this._prevState.items; - var stateChanged = this._currentState.choices !== this._prevState.choices || - this._currentState.groups !== this._prevState.groups || - shouldRenderItems; + var shouldRenderItems = changes === null || changes === void 0 ? void 0 : changes.items; + var stateChanged = (changes === null || changes === void 0 ? void 0 : changes.choices) || (changes === null || changes === void 0 ? void 0 : changes.groups) || shouldRenderItems; if (!stateChanged) { return; } @@ -4296,7 +3930,6 @@ if (shouldRenderItems) { this._renderItems(); } - this._prevState = this._currentState; }; Choices.prototype._renderChoices = function () { var _this = this; @@ -5515,7 +5148,6 @@ }); }; Choices.prototype._createStructure = function () { - var _this = this; // Hide original element this.passedElement.conceal(); // Wrap input in container preserving DOM ordering @@ -5543,6 +5175,10 @@ } this._highlightPosition = 0; this._isSearching = false; + }; + Choices.prototype._initStore = function () { + var _this = this; + this._store.subscribe(this._render); this._store.withTxn(function () { _this._addPredefinedChoices(_this._presetChoices, _this._isSelectOneElement && !_this._hasNonChoicePlaceholder, false); }); diff --git a/public/assets/scripts/choices.min.js b/public/assets/scripts/choices.min.js index 06216ec2..462b4e4f 100644 --- a/public/assets/scripts/choices.min.js +++ b/public/assets/scripts/choices.min.js @@ -1,2 +1,2 @@ /*! choices.js v11.0.0-rc5 | © 2024 Josh Johnson | https://github.com/jshjohnson/Choices#readme */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).Choices=t()}(this,(function(){"use strict";var e=function(t,i){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},e(t,i)};function t(t,i){if("function"!=typeof i&&null!==i)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");function n(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(n.prototype=i.prototype,new n)}var i=function(){return i=Object.assign||function(e){for(var t,i=1,n=arguments.length;i/g,">").replace(/0?this.element.scrollTop+r-s:e.offsetTop;requestAnimationFrame((function(){i._animateScroll(c,t)}))}},e.prototype._scrollDown=function(e,t,i){var n=(i-e)/t,s=n>1?n:1;this.element.scrollTop=e+s},e.prototype._scrollUp=function(e,t,i){var n=(e-i)/t,s=n>1?n:1;this.element.scrollTop=e-s},e.prototype._animateScroll=function(e,t){var i=this,n=this.element.scrollTop,s=!1;t>0?(this._scrollDown(n,4,e),ne&&(s=!0)),s&&requestAnimationFrame((function(){i._animateScroll(e,t)}))},e}(),C=function(){function e(e){var t=e.element,i=e.classNames;this.element=t,this.classNames=i,this.isDisabled=!1}return Object.defineProperty(e.prototype,"isActive",{get:function(){return"active"===this.element.dataset.choice},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dir",{get:function(){return this.element.dir},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.element.value},set:function(e){this.element.setAttribute("value",e),this.element.value=e},enumerable:!1,configurable:!0}),e.prototype.conceal=function(){var e;(e=this.element.classList).add.apply(e,d(this.classNames.input)),this.element.hidden=!0,this.element.tabIndex=-1;var t=this.element.getAttribute("style");t&&this.element.setAttribute("data-choice-orig-style",t),this.element.setAttribute("data-choice","active")},e.prototype.reveal=function(){var e;(e=this.element.classList).remove.apply(e,d(this.classNames.input)),this.element.hidden=!1,this.element.removeAttribute("tabindex");var t=this.element.getAttribute("data-choice-orig-style");t?(this.element.removeAttribute("data-choice-orig-style"),this.element.setAttribute("style",t)):this.element.removeAttribute("style"),this.element.removeAttribute("data-choice"),this.element.value=this.element.value},e.prototype.enable=function(){this.element.removeAttribute("disabled"),this.element.disabled=!1,this.isDisabled=!1},e.prototype.disable=function(){this.element.setAttribute("disabled",""),this.element.disabled=!0,this.isDisabled=!0},e.prototype.triggerEvent=function(e,t){!function(e,t,i){void 0===i&&(i=null);var n=new CustomEvent(t,{detail:i,bubbles:!0,cancelable:!0});e.dispatchEvent(n)}(this.element,e,t||{})},e}(),w=function(e){function i(){return null!==e&&e.apply(this,arguments)||this}return t(i,e),i}(C),I=function(e,t){return void 0===t&&(t=!0),void 0===e?t:!!e},S=function(e){if("string"==typeof e&&(e=e.split(" ").filter((function(e){return 0!==e.length}))),Array.isArray(e)&&0!==e.length)return e},O=function(e,t){if("string"==typeof e)return O({value:e,label:e},!1);var i=e;if("choices"in i){if(!t)throw new TypeError("optGroup is not allowed");var n=i,s=n.choices.map((function(e){return O(e,!1)}));return{id:0,label:l(n.label)||n.value,active:0!==s.length,disabled:!!n.disabled,choices:s}}var o=i;return{id:0,groupId:0,score:0,rank:0,value:o.value,label:o.label||o.value,active:I(o.active),selected:I(o.selected,!1),disabled:I(o.disabled,!1),placeholder:I(o.placeholder,!1),highlighted:!1,labelClass:S(o.labelClass),labelDescription:o.labelDescription,customProperties:o.customProperties}},A=function(e){function i(t){var i=t.element,n=t.classNames,s=t.template,o=t.extractPlaceholder,r=e.call(this,{element:i,classNames:n})||this;return r.template=s,r.extractPlaceholder=o,r}return t(i,e),Object.defineProperty(i.prototype,"placeholderOption",{get:function(){return this.element.querySelector('option[value=""]')||this.element.querySelector("option[placeholder]")},enumerable:!1,configurable:!0}),i.prototype.addOptions=function(e){var t=this;e.forEach((function(e){var i=e;if(!i.element){var n=t.template(i);t.element.appendChild(n),i.element=n}}))},i.prototype.optionsAsChoices=function(){var e=this,t=[];return this.element.querySelectorAll(":scope > option, :scope > optgroup").forEach((function(i){!function(e){return"OPTION"===e.tagName}(i)?function(e){return"OPTGROUP"===e.tagName}(i)&&t.push(e._optgroupToChoice(i)):t.push(e._optionToChoice(i))})),t},i.prototype._optionToChoice=function(e){return{id:0,groupId:0,score:0,rank:0,value:e.value,label:e.innerHTML,element:e,active:!0,selected:this.extractPlaceholder?e.selected:e.hasAttribute("selected"),disabled:e.disabled,highlighted:!1,placeholder:this.extractPlaceholder&&(""===e.value||e.hasAttribute("placeholder")),labelClass:void 0!==e.dataset.labelClass?S(e.dataset.labelClass):void 0,labelDescription:void 0!==e.dataset.labelDescription?e.dataset.labelDescription:void 0,customProperties:f(e.dataset.customProperties)}},i.prototype._optgroupToChoice=function(e){var t=this,i=e.querySelectorAll("option"),n=Array.from(i).map((function(e){return t._optionToChoice(e)}));return{id:0,label:e.label||"",element:e,active:0!==n.length,disabled:e.disabled,choices:n}},i}(C),x={items:[],choices:[],silent:!1,renderChoiceLimit:-1,maxItemCount:-1,singleModeForMultiSelect:!1,addChoices:!1,addItems:!0,addItemFilter:function(e){return!!e&&""!==e},removeItems:!0,removeItemButton:!1,removeItemButtonAlignLeft:!1,editItems:!1,allowHTML:!1,allowHtmlUserInput:!1,duplicateItemsAllowed:!0,delimiter:",",paste:!0,searchEnabled:!0,searchChoices:!0,searchFloor:1,searchResultLimit:4,searchFields:["label","value"],position:"auto",resetScrollPosition:!0,shouldSort:!0,shouldSortItems:!1,sorter:function(e,t){var i=e.value,n=e.label,s=void 0===n?i:n,o=t.value,r=t.label,c=void 0===r?o:r;return l(s).localeCompare(l(c),[],{sensitivity:"base",ignorePunctuation:!0,numeric:!0})},shadowRoot:null,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 "'.concat(e,'"')},removeItemIconText:function(){return"Remove item"},removeItemLabelText:function(e){return"Remove item: ".concat(e)},maxItemText:function(e){return"Only ".concat(e," values can be added")},valueComparer:function(e,t){return e===t},fuseOptions:{includeScore:!0},labelId:"",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"],description:["choices__description"],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"],selectedState:["is-selected"],flippedState:["is-flipped"],loadingState:["is-loading"],addChoice:["choices__item","choices__item--selectable","add-choice"],noResults:["has-no-results"],noChoices:["has-no-choices"]},appendGroupInSearch:!1},L=["fuseOptions","classNames"];function T(e){return"Minified Redux error #"+e+"; visit https://redux.js.org/Errors?code="+e+" for the full message or use the non-minified dev environment for full errors. "}var M="function"==typeof Symbol&&Symbol.observable||"@@observable",N=function(){return Math.random().toString(36).substring(7).split("").join(".")},F={INIT:"@@redux/INIT"+N(),REPLACE:"@@redux/REPLACE"+N(),PROBE_UNKNOWN_ACTION:function(){return"@@redux/PROBE_UNKNOWN_ACTION"+N()}};function j(e,t,i){var n;if("function"==typeof t&&"function"==typeof i||"function"==typeof i&&"function"==typeof arguments[3])throw new Error(T(0));if("function"==typeof t&&void 0===i&&(i=t,t=void 0),void 0!==i){if("function"!=typeof i)throw new Error(T(1));return i(j)(e,t)}if("function"!=typeof e)throw new Error(T(2));var s=e,o=t,r=[],c=r,a=!1;function h(){c===r&&(c=r.slice())}function l(){if(a)throw new Error(T(3));return o}function u(e){if("function"!=typeof e)throw new Error(T(4));if(a)throw new Error(T(5));var t=!0;return h(),c.push(e),function(){if(t){if(a)throw new Error(T(6));t=!1,h();var i=c.indexOf(e);c.splice(i,1),r=null}}}function d(e){if(!function(e){if("object"!=typeof e||null===e)return!1;for(var t=e;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}(e))throw new Error(T(7));if(void 0===e.type)throw new Error(T(8));if(a)throw new Error(T(9));try{a=!0,o=s(o,e)}finally{a=!1}for(var t=r=c,i=0;i0},e.prototype.getChoiceById=function(e){return this.activeChoices.find((function(t){return t.id===e}))},e.prototype.getGroupById=function(e){return this.groups.find((function(t){return t.id===e}))},e}(),H=function(e,t){return e?function(e){if("string"==typeof e)return e;if("object"==typeof e){if("escaped"in e)return e.escaped;if("trusted"in e)return e.trusted}return""}(t):a(t)},K=function(e,t){if(t){var i=e.dataset;"string"==typeof t?i.customProperties=t:"object"!=typeof t||function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}(t)||(i.customProperties=JSON.stringify(t))}},V={containerOuter:function(e,t,i,n,s,o,r){var c=e.classNames.containerOuter,a=Object.assign(document.createElement("div"),{className:d(c).join(" ")});return a.dataset.type=o,t&&(a.dir=t),n&&(a.tabIndex=0),i&&(a.setAttribute("role",s?"combobox":"listbox"),s&&a.setAttribute("aria-autocomplete","list")),a.setAttribute("aria-haspopup","true"),a.setAttribute("aria-expanded","false"),r&&a.setAttribute("aria-labelledby",r),a},containerInner:function(e){var t=e.classNames.containerInner;return Object.assign(document.createElement("div"),{className:d(t).join(" ")})},itemList:function(e,t){var i=e.classNames,n=i.list,s=i.listSingle,o=i.listItems;return Object.assign(document.createElement("div"),{className:"".concat(d(n).join(" ")," ").concat(t?d(s).join(" "):d(o).join(" "))})},placeholder:function(e,t){var i=e.allowHTML,n=e.classNames.placeholder;return Object.assign(document.createElement("div"),{className:d(n).join(" "),innerHTML:H(i,t)})},item:function(e,t,i){var n,s,o,r=e.allowHTML,c=e.removeItemButtonAlignLeft,h=e.classNames,l=h.item,u=h.button,p=h.highlightedState,f=h.itemSelectable,m=h.placeholder,g=t.id,v=t.value,_=t.label,y=t.labelClass,b=t.labelDescription,E=t.customProperties,C=t.active,w=t.disabled,I=t.highlighted,S=t.placeholder,O=Object.assign(document.createElement("div"),{className:d(l).join(" ")});if(y){var A=Object.assign(document.createElement("span"),{innerHTML:H(r,_),className:d(y).join(" ")});O.appendChild(A)}else O.innerHTML=H(r,_);if(Object.assign(O.dataset,{item:"",id:g,value:v}),y&&(O.dataset.labelClass=d(y).join(" ")),b&&(O.dataset.labelDescription=b),K(O,E),C&&O.setAttribute("aria-selected","true"),w&&O.setAttribute("aria-disabled","true"),S&&((n=O.classList).add.apply(n,d(m)),O.dataset.placeholder=""),(s=O.classList).add.apply(s,d(I?p:f)),i){w&&(o=O.classList).remove.apply(o,d(f)),O.dataset.deletable="";var x="function"==typeof this.config.removeItemIconText?this.config.removeItemIconText(a(v),v):this.config.removeItemIconText,L="function"==typeof this.config.removeItemLabelText?this.config.removeItemLabelText(a(v),v):this.config.removeItemLabelText,T=Object.assign(document.createElement("button"),{type:"button",className:d(u).join(" "),innerHTML:x});L&&T.setAttribute("aria-label",L),T.dataset.button="",c?O.insertAdjacentElement("afterbegin",T):O.appendChild(T)}return O},choiceList:function(e,t){var i=e.classNames.list,n=Object.assign(document.createElement("div"),{className:d(i).join(" ")});return t||n.setAttribute("aria-multiselectable","true"),n.setAttribute("role","listbox"),n},choiceGroup:function(e,t){var i=e.allowHTML,n=e.classNames,s=n.group,o=n.groupHeading,r=n.itemDisabled,c=t.id,a=t.label,h=t.disabled,l=Object.assign(document.createElement("div"),{className:"".concat(d(s).join(" ")," ").concat(h?d(r).join(" "):"")});return l.setAttribute("role","group"),Object.assign(l.dataset,{group:"",id:c,value:a}),h&&l.setAttribute("aria-disabled","true"),l.appendChild(Object.assign(document.createElement("div"),{className:d(o).join(" "),innerHTML:H(i,a)})),l},choice:function(e,t,i){var n,s,o,r,c,a=e.allowHTML,h=e.classNames,l=h.item,u=h.itemChoice,p=h.itemSelectable,f=h.selectedState,m=h.itemDisabled,g=h.description,v=h.placeholder,_=t.id,y=t.value,b=t.label,E=t.groupId,C=t.elementId,w=t.labelClass,I=t.labelDescription,S=t.disabled,O=t.selected,A=t.placeholder,x=Object.assign(document.createElement("div"),{id:C,className:"".concat(d(l).join(" ")," ").concat(d(u).join(" "))}),L=x;if(w){var T=Object.assign(document.createElement("span"),{innerHTML:H(a,b),className:d(w).join(" ")});L=T,x.appendChild(T)}else x.innerHTML=H(a,b);if(I){var M="".concat(C,"-description");L.setAttribute("aria-describedby",M);var N=Object.assign(document.createElement("span"),{innerHTML:H(a,I),id:M});(n=N.classList).add.apply(n,d(g)),x.appendChild(N)}return O&&(s=x.classList).add.apply(s,d(f)),A&&(o=x.classList).add.apply(o,d(v)),x.setAttribute("role",E&&E>0?"treeitem":"option"),Object.assign(x.dataset,{choice:"",id:_,value:y,selectText:i}),w&&(x.dataset.labelClass=d(w).join(" ")),I&&(x.dataset.labelDescription=I),S?((r=x.classList).add.apply(r,d(m)),x.dataset.choiceDisabled="",x.setAttribute("aria-disabled","true")):((c=x.classList).add.apply(c,d(p)),x.dataset.choiceSelectable=""),x},input:function(e,t){var i=e.classNames,n=i.input,s=i.inputCloned,o=Object.assign(document.createElement("input"),{type:"search",className:"".concat(d(n).join(" ")," ").concat(d(s).join(" ")),autocomplete:"off",autocapitalize:"off",spellcheck:!1});return o.setAttribute("role","textbox"),o.setAttribute("aria-autocomplete","list"),t&&o.setAttribute("aria-label",t),o},dropdown:function(e){var t,i,n=e.classNames,s=n.list,o=n.listDropdown,r=document.createElement("div");return(t=r.classList).add.apply(t,d(s)),(i=r.classList).add.apply(i,d(o)),r.setAttribute("aria-expanded","false"),r},notice:function(e,t,i){var s=e.allowHTML,o=e.classNames,r=o.item,c=o.itemChoice,a=o.addChoice,h=o.noResults,l=o.noChoices;void 0===i&&(i="");var u=n(n([],d(r),!0),d(c),!0);switch(i){case"add-choice":u.push.apply(u,d(a));break;case"no-results":u.push.apply(u,d(h));break;case"no-choices":u.push.apply(u,d(l))}var p=Object.assign(document.createElement("div"),{innerHTML:H(s,t),className:u.join(" ")});return"add-choice"===i&&(p.dataset.choiceSelectable="",p.dataset.choice=""),p},option:function(e){var t=e.label,i=e.value,n=e.labelClass,s=e.labelDescription,o=e.customProperties,r=e.active,c=e.disabled,a=l(t),h=new Option(a,i,!1,r);return n&&(h.dataset.labelClass=d(n).join(" ")),s&&(h.dataset.labelDescription=s),K(h,o),h.disabled=c,h}};function B(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function $(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function U(e){for(var t=1;t`Missing ${e} property in key`,ie=e=>`Property 'weight' in key '${e}' must be a positive integer`,ne=Object.prototype.hasOwnProperty;class se{constructor(e){this._keys=[],this._keyMap={};let t=0;e.forEach((e=>{let i=oe(e);this._keys.push(i),this._keyMap[i.id]=i,t+=i.weight})),this._keys.forEach((e=>{e.weight/=t}))}get(e){return this._keyMap[e]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function oe(e){let t=null,i=null,n=null,s=1,o=null;if(X(e)||q(e))n=e,t=re(e),i=ce(e);else{if(!ne.call(e,"name"))throw new Error(te("name"));const r=e.name;if(n=r,ne.call(e,"weight")&&(s=e.weight,s<=0))throw new Error(ie(r));t=re(r),i=ce(r),o=e.getFn}return{path:t,id:i,weight:s,src:n,getFn:o}}function re(e){return q(e)?e:e.split(".")}function ce(e){return q(e)?e.join("."):e}const ae={useExtendedSearch:!1,getFn:function(e,t){let i=[],n=!1;const s=(e,t,o)=>{if(Y(e))if(t[o]){const r=e[t[o]];if(!Y(r))return;if(o===t.length-1&&(X(r)||J(r)||z(r)))i.push(G(r));else if(q(r)){n=!0;for(let e=0,i=r.length;ee.score===t.score?e.idx{this._keysMap[e.id]=t}))}create(){!this.isCreated&&this.docs.length&&(this.isCreated=!0,X(this.docs[0])?this.docs.forEach(((e,t)=>{this._addString(e,t)})):this.docs.forEach(((e,t)=>{this._addObject(e,t)})),this.norm.clear())}add(e){const t=this.size();X(e)?this._addString(e,t):this._addObject(e,t)}removeAt(e){this.records.splice(e,1);for(let t=e,i=this.size();t{let s=t.getFn?t.getFn(e):this.getFn(e,t.path);if(Y(s))if(q(s)){let e=[];const t=[{nestedArrIndex:-1,value:s}];for(;t.length;){const{nestedArrIndex:i,value:n}=t.pop();if(Y(n))if(X(n)&&!Z(n)){let t={v:n,i:i,n:this.norm.get(n)};e.push(t)}else q(n)&&n.forEach(((e,i)=>{t.push({nestedArrIndex:i,value:e})}))}i.$[n]=e}else if(X(s)&&!Z(s)){let e={v:s,n:this.norm.get(s)};i.$[n]=e}})),this.records.push(i)}toJSON(){return{keys:this.keys,records:this.records}}}function de(e,t,{getFn:i=he.getFn,fieldNormWeight:n=he.fieldNormWeight}={}){const s=new ue({getFn:i,fieldNormWeight:n});return s.setKeys(e.map(oe)),s.setSources(t),s.create(),s}function pe(e,{errors:t=0,currentLocation:i=0,expectedLocation:n=0,distance:s=he.distance,ignoreLocation:o=he.ignoreLocation}={}){const r=t/e.length;if(o)return r;const c=Math.abs(n-i);return s?r+c/s:c?1:r}const fe=32;function me(e,t,i,{location:n=he.location,distance:s=he.distance,threshold:o=he.threshold,findAllMatches:r=he.findAllMatches,minMatchCharLength:c=he.minMatchCharLength,includeMatches:a=he.includeMatches,ignoreLocation:h=he.ignoreLocation}={}){if(t.length>fe)throw new Error(`Pattern length exceeds max of ${fe}.`);const l=t.length,u=e.length,d=Math.max(0,Math.min(n,u));let p=o,f=d;const m=c>1||a,g=m?Array(u):[];let v;for(;(v=e.indexOf(t,f))>-1;){let e=pe(t,{currentLocation:v,expectedLocation:d,distance:s,ignoreLocation:h});if(p=Math.min(e,p),f=v+l,m){let e=0;for(;e=a;o-=1){let r=o-1,c=i[e.charAt(r)];if(m&&(g[r]=+!!c),C[o]=(C[o+1]<<1|1)&c,n&&(C[o]|=(_[o+1]|_[o])<<1|1|_[o+1]),C[o]&E&&(y=pe(t,{errors:n,currentLocation:r,expectedLocation:d,distance:s,ignoreLocation:h}),y<=p)){if(p=y,f=r,f<=d)break;a=Math.max(1,2*d-f)}}if(pe(t,{errors:n+1,currentLocation:d,expectedLocation:d,distance:s,ignoreLocation:h})>p)break;_=C}const C={isMatch:f>=0,score:Math.max(.001,y)};if(m){const e=function(e=[],t=he.minMatchCharLength){let i=[],n=-1,s=-1,o=0;for(let r=e.length;o=t&&i.push([n,s]),n=-1)}return e[o-1]&&o-n>=t&&i.push([n,o-1]),i}(g,c);e.length?a&&(C.indices=e):C.isMatch=!1}return C}function ge(e){let t={};for(let i=0,n=e.length;i{this.chunks.push({pattern:e,alphabet:ge(e),startIndex:t})},l=this.pattern.length;if(l>fe){let e=0;const t=l%fe,i=l-t;for(;e{const{isMatch:f,score:m,indices:g}=me(e,t,d,{location:n+p,distance:s,threshold:o,findAllMatches:r,minMatchCharLength:c,includeMatches:i,ignoreLocation:a});f&&(u=!0),l+=m,f&&g&&(h=[...h,...g])}));let d={isMatch:u,score:u?l/this.chunks.length:1};return u&&i&&(d.indices=h),d}}class _e{constructor(e){this.pattern=e}static isMultiMatch(e){return ye(e,this.multiRegex)}static isSingleMatch(e){return ye(e,this.singleRegex)}search(){}}function ye(e,t){const i=e.match(t);return i?i[1]:null}class be extends _e{constructor(e,{location:t=he.location,threshold:i=he.threshold,distance:n=he.distance,includeMatches:s=he.includeMatches,findAllMatches:o=he.findAllMatches,minMatchCharLength:r=he.minMatchCharLength,isCaseSensitive:c=he.isCaseSensitive,ignoreLocation:a=he.ignoreLocation}={}){super(e),this._bitapSearch=new ve(e,{location:t,threshold:i,distance:n,includeMatches:s,findAllMatches:o,minMatchCharLength:r,isCaseSensitive:c,ignoreLocation:a})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(e){return this._bitapSearch.searchIn(e)}}class Ee extends _e{constructor(e){super(e)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(e){let t,i=0;const n=[],s=this.pattern.length;for(;(t=e.indexOf(this.pattern,i))>-1;)i=t+s,n.push([t,i-1]);const o=!!n.length;return{isMatch:o,score:o?0:1,indices:n}}}const Ce=[class extends _e{constructor(e){super(e)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(e){const t=e===this.pattern;return{isMatch:t,score:t?0:1,indices:[0,this.pattern.length-1]}}},Ee,class extends _e{constructor(e){super(e)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(e){const t=e.startsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,this.pattern.length-1]}}},class extends _e{constructor(e){super(e)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(e){const t=!e.startsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}},class extends _e{constructor(e){super(e)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(e){const t=!e.endsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}},class extends _e{constructor(e){super(e)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(e){const t=e.endsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[e.length-this.pattern.length,e.length-1]}}},class extends _e{constructor(e){super(e)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(e){const t=-1===e.indexOf(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}},be],we=Ce.length,Ie=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/;const Se=new Set([be.type,Ee.type]);class Oe{constructor(e,{isCaseSensitive:t=he.isCaseSensitive,includeMatches:i=he.includeMatches,minMatchCharLength:n=he.minMatchCharLength,ignoreLocation:s=he.ignoreLocation,findAllMatches:o=he.findAllMatches,location:r=he.location,threshold:c=he.threshold,distance:a=he.distance}={}){this.query=null,this.options={isCaseSensitive:t,includeMatches:i,minMatchCharLength:n,findAllMatches:o,ignoreLocation:s,location:r,threshold:c,distance:a},this.pattern=t?e:e.toLowerCase(),this.query=function(e,t={}){return e.split("|").map((e=>{let i=e.trim().split(Ie).filter((e=>e&&!!e.trim())),n=[];for(let e=0,s=i.length;e!(!e[Le]&&!e[Te]),je=e=>({[Le]:Object.keys(e).map((t=>({[t]:e[t]})))});function De(e,t,{auto:i=!0}={}){const n=e=>{let s=Object.keys(e);const o=(e=>!!e[Me])(e);if(!o&&s.length>1&&!Fe(e))return n(je(e));if((e=>!q(e)&&Q(e)&&!Fe(e))(e)){const n=o?e[Me]:s[0],r=o?e[Ne]:e[n];if(!X(r))throw new Error((e=>`Invalid value for key ${e}`)(n));const c={keyId:ce(n),pattern:r};return i&&(c.searcher=xe(r,t)),c}let r={children:[],operator:s[0]};return s.forEach((t=>{const i=e[t];q(i)&&i.forEach((e=>{r.children.push(n(e))}))})),r};return Fe(e)||(e=je(e)),n(e)}function Pe(e,t){const i=e.matches;t.matches=[],Y(i)&&i.forEach((e=>{if(!Y(e.indices)||!e.indices.length)return;const{indices:i,value:n}=e;let s={indices:i,value:n};e.key&&(s.key=e.key.src),e.idx>-1&&(s.refIndex=e.idx),t.matches.push(s)}))}function ke(e,t){t.score=e.score}class Re{constructor(e,t={},i){this.options=U(U({},he),t),this.options.useExtendedSearch,this._keyStore=new se(this.options.keys),this.setCollection(e,i)}setCollection(e,t){if(this._docs=e,t&&!(t instanceof ue))throw new Error("Incorrect 'index' type");this._myIndex=t||de(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(e){Y(e)&&(this._docs.push(e),this._myIndex.add(e))}remove(e=()=>!1){const t=[];for(let i=0,n=this._docs.length;i{let i=1;e.matches.forEach((({key:e,norm:n,score:s})=>{const o=e?e.weight:null;i*=Math.pow(0===s&&o?Number.EPSILON:s,(o||1)*(t?1:n))})),e.score=i}))}(c,{ignoreFieldNorm:r}),s&&c.sort(o),J(t)&&t>-1&&(c=c.slice(0,t)),function(e,t,{includeMatches:i=he.includeMatches,includeScore:n=he.includeScore}={}){const s=[];return i&&s.push(Pe),n&&s.push(ke),e.map((e=>{const{idx:i}=e,n={item:t[i],refIndex:i};return s.length&&s.forEach((t=>{t(e,n)})),n}))}(c,this._docs,{includeMatches:i,includeScore:n})}_searchStringList(e){const t=xe(e,this.options),{records:i}=this._myIndex,n=[];return i.forEach((({v:e,i:i,n:s})=>{if(!Y(e))return;const{isMatch:o,score:r,indices:c}=t.searchIn(e);o&&n.push({item:e,idx:i,matches:[{score:r,value:e,norm:s,indices:c}]})})),n}_searchLogical(e){const t=De(e,this.options),i=(e,t,n)=>{if(!e.children){const{keyId:i,searcher:s}=e,o=this._findMatches({key:this._keyStore.get(i),value:this._myIndex.getValueForItemAtKeyId(t,i),searcher:s});return o&&o.length?[{idx:n,item:t,matches:o}]:[]}const s=[];for(let o=0,r=e.children.length;o{if(Y(e)){let r=i(t,e,n);r.length&&(s[n]||(s[n]={idx:n,item:e,matches:[]},o.push(s[n])),r.forEach((({matches:e})=>{s[n].matches.push(...e)})))}})),o}_searchObjectList(e){const t=xe(e,this.options),{keys:i,records:n}=this._myIndex,s=[];return n.forEach((({$:e,i:n})=>{if(!Y(e))return;let o=[];i.forEach(((i,n)=>{o.push(...this._findMatches({key:i,value:e[n],searcher:t}))})),o.length&&s.push({idx:n,item:e,matches:o})})),s}_findMatches({key:e,value:t,searcher:i}){if(!Y(t))return[];let n=[];if(q(t))t.forEach((({v:t,i:s,n:o})=>{if(!Y(t))return;const{isMatch:r,score:c,indices:a}=i.searchIn(t);r&&n.push({score:c,key:e,value:t,idx:s,norm:o,indices:a})}));else{const{v:s,n:o}=t,{isMatch:r,score:c,indices:a}=i.searchIn(s);r&&n.push({score:c,key:e,value:s,norm:o,indices:a})}return n}}Re.version="7.0.0",Re.createIndex=de,Re.parseIndex=function(e,{getFn:t=he.getFn,fieldNormWeight:i=he.fieldNormWeight}={}){const{keys:n,records:s}=e,o=new ue({getFn:t,fieldNormWeight:i});return o.setKeys(n),o.setIndexRecords(s),o},Re.config=he,Re.parseQuery=De,function(...e){Ae.push(...e)}(Oe);var He=function(){function e(e){this._haystack=[],this._fuseOptions=i(i({},e.fuseOptions),{keys:n([],e.searchFields,!0),includeMatches:!0})}return e.prototype.index=function(e){this._haystack=e,this._fuse&&this._fuse.setCollection(e)},e.prototype.reset=function(){this._haystack=[],this._fuse=void 0},e.prototype.isEmptyIndex=function(){return 0===this._haystack.length},e.prototype.search=function(e){return this._fuse||(this._fuse=new Re(this._haystack,this._fuseOptions)),this._fuse.search(e).map((function(e,t){return{item:e.item,score:e.score||0,rank:t}}))},e}();var Ke="-ms-scroll-limit"in document.documentElement.style&&"-ms-ime-align"in document.documentElement.style,Ve={},Be=function(e){if(e){var t=e.dataset.id;return t?parseInt(t,10):void 0}},$e=function(){function e(t,n){void 0===t&&(t="[data-choice]"),void 0===n&&(n={});var s=this;this.initialisedOK=void 0,this._hasNonChoicePlaceholder=!1,this._lastAddedChoiceId=0,this._lastAddedGroupId=0,this.config=i(i(i({},e.defaults.allOptions),e.defaults.options),n),L.forEach((function(t){s.config[t]=i(i(i({},e.defaults.allOptions[t]),e.defaults.options[t]),n[t])})),this.config.silent||this._validateConfig();var o=this.config.shadowRoot||document.documentElement,r="string"==typeof t?o.querySelector(t):t;if(!r||"object"!=typeof r||"INPUT"!==r.tagName&&!function(e){return"SELECT"===e.tagName}(r)){if(!r&&"string"==typeof t)throw TypeError("Selector ".concat(t," failed to find an element"));throw TypeError("Expected one of the following types text|select-one|select-multiple")}if(this._elementType=r.type,this._isTextElement=this._elementType===g,(this._isTextElement||1!==this.config.maxItemCount)&&(this.config.singleModeForMultiSelect=!1),this.config.singleModeForMultiSelect&&(this._elementType=_),this._isSelectOneElement=this._elementType===v,this._isSelectMultipleElement=this._elementType===_,this._isSelectElement=this._isSelectOneElement||this._isSelectMultipleElement,this._canAddUserChoices=this._isTextElement&&this.config.addItems||this._isSelectElement&&this.config.addChoices,["auto","always"].includes("".concat(this.config.renderSelectedChoices))||(this.config.renderSelectedChoices="auto"),this.config.placeholder&&(this.config.placeholderValue?this._hasNonChoicePlaceholder=!0:r.dataset.placeholder&&(this._hasNonChoicePlaceholder=!0,this.config.placeholderValue=r.dataset.placeholder)),n.addItemFilter&&"function"!=typeof n.addItemFilter){var a=n.addItemFilter instanceof RegExp?n.addItemFilter:new RegExp(n.addItemFilter);this.config.addItemFilter=a.test.bind(a)}if(this._isTextElement)this.passedElement=new w({element:r,classNames:this.config.classNames});else{var h=r;this.passedElement=new A({element:h,classNames:this.config.classNames,template:function(e){return s._templates.option(e)},extractPlaceholder:this.config.placeholder&&!this._hasNonChoicePlaceholder})}if(this.initialised=!1,this._store=new R,this._initialState=D,this._currentState=D,this._prevState=D,this._currentValue="",this.config.searchEnabled=!this._isTextElement&&this.config.searchEnabled||this._elementType===_,this._canSearch=this.config.searchEnabled,this._isScrollingOnIe=!1,this._highlightPosition=0,this._wasTap=!0,this._placeholderValue=this._generatePlaceholderValue(),this._baseId=function(e,t){var i=e.id||e.name&&"".concat(e.name,"-").concat(c(2))||c(4);return i=i.replace(/(:|\.|\[|\]|,)/g,""),"".concat(t,"-").concat(i)}(this.passedElement.element,"choices-"),this._direction=this.passedElement.dir,!this._direction){var l=window.getComputedStyle(this.passedElement.element).direction;l!==window.getComputedStyle(document.documentElement).direction&&(this._direction=l)}if(this._idNames={itemChoice:"item-choice"},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._onInput=this._onInput.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._onSelectKey=this._onSelectKey.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.passedElement.isActive)return this.config.silent||console.warn("Trying to initialise Choices on element already initialised",{element:t}),this.initialised=!0,void(this.initialisedOK=!1);this.init(),this._initialItems=this._store.items.map((function(e){return e.value}))}return Object.defineProperty(e,"defaults",{get:function(){return Object.preventExtensions({get options(){return Ve},get allOptions(){return x},get templates(){return V}})},enumerable:!1,configurable:!0}),e.prototype.init=function(){if(!this.initialised&&void 0===this.initialisedOK){var e;this._searcher=(e=this.config,new He(e)),this._loadChoices(),this._createTemplates(),this._createElements(),this._createStructure(),this._store.subscribe(this._render),this._render(),this._addEventListeners(),(this._isTextElement&&!this.config.addItems||this.passedElement.element.hasAttribute("disabled")||!!this.passedElement.element.closest("fieldset:disabled"))&&this.disable(),this.initialised=!0,this.initialisedOK=!0;var t=this.config.callbackOnInit;t&&"function"==typeof t&&t.call(this)}},e.prototype.destroy=function(){this.initialised&&(this._removeEventListeners(),this.passedElement.reveal(),this.containerOuter.unwrap(this.passedElement.element),this.clearStore(),this._stopSearch(),this._templates=V,this.initialised=!1,this.initialisedOK=void 0)},e.prototype.enable=function(){return this.passedElement.isDisabled&&this.passedElement.enable(),this.containerOuter.isDisabled&&(this._addEventListeners(),this.input.enable(),this.containerOuter.enable()),this},e.prototype.disable=function(){return this.passedElement.isDisabled||this.passedElement.disable(),this.containerOuter.isDisabled||(this._removeEventListeners(),this.input.disable(),this.containerOuter.disable()),this},e.prototype.highlightItem=function(e,t){if(void 0===t&&(t=!0),!e||!e.id)return this;var i=this._store.choices.find((function(t){return t.id===e.id}));return!i||i.highlighted||(this._store.dispatch(o(i,!0)),t&&this.passedElement.triggerEvent("highlightItem",this._getChoiceForOutput(i))),this},e.prototype.unhighlightItem=function(e,t){if(void 0===t&&(t=!0),!e||!e.id)return this;var i=this._store.choices.find((function(t){return t.id===e.id}));return i&&i.highlighted?(this._store.dispatch(o(i,!1)),t&&this.passedElement.triggerEvent("highlightItem",this._getChoiceForOutput(i)),this):this},e.prototype.highlightAll=function(){var e=this;return this._store.withTxn((function(){e._store.items.forEach((function(t){return e.highlightItem(t)}))})),this},e.prototype.unhighlightAll=function(){var e=this;return this._store.withTxn((function(){e._store.items.forEach((function(t){return e.unhighlightItem(t)}))})),this},e.prototype.removeActiveItemsByValue=function(e){var t=this;return this._store.withTxn((function(){t._store.items.filter((function(t){return t.value===e})).forEach((function(e){return t._removeItem(e)}))})),this},e.prototype.removeActiveItems=function(e){var t=this;return this._store.withTxn((function(){t._store.items.filter((function(t){return t.id!==e})).forEach((function(e){return t._removeItem(e)}))})),this},e.prototype.removeHighlightedItems=function(e){var t=this;return void 0===e&&(e=!1),this._store.withTxn((function(){t._store.highlightedActiveItems.forEach((function(i){t._removeItem(i),e&&t._triggerChange(i.value)}))})),this},e.prototype.showDropdown=function(e){var t=this;return this.dropdown.isActive||requestAnimationFrame((function(){t.dropdown.show(),t.containerOuter.open(t.dropdown.distanceFromTopWindow),!e&&t._canSearch&&t.input.focus(),t.passedElement.triggerEvent("showDropdown")})),this},e.prototype.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("hideDropdown")})),this):this},e.prototype.getValue=function(e){var t=this;void 0===e&&(e=!1);var i=this._store.items.reduce((function(i,n){var s=e?n.value:t._getChoiceForOutput(n);return i.push(s),i}),[]);return this._isSelectOneElement||this.config.singleModeForMultiSelect?i[0]:i},e.prototype.setValue=function(e){var t=this;return this.initialisedOK?(this._store.withTxn((function(){e.forEach((function(e){e&&t._addChoice(O(e,!1))}))})),this._searcher.reset(),this):(this._warnChoicesInitFailed("setValue"),this)},e.prototype.setChoiceByValue=function(e){var t=this;return this.initialisedOK?(this._isTextElement||(this._store.withTxn((function(){(Array.isArray(e)?e:[e]).forEach((function(e){return t._findAndSelectChoiceByValue(e)}))})),this._searcher.reset()),this):(this._warnChoicesInitFailed("setChoiceByValue"),this)},e.prototype.setChoices=function(e,t,n,s){var o=this;if(void 0===e&&(e=[]),void 0===t&&(t="value"),void 0===n&&(n="label"),void 0===s&&(s=!1),!this.initialisedOK)return this._warnChoicesInitFailed("setChoices"),this;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(s&&this.clearChoices(),"function"==typeof e){var r=e(this);if("function"==typeof Promise&&r instanceof Promise)return new Promise((function(e){return requestAnimationFrame(e)})).then((function(){return o._handleLoadingState(!0)})).then((function(){return r})).then((function(e){return o.setChoices(e,t,n,s)})).catch((function(e){o.config.silent||console.error(e)})).then((function(){return o._handleLoadingState(!1)})).then((function(){return o}));if(!Array.isArray(r))throw new TypeError(".setChoices first argument function must return either array of choices or Promise, got: ".concat(typeof r));return this.setChoices(r,t,n,!1)}if(!Array.isArray(e))throw new TypeError(".setChoices must be called either with array of choices with a function resulting into Promise of array of choices");return this.containerOuter.removeLoadingState(),this._store.withTxn((function(){var s="value"===t,r="label"===n;e.forEach((function(e){if("choices"in e){var c=e;r||(c=i(i({},c),{label:c[n]})),o._addGroup(O(c,!0))}else{var a=e;r&&s||(a=i(i({},a),{value:a[t],label:a[n]})),o._addChoice(O(a,!1))}}))})),this._searcher.reset(),this},e.prototype.refresh=function(e,t,i){var n=this;return void 0===e&&(e=!1),void 0===t&&(t=!1),void 0===i&&(i=!1),this._isSelectElement?(this._store.withTxn((function(){var s=n.passedElement.optionsAsChoices(),o=n._store.items,r={};i||o.forEach((function(e){e.id&&e.active&&e.selected&&!e.disabled&&(r[e.value]=!0)})),s.forEach((function(e){if(!("choices"in e)){var t=e;i?t.selected=!1:r[t.value]&&(t.selected=!0)}})),n.clearStore(),n._addPredefinedChoices(s,t,e),n._isSearching&&n._searchChoices(n.input.value)})),this):(this.config.silent||console.warn("refresh method can only be used on choices backed by a element"),this)},e.prototype.removeChoice=function(e){var t=this._store.choices.find((function(t){return t.value===e}));return t?(this._store.dispatch(function(e){return{type:"REMOVE_CHOICE",choice:e}}(t)),this._searcher.reset(),t.selected&&this.passedElement.triggerEvent("removeItem",this._getChoiceForOutput(t)),this):this},e.prototype.clearChoices=function(){return this.passedElement.element.innerHTML="",this._store.dispatch({type:"CLEAR_CHOICES"}),this._searcher.reset(),this},e.prototype.clearStore=function(){return this._store.resetStore(),this._lastAddedChoiceId=0,this._lastAddedGroupId=0,this._searcher.reset(),this},e.prototype.clearInput=function(){var e=!this._isSelectOneElement;return this.input.clear(e),this._isSearching&&this._stopSearch(),this},e.prototype._validateConfig=function(){var e,t,i,n,s=(e=this.config,t=x,i=Object.keys(e).sort(),n=Object.keys(t).sort(),i.filter((function(e){return n.indexOf(e)<0})));s.length&&console.warn("Unknown config option(s) passed",s.join(", ")),this.config.allowHTML&&this.config.allowHtmlUserInput&&(this.config.addItems&&console.warn("Warning: allowHTML/allowHtmlUserInput/addItems all being true is strongly not recommended and may lead to XSS attacks"),this.config.addChoices&&console.warn("Warning: allowHTML/allowHtmlUserInput/addChoices all being true is strongly not recommended and may lead to XSS attacks"))},e.prototype._render=function(e){if(!this._store.inTxn()){var t=null==e?void 0:e.items;((null==e?void 0:e.choices)||(null==e?void 0:e.groups)||t)&&(this._isSelectElement&&this._renderChoices(),t&&this._renderItems())}},e.prototype._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){if(!this._hasNonChoicePlaceholder){var o=n.filter((function(e){return e.placeholder&&-1===e.groupId}));o.length>=1&&(s=this._createChoicesFragment(o,s))}s=this._createGroupsFragment(i,n,s)}else n.length>=1&&(s=this._createChoicesFragment(n,s));var r=this.input.value,c=this._canAddItem(this._store.items,r);if(s.childNodes&&s.childNodes.length>0){var a=!c.response;if(c.response&&(this.choiceList.append(s),this._highlightChoice(),this._canAddUserChoices&&r&&c.notice&&(a=!n.find((function(t){return e.config.valueComparer(t.value,r)})))),a){var h=this._templates.notice(this.config,c.notice,this._canAddUserChoices?"add-choice":"");this.choiceList.prepend(h)}}else{var l=void 0;if(c.response&&this._canAddUserChoices&&r)l=this._templates.notice(this.config,c.notice,"add-choice");else if(this._isSearching){h="function"==typeof this.config.noResultsText?this.config.noResultsText():this.config.noResultsText;l=this._templates.notice(this.config,h,"no-results")}else{h="function"==typeof this.config.noChoicesText?this.config.noChoicesText():this.config.noChoicesText;l=this._templates.notice(this.config,h,"no-choices")}this.choiceList.append(l)}},e.prototype._renderItems=function(){var e=this._store.items||[];this.itemList.clear();var t=this._createItemsFragment(e);t.childNodes&&this.itemList.append(t)},e.prototype._createGroupsFragment=function(e,t,i){var n=this;void 0===i&&(i=document.createDocumentFragment());this.config.shouldSort&&e.sort(this.config.sorter);var s=t.filter((function(e){return 0===e.groupId}));return s.length>0&&this._createChoicesFragment(s,i,!1),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 o=n._templates.choiceGroup(n.config,e);i.appendChild(o),n._createChoicesFragment(s,i,!0)}})),i},e.prototype._createChoicesFragment=function(e,t,i){var s=this;void 0===t&&(t=document.createDocumentFragment()),void 0===i&&(i=!1);var o=this.config,r=o.renderSelectedChoices,c=o.searchResultLimit,a=o.renderChoiceLimit,h=[],u=this.config.appendGroupInSearch&&this._isSearching;u&&this._store.groups.forEach((function(e){h[e.id]=e.label}));var d=function(e){if("auto"!==r||(s._isSelectOneElement||!e.selected)){var i=s._templates.choice(s.config,e,s.config.itemSelectText);if(u&&e.groupId>0){var n=h[e.groupId];n&&(i.innerHTML+=" (".concat(n,")"))}t.appendChild(i)}},p=e;if("auto"!==r||this._isSelectOneElement||(p=e.filter((function(e){return!e.selected}))),this._isSelectElement){var f=e.filter((function(e){return!e.element}));0!==f.length&&this.passedElement.addOptions(f)}var m=[],g=[];this._hasNonChoicePlaceholder?g=p:p.forEach((function(e){e.placeholder?m.push(e):g.push(e)})),this._isSearching?g.sort(l):this.config.shouldSort&&g.sort(this.config.sorter);var v=p.length,_=this._isSelectOneElement&&0!==m.length?n(n([],m,!0),g,!0):g;this._isSearching?v=c:a&&a>0&&!i&&(v=a);for(var y=0;y0?this._store.getGroupById(e.groupId):null;return{id:e.id,highlighted:e.highlighted,labelClass:e.labelClass,labelDescription:e.labelDescription,customProperties:e.customProperties,disabled:e.disabled,active:e.active,label:e.label,placeholder:e.placeholder,value:e.value,groupValue:i&&i.label?i.label:void 0,element:e.element,keyCode:t}}},e.prototype._triggerChange=function(e){null!=e&&this.passedElement.triggerEvent("change",{value:e})},e.prototype._handleButtonAction=function(e,t){if(0!==e.length&&this.config.removeItems&&this.config.removeItemButton){var i=t&&De(t.parentNode),n=i&&e.find((function(e){return e.id===i}));if(n&&(this._removeItem(n),this._triggerChange(n.value),this._isSelectOneElement&&!this._hasNonChoicePlaceholder)){var s=this._store.choices.reverse().find((function(e){return!e.disabled&&e.placeholder}));s&&(this._addItem(s),s.value&&this._triggerChange(s.value))}}},e.prototype._handleItemAction=function(e,t,i){var n=this;if(void 0===i&&(i=!1),0!==e.length&&this.config.removeItems&&!this._isSelectOneElement){var s=De(t);s&&(e.forEach((function(e){e.id!==s||e.highlighted?!i&&e.highlighted&&n.unhighlightItem(e):n.highlightItem(e)})),this.input.focus())}},e.prototype._handleChoiceAction=function(e,t,i){var n=this,s=De(t),o=s&&this._store.getChoiceById(s);if(!o)return!1;var r=this.dropdown.isActive,c=!1;return this._store.withTxn((function(){if(!o.selected&&!o.disabled&&n._canAddItem(e,o.value).response){if(n.config.singleModeForMultiSelect&&0!==e.length){var t=e[e.length-1];n._removeItem(t)}n.passedElement.triggerEvent("choice",n._getChoiceForOutput(o,i)),n._addItem(o),n.clearInput(),c=!0}})),!!c&&(this._triggerChange(o.value),r&&(this.config.singleModeForMultiSelect||this._isSelectOneElement)&&(this.hideDropdown(!0),this.containerOuter.focus()),!0)},e.prototype._handleBackspace=function(e){if(this.config.removeItems&&0!==e.length){var t=e[e.length-1],i=e.some((function(e){return e.highlighted}));this.config.editItems&&!i&&t?(this.input.value=t.value,this.input.setWidth(),this._removeItem(t),this._triggerChange(t.value)):(i||this.highlightItem(t,!1),this.removeHighlightedItems(!0))}},e.prototype._loadChoices=function(){var e;if(this._isTextElement){this._presetChoices=this.config.items.map((function(e){return w(e,!1)}));var t=this.passedElement.value;if(t){var i=t.split(this.config.delimiter).map((function(e){return w(e,!1)}));this._presetChoices=this._presetChoices.concat(i)}this._presetChoices.forEach((function(e){e.selected=!0}))}else if(this._isSelectElement){this._presetChoices=this.config.choices.map((function(e){return w(e,!0)}));var n=this.passedElement.optionsAsChoices();n&&(e=this._presetChoices).push.apply(e,n)}},e.prototype._handleLoadingState=function(e){void 0===e&&(e=!0);var t=this.itemList.element.querySelector(d(this.config.classNames.placeholder));e?(this.disable(),this.containerOuter.addLoadingState(),this._isSelectOneElement?t?t.innerHTML=this.config.loadingText:(t=this._templates.placeholder(this.config,this.config.loadingText))&&this.itemList.append(t):this.input.placeholder=this.config.loadingText):(this.enable(),this.containerOuter.removeLoadingState(),this._isSelectOneElement?t&&(t.innerHTML=this._placeholderValue||""):this.input.placeholder=this._placeholderValue||"")},e.prototype._handleSearch=function(e){if(this.input.isFocussed){var t=this._store.choices,i=this.config,n=i.searchFloor,s=i.searchChoices,o=t.some((function(e){return!e.active}));if(null!=e&&e.length>=n){var r=s?this._searchChoices(e):0;null!==r&&this.passedElement.triggerEvent("search",{value:e,resultCount:r})}else o&&this._stopSearch()}},e.prototype._canAddItem=function(e,t){var i=this,n=!0,s="";(this.config.maxItemCount>0&&this.config.maxItemCount<=e.length&&(this.config.singleModeForMultiSelect||(n=!1,s="function"==typeof this.config.maxItemText?this.config.maxItemText(this.config.maxItemCount):this.config.maxItemText)),n&&this._canAddUserChoices&&""!==t&&"function"==typeof this.config.addItemFilter&&!this.config.addItemFilter(t)&&(n=!1,s="function"==typeof this.config.customAddItemText?this.config.customAddItemText(c(t),t):this.config.customAddItemText),!n||""===t||!this._isSelectElement&&this.config.duplicateItemsAllowed)||this._store.items.find((function(e){return i.config.valueComparer(e.value,t)}))&&(n=!1,s="function"==typeof this.config.uniqueItemText?this.config.uniqueItemText(c(t),t):this.config.uniqueItemText);return n&&(s="function"==typeof this.config.addItemText?this.config.addItemText(c(t),t):this.config.addItemText),{response:n,notice:{trusted:s}}},e.prototype._searchChoices=function(e){var t=e.trim().replace(/\s{2,}/," ");if(0===t.length||t===this._currentValue)return null;var i=this._searcher;i.isEmptyIndex()&&i.index(this._store.searchableChoices);var n=i.search(t);return this._currentValue=t,this._highlightPosition=0,this._isSearching=!0,this._store.dispatch(function(e){return{type:"FILTER_CHOICES",results:e}}(n)),n.length},e.prototype._stopSearch=function(){var e=this._isSearching;this._currentValue="",this._isSearching=!1,e&&this._store.dispatch({type:"ACTIVATE_CHOICES",active:!0})},e.prototype._addEventListeners=function(){var e=this.config.shadowRoot||document.documentElement;e.addEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.addEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.addEventListener("mousedown",this._onMouseDown,!0),e.addEventListener("click",this._onClick,{passive:!0}),e.addEventListener("touchmove",this._onTouchMove,{passive:!0}),this.dropdown.element.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("input",this._onInput,{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()},e.prototype._removeEventListeners=function(){var e=this.config.shadowRoot||document.documentElement;e.removeEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.removeEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.removeEventListener("mousedown",this._onMouseDown,!0),e.removeEventListener("click",this._onClick),e.removeEventListener("touchmove",this._onTouchMove),this.dropdown.element.removeEventListener("mouseover",this._onMouseOver),this._isSelectOneElement&&(this.containerOuter.element.removeEventListener("focus",this._onFocus),this.containerOuter.element.removeEventListener("blur",this._onBlur)),this.input.element.removeEventListener("keyup",this._onKeyUp),this.input.element.removeEventListener("input",this._onInput),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()},e.prototype._onKeyDown=function(e){var t=e.keyCode,i=this._store.items,n=this.input.isFocussed,s=this.dropdown.isActive,o=this.itemList.hasChildren(),r=1===e.key.length||2===e.key.length&&e.key.charCodeAt(0)>=55296||"Unidentified"===e.key;switch(this._isTextElement||s||(this.showDropdown(),!this.input.isFocussed&&r&&(this.input.value+=e.key)),t){case 65:return this._onSelectKey(e,o);case 13:return this._onEnterKey(e,i,s);case 27:return this._onEscapeKey(e,s);case 38:case 33:case 40:case 34:return this._onDirectionKey(e,s);case 8:case 46:return this._onDeleteKey(e,i,n)}},e.prototype._onKeyUp=function(){this._canSearch=this.config.searchEnabled},e.prototype._onInput=function(){var e=this.input.value;if(e){if(this._isTextElement){var t=this._canAddItem(this._store.items,e);t.notice&&(this._displayAddItemNotice(t),this.showDropdown(!0))}if(this._canSearch){this._handleSearch(e);var i=this._canAddItem(this._store.items,e);i.response||this._displayAddItemNotice(i),this._canAddUserChoices&&(this._highlightPosition=0,this._highlightChoice())}}else this._isTextElement?this.hideDropdown(!0):this._stopSearch()},e.prototype._displayAddItemNotice=function(e){var t=this._templates.notice(this.config,e.notice,"add-choice"),i="".concat(d(this.config.classNames.addChoice),"[data-choice-selectable]"),n=this.choiceList.element.querySelector(i);n?n.outerHTML=t.outerHTML:this.choiceList.prepend(t)},e.prototype._onSelectKey=function(e,t){var i=e.ctrlKey,n=e.metaKey;(i||n)&&t&&(this._canSearch=!1,this.config.removeItems&&!this.input.value&&this.input.element===document.activeElement&&this.highlightAll())},e.prototype._onEnterKey=function(e,t,i){var n=this,s=this.input.value,o=e.target;if(o&&o.hasAttribute("data-button"))return e.preventDefault(),void this._handleButtonAction(t,o);if(!i&&this._isSelectOneElement)return e.preventDefault(),void this.showDropdown();if(i){var r=this.dropdown.element.querySelector(d(this.config.classNames.highlightedState));if(r&&this._handleChoiceAction(t,r,13))return e.preventDefault(),void this.unhighlightAll();s||this.hideDropdown(!0)}o&&s&&this._canAddUserChoices&&(this._canAddItem(t,s).response&&(this._store.withTxn((function(){if((n._isSelectOneElement||n.config.singleModeForMultiSelect)&&0!==t.length){var e=t[t.length-1];n._removeItem(e)}var i=!0;if(!n._isSelectElement&&n.config.duplicateItemsAllowed||(i=!n._findAndSelectChoiceByValue(s)),i){var o=c(s),r=n.config.allowHtmlUserInput||o===s?s:{escaped:o,raw:s};n._addChoice(w({value:r,label:r,selected:!0},!1))}n.clearInput(),n.unhighlightAll(),n._triggerChange(s)})),(this._isTextElement||this._isSelectOneElement)&&this.hideDropdown(!0)))},e.prototype._onEscapeKey=function(e,t){t&&(e.stopPropagation(),this.hideDropdown(!0),this.containerOuter.focus())},e.prototype._onDirectionKey=function(e,t){var i,n,s,o=e.keyCode,r=e.metaKey;if(t||this._isSelectOneElement){this.showDropdown(),this._canSearch=!1;var c=40===o||34===o?1:-1,a="[data-choice-selectable]",h=void 0;if(r||34===o||33===o)h=c>0?this.dropdown.element.querySelector("".concat(a,":last-of-type")):this.dropdown.element.querySelector(a);else{var l=this.dropdown.element.querySelector(d(this.config.classNames.highlightedState));h=l?function(e,t,i){void 0===i&&(i=1);for(var n="".concat(i>0?"next":"previous","ElementSibling"),s=e[n];s;){if(s.matches(t))return s;s=s[n]}return s}(l,a,c):this.dropdown.element.querySelector(a)}h&&(i=h,n=this.choiceList.element,void 0===(s=c)&&(s=1),i&&(s>0?n.scrollTop+n.offsetHeight>=i.offsetTop+i.offsetHeight:i.offsetTop>=n.scrollTop)||this.choiceList.scrollToChildElement(h,c),this._highlightChoice(h)),e.preventDefault()}},e.prototype._onDeleteKey=function(e,t,i){var n=e.target;this._isSelectOneElement||n.value||!i||(this._handleBackspace(t),e.preventDefault())},e.prototype._onTouchMove=function(){this._wasTap&&(this._wasTap=!1)},e.prototype._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},e.prototype._onMouseDown=function(e){var t=e.target;if(t instanceof HTMLElement){if(Ne&&this.choiceList.element.contains(t)){var i=this.choiceList.element.firstElementChild;this._isScrollingOnIe="ltr"===this._direction?e.offsetX>=i.offsetWidth:e.offsetX0&&this.unhighlightAll(),this.containerOuter.removeFocusState(),this.hideDropdown(!0))},e.prototype._onFocus=function(e){var t,i=this,n=e.target;n&&this.containerOuter.element.contains(n)&&((t={})[m]=function(){n===i.input.element&&i.containerOuter.addFocusState()},t[g]=function(){i.containerOuter.addFocusState(),n===i.input.element&&i.showDropdown(!0)},t[v]=function(){n===i.input.element&&(i.showDropdown(!0),i.containerOuter.addFocusState())},t)[this._elementType]()},e.prototype._onBlur=function(e){var t,i=this,n=e.target;if(n&&this.containerOuter.element.contains(n)&&!this._isScrollingOnIe){var s=this._store.activeChoices.some((function(e){return e.highlighted}));((t={})[m]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),s&&i.unhighlightAll(),i.hideDropdown(!0))},t[g]=function(){i.containerOuter.removeFocusState(),(n===i.input.element||n===i.containerOuter.element&&!i._canSearch)&&i.hideDropdown(!0)},t[v]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),i.hideDropdown(!0),s&&i.unhighlightAll())},t)[this._elementType]()}else this._isScrollingOnIe=!1,this.input.element.focus()},e.prototype._onFormReset=function(){var e=this;this._store.withTxn((function(){e.clearInput(),e.hideDropdown(),e.refresh(!1,!1,!0),0!==e._initialItems.length&&e.setChoiceByValue(e._initialItems)}))},e.prototype._highlightChoice=function(e){var t,i=this;void 0===e&&(e=null);var n=Array.from(this.dropdown.element.querySelectorAll("[data-choice-selectable]"));if(n.length){var s=e;Array.from(this.dropdown.element.querySelectorAll(d(this.config.classNames.highlightedState))).forEach((function(e){var t;(t=e.classList).remove.apply(t,u(i.config.classNames.highlightedState)),e.setAttribute("aria-selected","false")})),s?this._highlightPosition=n.indexOf(s):(s=n.length>this._highlightPosition?n[this._highlightPosition]:n[n.length-1])||(s=n[0]),(t=s.classList).add.apply(t,u(this.config.classNames.highlightedState)),s.setAttribute("aria-selected","true"),this.passedElement.triggerEvent("highlightChoice",{el:s}),this.dropdown.isActive&&(this.input.setActiveDescendant(s.id),this.containerOuter.setActiveDescendant(s.id))}},e.prototype._addItem=function(e,t){void 0===t&&(t=!0);var i=e.id;if(0===i)throw new TypeError("item.id must be set before _addItem is called for a choice/item");this._store.dispatch(function(e){return{type:"ADD_ITEM",item:e}}(e)),this._isSelectOneElement&&this.removeActiveItems(i),t&&this.passedElement.triggerEvent("addItem",this._getChoiceForOutput(e))},e.prototype._removeItem=function(e){e.id&&(this._store.dispatch(function(e){return{type:"REMOVE_ITEM",item:e}}(e)),this.passedElement.triggerEvent("removeItem",this._getChoiceForOutput(e)))},e.prototype._addChoice=function(e,t){if(void 0===t&&(t=!0),0!==e.id)throw new TypeError("Can not re-add a choice which has already been added");var i=e;this._lastAddedChoiceId++,i.id=this._lastAddedChoiceId,i.elementId="".concat(this._baseId,"-").concat(this._idNames.itemChoice,"-").concat(i.id),this.config.prependValue&&(i.value=this.config.prependValue+i.value),this.config.appendValue&&(i.value+=this.config.appendValue.toString()),(this.config.prependValue||this.config.appendValue)&&i.element&&(i.element.value=i.value),this._store.dispatch(function(e){return{type:"ADD_CHOICE",choice:e}}(e)),e.selected&&this._addItem(e,t)},e.prototype._addGroup=function(e,t){var i=this;if(void 0===t&&(t=!0),0!==e.id)throw new TypeError("Can not re-add a group which has already been added");if(this._store.dispatch(function(e){return{type:"ADD_GROUP",group:e}}(e)),e.choices){var n=e;this._lastAddedGroupId++,n.id=this._lastAddedGroupId;var s=e.id,o=e.choices;n.choices=[],o.forEach((function(n){var o=n;o.groupId=s,e.disabled&&(o.disabled=!0),i._addChoice(o,t)}))}},e.prototype._createTemplates=function(){var e=this,t=this.config.callbackOnCreateTemplates,i={};t&&"function"==typeof t&&(i=t.call(this,a,M));var n={};Object.keys(F).forEach((function(t){n[t]=t in i?i[t].bind(e):F[t].bind(e)})),this._templates=n},e.prototype._createElements=function(){this.containerOuter=new _({element:this._templates.containerOuter(this.config,this._direction,this._isSelectElement,this._isSelectOneElement,this.config.searchEnabled,this._elementType,this.config.labelId),classNames:this.config.classNames,type:this._elementType,position:this.config.position}),this.containerInner=new _({element:this._templates.containerInner(this.config),classNames:this.config.classNames,type:this._elementType,position:this.config.position}),this.input=new y({element:this._templates.input(this.config,this._placeholderValue),classNames:this.config.classNames,type:this._elementType,preventPaste:!this.config.paste}),this.choiceList=new b({element:this._templates.choiceList(this.config,this._isSelectOneElement)}),this.itemList=new b({element:this._templates.itemList(this.config,this._isSelectOneElement)}),this.dropdown=new f({element:this._templates.dropdown(this.config),classNames:this.config.classNames,type:this._elementType})},e.prototype._createStructure=function(){this.passedElement.conceal(),this.containerInner.wrap(this.passedElement.element),this.containerOuter.wrap(this.containerInner.element),this._isSelectOneElement?this.input.placeholder=this.config.searchPlaceholderValue||"":(this._placeholderValue&&(this.input.placeholder=this._placeholderValue),this.input.setWidth()),this.containerOuter.element.appendChild(this.containerInner.element),this.containerOuter.element.appendChild(this.dropdown.element),this.containerInner.element.appendChild(this.itemList.element),this.dropdown.element.appendChild(this.choiceList.element),this._isSelectOneElement?this.config.searchEnabled&&this.dropdown.element.insertBefore(this.input.element,this.dropdown.element.firstChild):this.containerInner.element.appendChild(this.input.element),this._highlightPosition=0,this._isSearching=!1},e.prototype._initStore=function(){var e=this;this._store.subscribe(this._render),this._store.withTxn((function(){e._addPredefinedChoices(e._presetChoices,e._isSelectOneElement&&!e._hasNonChoicePlaceholder,!1)}))},e.prototype._addPredefinedChoices=function(e,t,i){var n=this;if(void 0===t&&(t=!1),void 0===i&&(i=!0),this.config.shouldSort&&e.sort(this.config.sorter),t){var s=-1===e.findIndex((function(e){return!!e.selected}));if(s){var o=e.findIndex((function(e){return void 0===e.disabled||!e.disabled}));if(-1!==o)e[o].selected=!0}}e.forEach((function(e){"choices"in e?n._isSelectElement&&n._addGroup(e,i):n._addChoice(e,i)}))},e.prototype._findAndSelectChoiceByValue=function(e){var t=this,i=this._store.choices.find((function(i){return t.config.valueComparer(i.value,e)}));return!(!i||i.selected)&&(this._addItem(i),!0)},e.prototype._generatePlaceholderValue=function(){if(!this.config.placeholder)return null;if(this._hasNonChoicePlaceholder)return this.config.placeholderValue;if(this._isSelectElement){var e=this.passedElement.placeholderOption;return e?e.text:null}return null},e.prototype._warnChoicesInitFailed=function(e){if(!this.config.silent){if(!this.initialised)throw new TypeError("".concat(e," called on a non-initialised instance of Choices"));if(!this.initialisedOK)throw new TypeError("".concat(e," called for an element which has multiple instances of Choices initialised on it"))}},e.version="11.0.0-rc5",e}();return je})); diff --git a/public/assets/scripts/choices.min.mjs b/public/assets/scripts/choices.min.mjs index ae7e82fe..44e5ef20 100644 --- a/public/assets/scripts/choices.min.mjs +++ b/public/assets/scripts/choices.min.mjs @@ -1,2 +1,2 @@ /*! choices.js v11.0.0-rc5 | © 2024 Josh Johnson | https://github.com/jshjohnson/Choices#readme */ -var e=function(t,i){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},e(t,i)};function t(t,i){if("function"!=typeof i&&null!==i)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");function n(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(n.prototype=i.prototype,new n)}var i=function(){return i=Object.assign||function(e){for(var t,i=1,n=arguments.length;i/g,">").replace(/0?this.element.scrollTop+r-s:e.offsetTop;requestAnimationFrame((function(){i._animateScroll(c,t)}))}},e.prototype._scrollDown=function(e,t,i){var n=(i-e)/t,s=n>1?n:1;this.element.scrollTop=e+s},e.prototype._scrollUp=function(e,t,i){var n=(e-i)/t,s=n>1?n:1;this.element.scrollTop=e-s},e.prototype._animateScroll=function(e,t){var i=this,n=this.element.scrollTop,s=!1;t>0?(this._scrollDown(n,4,e),ne&&(s=!0)),s&&requestAnimationFrame((function(){i._animateScroll(e,t)}))},e}(),C=function(){function e(e){var t=e.element,i=e.classNames;this.element=t,this.classNames=i,this.isDisabled=!1}return Object.defineProperty(e.prototype,"isActive",{get:function(){return"active"===this.element.dataset.choice},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dir",{get:function(){return this.element.dir},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.element.value},set:function(e){this.element.setAttribute("value",e),this.element.value=e},enumerable:!1,configurable:!0}),e.prototype.conceal=function(){var e;(e=this.element.classList).add.apply(e,d(this.classNames.input)),this.element.hidden=!0,this.element.tabIndex=-1;var t=this.element.getAttribute("style");t&&this.element.setAttribute("data-choice-orig-style",t),this.element.setAttribute("data-choice","active")},e.prototype.reveal=function(){var e;(e=this.element.classList).remove.apply(e,d(this.classNames.input)),this.element.hidden=!1,this.element.removeAttribute("tabindex");var t=this.element.getAttribute("data-choice-orig-style");t?(this.element.removeAttribute("data-choice-orig-style"),this.element.setAttribute("style",t)):this.element.removeAttribute("style"),this.element.removeAttribute("data-choice"),this.element.value=this.element.value},e.prototype.enable=function(){this.element.removeAttribute("disabled"),this.element.disabled=!1,this.isDisabled=!1},e.prototype.disable=function(){this.element.setAttribute("disabled",""),this.element.disabled=!0,this.isDisabled=!0},e.prototype.triggerEvent=function(e,t){!function(e,t,i){void 0===i&&(i=null);var n=new CustomEvent(t,{detail:i,bubbles:!0,cancelable:!0});e.dispatchEvent(n)}(this.element,e,t||{})},e}(),w=function(e){function i(){return null!==e&&e.apply(this,arguments)||this}return t(i,e),i}(C),I=function(e,t){return void 0===t&&(t=!0),void 0===e?t:!!e},S=function(e){if("string"==typeof e&&(e=e.split(" ").filter((function(e){return 0!==e.length}))),Array.isArray(e)&&0!==e.length)return e},O=function(e,t){if("string"==typeof e)return O({value:e,label:e},!1);var i=e;if("choices"in i){if(!t)throw new TypeError("optGroup is not allowed");var n=i,s=n.choices.map((function(e){return O(e,!1)}));return{id:0,label:l(n.label)||n.value,active:0!==s.length,disabled:!!n.disabled,choices:s}}var o=i;return{id:0,groupId:0,score:0,rank:0,value:o.value,label:o.label||o.value,active:I(o.active),selected:I(o.selected,!1),disabled:I(o.disabled,!1),placeholder:I(o.placeholder,!1),highlighted:!1,labelClass:S(o.labelClass),labelDescription:o.labelDescription,customProperties:o.customProperties}},A=function(e){function i(t){var i=t.element,n=t.classNames,s=t.template,o=t.extractPlaceholder,r=e.call(this,{element:i,classNames:n})||this;return r.template=s,r.extractPlaceholder=o,r}return t(i,e),Object.defineProperty(i.prototype,"placeholderOption",{get:function(){return this.element.querySelector('option[value=""]')||this.element.querySelector("option[placeholder]")},enumerable:!1,configurable:!0}),i.prototype.addOptions=function(e){var t=this;e.forEach((function(e){var i=e;if(!i.element){var n=t.template(i);t.element.appendChild(n),i.element=n}}))},i.prototype.optionsAsChoices=function(){var e=this,t=[];return this.element.querySelectorAll(":scope > option, :scope > optgroup").forEach((function(i){!function(e){return"OPTION"===e.tagName}(i)?function(e){return"OPTGROUP"===e.tagName}(i)&&t.push(e._optgroupToChoice(i)):t.push(e._optionToChoice(i))})),t},i.prototype._optionToChoice=function(e){return{id:0,groupId:0,score:0,rank:0,value:e.value,label:e.innerHTML,element:e,active:!0,selected:this.extractPlaceholder?e.selected:e.hasAttribute("selected"),disabled:e.disabled,highlighted:!1,placeholder:this.extractPlaceholder&&(""===e.value||e.hasAttribute("placeholder")),labelClass:void 0!==e.dataset.labelClass?S(e.dataset.labelClass):void 0,labelDescription:void 0!==e.dataset.labelDescription?e.dataset.labelDescription:void 0,customProperties:f(e.dataset.customProperties)}},i.prototype._optgroupToChoice=function(e){var t=this,i=e.querySelectorAll("option"),n=Array.from(i).map((function(e){return t._optionToChoice(e)}));return{id:0,label:e.label||"",element:e,active:0!==n.length,disabled:e.disabled,choices:n}},i}(C),x={items:[],choices:[],silent:!1,renderChoiceLimit:-1,maxItemCount:-1,singleModeForMultiSelect:!1,addChoices:!1,addItems:!0,addItemFilter:function(e){return!!e&&""!==e},removeItems:!0,removeItemButton:!1,removeItemButtonAlignLeft:!1,editItems:!1,allowHTML:!1,allowHtmlUserInput:!1,duplicateItemsAllowed:!0,delimiter:",",paste:!0,searchEnabled:!0,searchChoices:!0,searchFloor:1,searchResultLimit:4,searchFields:["label","value"],position:"auto",resetScrollPosition:!0,shouldSort:!0,shouldSortItems:!1,sorter:function(e,t){var i=e.value,n=e.label,s=void 0===n?i:n,o=t.value,r=t.label,c=void 0===r?o:r;return l(s).localeCompare(l(c),[],{sensitivity:"base",ignorePunctuation:!0,numeric:!0})},shadowRoot:null,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 "'.concat(e,'"')},removeItemIconText:function(){return"Remove item"},removeItemLabelText:function(e){return"Remove item: ".concat(e)},maxItemText:function(e){return"Only ".concat(e," values can be added")},valueComparer:function(e,t){return e===t},fuseOptions:{includeScore:!0},labelId:"",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"],description:["choices__description"],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"],selectedState:["is-selected"],flippedState:["is-flipped"],loadingState:["is-loading"],addChoice:["choices__item","choices__item--selectable","add-choice"],noResults:["has-no-results"],noChoices:["has-no-choices"]},appendGroupInSearch:!1},L=["fuseOptions","classNames"];function T(e){return"Minified Redux error #"+e+"; visit https://redux.js.org/Errors?code="+e+" for the full message or use the non-minified dev environment for full errors. "}var M="function"==typeof Symbol&&Symbol.observable||"@@observable",N=function(){return Math.random().toString(36).substring(7).split("").join(".")},F={INIT:"@@redux/INIT"+N(),REPLACE:"@@redux/REPLACE"+N(),PROBE_UNKNOWN_ACTION:function(){return"@@redux/PROBE_UNKNOWN_ACTION"+N()}};function j(e,t,i){var n;if("function"==typeof t&&"function"==typeof i||"function"==typeof i&&"function"==typeof arguments[3])throw new Error(T(0));if("function"==typeof t&&void 0===i&&(i=t,t=void 0),void 0!==i){if("function"!=typeof i)throw new Error(T(1));return i(j)(e,t)}if("function"!=typeof e)throw new Error(T(2));var s=e,o=t,r=[],c=r,a=!1;function h(){c===r&&(c=r.slice())}function l(){if(a)throw new Error(T(3));return o}function u(e){if("function"!=typeof e)throw new Error(T(4));if(a)throw new Error(T(5));var t=!0;return h(),c.push(e),function(){if(t){if(a)throw new Error(T(6));t=!1,h();var i=c.indexOf(e);c.splice(i,1),r=null}}}function d(e){if(!function(e){if("object"!=typeof e||null===e)return!1;for(var t=e;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}(e))throw new Error(T(7));if(void 0===e.type)throw new Error(T(8));if(a)throw new Error(T(9));try{a=!0,o=s(o,e)}finally{a=!1}for(var t=r=c,i=0;i0},e.prototype.getChoiceById=function(e){return this.activeChoices.find((function(t){return t.id===e}))},e.prototype.getGroupById=function(e){return this.groups.find((function(t){return t.id===e}))},e}(),H=function(e,t){return e?function(e){if("string"==typeof e)return e;if("object"==typeof e){if("escaped"in e)return e.escaped;if("trusted"in e)return e.trusted}return""}(t):a(t)},K=function(e,t){if(t){var i=e.dataset;"string"==typeof t?i.customProperties=t:"object"!=typeof t||function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}(t)||(i.customProperties=JSON.stringify(t))}},V={containerOuter:function(e,t,i,n,s,o,r){var c=e.classNames.containerOuter,a=Object.assign(document.createElement("div"),{className:d(c).join(" ")});return a.dataset.type=o,t&&(a.dir=t),n&&(a.tabIndex=0),i&&(a.setAttribute("role",s?"combobox":"listbox"),s&&a.setAttribute("aria-autocomplete","list")),a.setAttribute("aria-haspopup","true"),a.setAttribute("aria-expanded","false"),r&&a.setAttribute("aria-labelledby",r),a},containerInner:function(e){var t=e.classNames.containerInner;return Object.assign(document.createElement("div"),{className:d(t).join(" ")})},itemList:function(e,t){var i=e.classNames,n=i.list,s=i.listSingle,o=i.listItems;return Object.assign(document.createElement("div"),{className:"".concat(d(n).join(" ")," ").concat(t?d(s).join(" "):d(o).join(" "))})},placeholder:function(e,t){var i=e.allowHTML,n=e.classNames.placeholder;return Object.assign(document.createElement("div"),{className:d(n).join(" "),innerHTML:H(i,t)})},item:function(e,t,i){var n,s,o,r=e.allowHTML,c=e.removeItemButtonAlignLeft,h=e.classNames,l=h.item,u=h.button,p=h.highlightedState,f=h.itemSelectable,m=h.placeholder,g=t.id,v=t.value,_=t.label,y=t.labelClass,b=t.labelDescription,E=t.customProperties,C=t.active,w=t.disabled,I=t.highlighted,S=t.placeholder,O=Object.assign(document.createElement("div"),{className:d(l).join(" ")});if(y){var A=Object.assign(document.createElement("span"),{innerHTML:H(r,_),className:d(y).join(" ")});O.appendChild(A)}else O.innerHTML=H(r,_);if(Object.assign(O.dataset,{item:"",id:g,value:v}),y&&(O.dataset.labelClass=d(y).join(" ")),b&&(O.dataset.labelDescription=b),K(O,E),C&&O.setAttribute("aria-selected","true"),w&&O.setAttribute("aria-disabled","true"),S&&((n=O.classList).add.apply(n,d(m)),O.dataset.placeholder=""),(s=O.classList).add.apply(s,d(I?p:f)),i){w&&(o=O.classList).remove.apply(o,d(f)),O.dataset.deletable="";var x="function"==typeof this.config.removeItemIconText?this.config.removeItemIconText(a(v),v):this.config.removeItemIconText,L="function"==typeof this.config.removeItemLabelText?this.config.removeItemLabelText(a(v),v):this.config.removeItemLabelText,T=Object.assign(document.createElement("button"),{type:"button",className:d(u).join(" "),innerHTML:x});L&&T.setAttribute("aria-label",L),T.dataset.button="",c?O.insertAdjacentElement("afterbegin",T):O.appendChild(T)}return O},choiceList:function(e,t){var i=e.classNames.list,n=Object.assign(document.createElement("div"),{className:d(i).join(" ")});return t||n.setAttribute("aria-multiselectable","true"),n.setAttribute("role","listbox"),n},choiceGroup:function(e,t){var i=e.allowHTML,n=e.classNames,s=n.group,o=n.groupHeading,r=n.itemDisabled,c=t.id,a=t.label,h=t.disabled,l=Object.assign(document.createElement("div"),{className:"".concat(d(s).join(" ")," ").concat(h?d(r).join(" "):"")});return l.setAttribute("role","group"),Object.assign(l.dataset,{group:"",id:c,value:a}),h&&l.setAttribute("aria-disabled","true"),l.appendChild(Object.assign(document.createElement("div"),{className:d(o).join(" "),innerHTML:H(i,a)})),l},choice:function(e,t,i){var n,s,o,r,c,a=e.allowHTML,h=e.classNames,l=h.item,u=h.itemChoice,p=h.itemSelectable,f=h.selectedState,m=h.itemDisabled,g=h.description,v=h.placeholder,_=t.id,y=t.value,b=t.label,E=t.groupId,C=t.elementId,w=t.labelClass,I=t.labelDescription,S=t.disabled,O=t.selected,A=t.placeholder,x=Object.assign(document.createElement("div"),{id:C,className:"".concat(d(l).join(" ")," ").concat(d(u).join(" "))}),L=x;if(w){var T=Object.assign(document.createElement("span"),{innerHTML:H(a,b),className:d(w).join(" ")});L=T,x.appendChild(T)}else x.innerHTML=H(a,b);if(I){var M="".concat(C,"-description");L.setAttribute("aria-describedby",M);var N=Object.assign(document.createElement("span"),{innerHTML:H(a,I),id:M});(n=N.classList).add.apply(n,d(g)),x.appendChild(N)}return O&&(s=x.classList).add.apply(s,d(f)),A&&(o=x.classList).add.apply(o,d(v)),x.setAttribute("role",E&&E>0?"treeitem":"option"),Object.assign(x.dataset,{choice:"",id:_,value:y,selectText:i}),w&&(x.dataset.labelClass=d(w).join(" ")),I&&(x.dataset.labelDescription=I),S?((r=x.classList).add.apply(r,d(m)),x.dataset.choiceDisabled="",x.setAttribute("aria-disabled","true")):((c=x.classList).add.apply(c,d(p)),x.dataset.choiceSelectable=""),x},input:function(e,t){var i=e.classNames,n=i.input,s=i.inputCloned,o=Object.assign(document.createElement("input"),{type:"search",className:"".concat(d(n).join(" ")," ").concat(d(s).join(" ")),autocomplete:"off",autocapitalize:"off",spellcheck:!1});return o.setAttribute("role","textbox"),o.setAttribute("aria-autocomplete","list"),t&&o.setAttribute("aria-label",t),o},dropdown:function(e){var t,i,n=e.classNames,s=n.list,o=n.listDropdown,r=document.createElement("div");return(t=r.classList).add.apply(t,d(s)),(i=r.classList).add.apply(i,d(o)),r.setAttribute("aria-expanded","false"),r},notice:function(e,t,i){var s=e.allowHTML,o=e.classNames,r=o.item,c=o.itemChoice,a=o.addChoice,h=o.noResults,l=o.noChoices;void 0===i&&(i="");var u=n(n([],d(r),!0),d(c),!0);switch(i){case"add-choice":u.push.apply(u,d(a));break;case"no-results":u.push.apply(u,d(h));break;case"no-choices":u.push.apply(u,d(l))}var p=Object.assign(document.createElement("div"),{innerHTML:H(s,t),className:u.join(" ")});return"add-choice"===i&&(p.dataset.choiceSelectable="",p.dataset.choice=""),p},option:function(e){var t=e.label,i=e.value,n=e.labelClass,s=e.labelDescription,o=e.customProperties,r=e.active,c=e.disabled,a=l(t),h=new Option(a,i,!1,r);return n&&(h.dataset.labelClass=d(n).join(" ")),s&&(h.dataset.labelDescription=s),K(h,o),h.disabled=c,h}};function B(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function $(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function U(e){for(var t=1;t`Missing ${e} property in key`,ie=e=>`Property 'weight' in key '${e}' must be a positive integer`,ne=Object.prototype.hasOwnProperty;class se{constructor(e){this._keys=[],this._keyMap={};let t=0;e.forEach((e=>{let i=oe(e);this._keys.push(i),this._keyMap[i.id]=i,t+=i.weight})),this._keys.forEach((e=>{e.weight/=t}))}get(e){return this._keyMap[e]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function oe(e){let t=null,i=null,n=null,s=1,o=null;if(X(e)||q(e))n=e,t=re(e),i=ce(e);else{if(!ne.call(e,"name"))throw new Error(te("name"));const r=e.name;if(n=r,ne.call(e,"weight")&&(s=e.weight,s<=0))throw new Error(ie(r));t=re(r),i=ce(r),o=e.getFn}return{path:t,id:i,weight:s,src:n,getFn:o}}function re(e){return q(e)?e:e.split(".")}function ce(e){return q(e)?e.join("."):e}const ae={useExtendedSearch:!1,getFn:function(e,t){let i=[],n=!1;const s=(e,t,o)=>{if(Y(e))if(t[o]){const r=e[t[o]];if(!Y(r))return;if(o===t.length-1&&(X(r)||J(r)||z(r)))i.push(G(r));else if(q(r)){n=!0;for(let e=0,i=r.length;ee.score===t.score?e.idx{this._keysMap[e.id]=t}))}create(){!this.isCreated&&this.docs.length&&(this.isCreated=!0,X(this.docs[0])?this.docs.forEach(((e,t)=>{this._addString(e,t)})):this.docs.forEach(((e,t)=>{this._addObject(e,t)})),this.norm.clear())}add(e){const t=this.size();X(e)?this._addString(e,t):this._addObject(e,t)}removeAt(e){this.records.splice(e,1);for(let t=e,i=this.size();t{let s=t.getFn?t.getFn(e):this.getFn(e,t.path);if(Y(s))if(q(s)){let e=[];const t=[{nestedArrIndex:-1,value:s}];for(;t.length;){const{nestedArrIndex:i,value:n}=t.pop();if(Y(n))if(X(n)&&!Z(n)){let t={v:n,i:i,n:this.norm.get(n)};e.push(t)}else q(n)&&n.forEach(((e,i)=>{t.push({nestedArrIndex:i,value:e})}))}i.$[n]=e}else if(X(s)&&!Z(s)){let e={v:s,n:this.norm.get(s)};i.$[n]=e}})),this.records.push(i)}toJSON(){return{keys:this.keys,records:this.records}}}function de(e,t,{getFn:i=he.getFn,fieldNormWeight:n=he.fieldNormWeight}={}){const s=new ue({getFn:i,fieldNormWeight:n});return s.setKeys(e.map(oe)),s.setSources(t),s.create(),s}function pe(e,{errors:t=0,currentLocation:i=0,expectedLocation:n=0,distance:s=he.distance,ignoreLocation:o=he.ignoreLocation}={}){const r=t/e.length;if(o)return r;const c=Math.abs(n-i);return s?r+c/s:c?1:r}const fe=32;function me(e,t,i,{location:n=he.location,distance:s=he.distance,threshold:o=he.threshold,findAllMatches:r=he.findAllMatches,minMatchCharLength:c=he.minMatchCharLength,includeMatches:a=he.includeMatches,ignoreLocation:h=he.ignoreLocation}={}){if(t.length>fe)throw new Error(`Pattern length exceeds max of ${fe}.`);const l=t.length,u=e.length,d=Math.max(0,Math.min(n,u));let p=o,f=d;const m=c>1||a,g=m?Array(u):[];let v;for(;(v=e.indexOf(t,f))>-1;){let e=pe(t,{currentLocation:v,expectedLocation:d,distance:s,ignoreLocation:h});if(p=Math.min(e,p),f=v+l,m){let e=0;for(;e=a;o-=1){let r=o-1,c=i[e.charAt(r)];if(m&&(g[r]=+!!c),C[o]=(C[o+1]<<1|1)&c,n&&(C[o]|=(_[o+1]|_[o])<<1|1|_[o+1]),C[o]&E&&(y=pe(t,{errors:n,currentLocation:r,expectedLocation:d,distance:s,ignoreLocation:h}),y<=p)){if(p=y,f=r,f<=d)break;a=Math.max(1,2*d-f)}}if(pe(t,{errors:n+1,currentLocation:d,expectedLocation:d,distance:s,ignoreLocation:h})>p)break;_=C}const C={isMatch:f>=0,score:Math.max(.001,y)};if(m){const e=function(e=[],t=he.minMatchCharLength){let i=[],n=-1,s=-1,o=0;for(let r=e.length;o=t&&i.push([n,s]),n=-1)}return e[o-1]&&o-n>=t&&i.push([n,o-1]),i}(g,c);e.length?a&&(C.indices=e):C.isMatch=!1}return C}function ge(e){let t={};for(let i=0,n=e.length;i{this.chunks.push({pattern:e,alphabet:ge(e),startIndex:t})},l=this.pattern.length;if(l>fe){let e=0;const t=l%fe,i=l-t;for(;e{const{isMatch:f,score:m,indices:g}=me(e,t,d,{location:n+p,distance:s,threshold:o,findAllMatches:r,minMatchCharLength:c,includeMatches:i,ignoreLocation:a});f&&(u=!0),l+=m,f&&g&&(h=[...h,...g])}));let d={isMatch:u,score:u?l/this.chunks.length:1};return u&&i&&(d.indices=h),d}}class _e{constructor(e){this.pattern=e}static isMultiMatch(e){return ye(e,this.multiRegex)}static isSingleMatch(e){return ye(e,this.singleRegex)}search(){}}function ye(e,t){const i=e.match(t);return i?i[1]:null}class be extends _e{constructor(e,{location:t=he.location,threshold:i=he.threshold,distance:n=he.distance,includeMatches:s=he.includeMatches,findAllMatches:o=he.findAllMatches,minMatchCharLength:r=he.minMatchCharLength,isCaseSensitive:c=he.isCaseSensitive,ignoreLocation:a=he.ignoreLocation}={}){super(e),this._bitapSearch=new ve(e,{location:t,threshold:i,distance:n,includeMatches:s,findAllMatches:o,minMatchCharLength:r,isCaseSensitive:c,ignoreLocation:a})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(e){return this._bitapSearch.searchIn(e)}}class Ee extends _e{constructor(e){super(e)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(e){let t,i=0;const n=[],s=this.pattern.length;for(;(t=e.indexOf(this.pattern,i))>-1;)i=t+s,n.push([t,i-1]);const o=!!n.length;return{isMatch:o,score:o?0:1,indices:n}}}const Ce=[class extends _e{constructor(e){super(e)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(e){const t=e===this.pattern;return{isMatch:t,score:t?0:1,indices:[0,this.pattern.length-1]}}},Ee,class extends _e{constructor(e){super(e)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(e){const t=e.startsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,this.pattern.length-1]}}},class extends _e{constructor(e){super(e)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(e){const t=!e.startsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}},class extends _e{constructor(e){super(e)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(e){const t=!e.endsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}},class extends _e{constructor(e){super(e)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(e){const t=e.endsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[e.length-this.pattern.length,e.length-1]}}},class extends _e{constructor(e){super(e)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(e){const t=-1===e.indexOf(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}},be],we=Ce.length,Ie=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/;const Se=new Set([be.type,Ee.type]);class Oe{constructor(e,{isCaseSensitive:t=he.isCaseSensitive,includeMatches:i=he.includeMatches,minMatchCharLength:n=he.minMatchCharLength,ignoreLocation:s=he.ignoreLocation,findAllMatches:o=he.findAllMatches,location:r=he.location,threshold:c=he.threshold,distance:a=he.distance}={}){this.query=null,this.options={isCaseSensitive:t,includeMatches:i,minMatchCharLength:n,findAllMatches:o,ignoreLocation:s,location:r,threshold:c,distance:a},this.pattern=t?e:e.toLowerCase(),this.query=function(e,t={}){return e.split("|").map((e=>{let i=e.trim().split(Ie).filter((e=>e&&!!e.trim())),n=[];for(let e=0,s=i.length;e!(!e[Le]&&!e[Te]),je=e=>({[Le]:Object.keys(e).map((t=>({[t]:e[t]})))});function De(e,t,{auto:i=!0}={}){const n=e=>{let s=Object.keys(e);const o=(e=>!!e[Me])(e);if(!o&&s.length>1&&!Fe(e))return n(je(e));if((e=>!q(e)&&Q(e)&&!Fe(e))(e)){const n=o?e[Me]:s[0],r=o?e[Ne]:e[n];if(!X(r))throw new Error((e=>`Invalid value for key ${e}`)(n));const c={keyId:ce(n),pattern:r};return i&&(c.searcher=xe(r,t)),c}let r={children:[],operator:s[0]};return s.forEach((t=>{const i=e[t];q(i)&&i.forEach((e=>{r.children.push(n(e))}))})),r};return Fe(e)||(e=je(e)),n(e)}function Pe(e,t){const i=e.matches;t.matches=[],Y(i)&&i.forEach((e=>{if(!Y(e.indices)||!e.indices.length)return;const{indices:i,value:n}=e;let s={indices:i,value:n};e.key&&(s.key=e.key.src),e.idx>-1&&(s.refIndex=e.idx),t.matches.push(s)}))}function ke(e,t){t.score=e.score}class Re{constructor(e,t={},i){this.options=U(U({},he),t),this.options.useExtendedSearch,this._keyStore=new se(this.options.keys),this.setCollection(e,i)}setCollection(e,t){if(this._docs=e,t&&!(t instanceof ue))throw new Error("Incorrect 'index' type");this._myIndex=t||de(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(e){Y(e)&&(this._docs.push(e),this._myIndex.add(e))}remove(e=()=>!1){const t=[];for(let i=0,n=this._docs.length;i{let i=1;e.matches.forEach((({key:e,norm:n,score:s})=>{const o=e?e.weight:null;i*=Math.pow(0===s&&o?Number.EPSILON:s,(o||1)*(t?1:n))})),e.score=i}))}(c,{ignoreFieldNorm:r}),s&&c.sort(o),J(t)&&t>-1&&(c=c.slice(0,t)),function(e,t,{includeMatches:i=he.includeMatches,includeScore:n=he.includeScore}={}){const s=[];return i&&s.push(Pe),n&&s.push(ke),e.map((e=>{const{idx:i}=e,n={item:t[i],refIndex:i};return s.length&&s.forEach((t=>{t(e,n)})),n}))}(c,this._docs,{includeMatches:i,includeScore:n})}_searchStringList(e){const t=xe(e,this.options),{records:i}=this._myIndex,n=[];return i.forEach((({v:e,i:i,n:s})=>{if(!Y(e))return;const{isMatch:o,score:r,indices:c}=t.searchIn(e);o&&n.push({item:e,idx:i,matches:[{score:r,value:e,norm:s,indices:c}]})})),n}_searchLogical(e){const t=De(e,this.options),i=(e,t,n)=>{if(!e.children){const{keyId:i,searcher:s}=e,o=this._findMatches({key:this._keyStore.get(i),value:this._myIndex.getValueForItemAtKeyId(t,i),searcher:s});return o&&o.length?[{idx:n,item:t,matches:o}]:[]}const s=[];for(let o=0,r=e.children.length;o{if(Y(e)){let r=i(t,e,n);r.length&&(s[n]||(s[n]={idx:n,item:e,matches:[]},o.push(s[n])),r.forEach((({matches:e})=>{s[n].matches.push(...e)})))}})),o}_searchObjectList(e){const t=xe(e,this.options),{keys:i,records:n}=this._myIndex,s=[];return n.forEach((({$:e,i:n})=>{if(!Y(e))return;let o=[];i.forEach(((i,n)=>{o.push(...this._findMatches({key:i,value:e[n],searcher:t}))})),o.length&&s.push({idx:n,item:e,matches:o})})),s}_findMatches({key:e,value:t,searcher:i}){if(!Y(t))return[];let n=[];if(q(t))t.forEach((({v:t,i:s,n:o})=>{if(!Y(t))return;const{isMatch:r,score:c,indices:a}=i.searchIn(t);r&&n.push({score:c,key:e,value:t,idx:s,norm:o,indices:a})}));else{const{v:s,n:o}=t,{isMatch:r,score:c,indices:a}=i.searchIn(s);r&&n.push({score:c,key:e,value:s,norm:o,indices:a})}return n}}Re.version="7.0.0",Re.createIndex=de,Re.parseIndex=function(e,{getFn:t=he.getFn,fieldNormWeight:i=he.fieldNormWeight}={}){const{keys:n,records:s}=e,o=new ue({getFn:t,fieldNormWeight:i});return o.setKeys(n),o.setIndexRecords(s),o},Re.config=he,Re.parseQuery=De,function(...e){Ae.push(...e)}(Oe);var He=function(){function e(e){this._haystack=[],this._fuseOptions=i(i({},e.fuseOptions),{keys:n([],e.searchFields,!0),includeMatches:!0})}return e.prototype.index=function(e){this._haystack=e,this._fuse&&this._fuse.setCollection(e)},e.prototype.reset=function(){this._haystack=[],this._fuse=void 0},e.prototype.isEmptyIndex=function(){return 0===this._haystack.length},e.prototype.search=function(e){return this._fuse||(this._fuse=new Re(this._haystack,this._fuseOptions)),this._fuse.search(e).map((function(e,t){return{item:e.item,score:e.score||0,rank:t}}))},e}();var Ke="-ms-scroll-limit"in document.documentElement.style&&"-ms-ime-align"in document.documentElement.style,Ve={},Be=function(e){if(e){var t=e.dataset.id;return t?parseInt(t,10):void 0}},$e=function(){function e(t,n){void 0===t&&(t="[data-choice]"),void 0===n&&(n={});var s=this;this.initialisedOK=void 0,this._hasNonChoicePlaceholder=!1,this._lastAddedChoiceId=0,this._lastAddedGroupId=0,this.config=i(i(i({},e.defaults.allOptions),e.defaults.options),n),L.forEach((function(t){s.config[t]=i(i(i({},e.defaults.allOptions[t]),e.defaults.options[t]),n[t])})),this.config.silent||this._validateConfig();var o=this.config.shadowRoot||document.documentElement,r="string"==typeof t?o.querySelector(t):t;if(!r||"object"!=typeof r||"INPUT"!==r.tagName&&!function(e){return"SELECT"===e.tagName}(r)){if(!r&&"string"==typeof t)throw TypeError("Selector ".concat(t," failed to find an element"));throw TypeError("Expected one of the following types text|select-one|select-multiple")}if(this._elementType=r.type,this._isTextElement=this._elementType===g,(this._isTextElement||1!==this.config.maxItemCount)&&(this.config.singleModeForMultiSelect=!1),this.config.singleModeForMultiSelect&&(this._elementType=_),this._isSelectOneElement=this._elementType===v,this._isSelectMultipleElement=this._elementType===_,this._isSelectElement=this._isSelectOneElement||this._isSelectMultipleElement,this._canAddUserChoices=this._isTextElement&&this.config.addItems||this._isSelectElement&&this.config.addChoices,["auto","always"].includes("".concat(this.config.renderSelectedChoices))||(this.config.renderSelectedChoices="auto"),this.config.placeholder&&(this.config.placeholderValue?this._hasNonChoicePlaceholder=!0:r.dataset.placeholder&&(this._hasNonChoicePlaceholder=!0,this.config.placeholderValue=r.dataset.placeholder)),n.addItemFilter&&"function"!=typeof n.addItemFilter){var a=n.addItemFilter instanceof RegExp?n.addItemFilter:new RegExp(n.addItemFilter);this.config.addItemFilter=a.test.bind(a)}if(this._isTextElement)this.passedElement=new w({element:r,classNames:this.config.classNames});else{var h=r;this.passedElement=new A({element:h,classNames:this.config.classNames,template:function(e){return s._templates.option(e)},extractPlaceholder:this.config.placeholder&&!this._hasNonChoicePlaceholder})}if(this.initialised=!1,this._store=new R,this._initialState=D,this._currentState=D,this._prevState=D,this._currentValue="",this.config.searchEnabled=!this._isTextElement&&this.config.searchEnabled||this._elementType===_,this._canSearch=this.config.searchEnabled,this._isScrollingOnIe=!1,this._highlightPosition=0,this._wasTap=!0,this._placeholderValue=this._generatePlaceholderValue(),this._baseId=function(e,t){var i=e.id||e.name&&"".concat(e.name,"-").concat(c(2))||c(4);return i=i.replace(/(:|\.|\[|\]|,)/g,""),"".concat(t,"-").concat(i)}(this.passedElement.element,"choices-"),this._direction=this.passedElement.dir,!this._direction){var l=window.getComputedStyle(this.passedElement.element).direction;l!==window.getComputedStyle(document.documentElement).direction&&(this._direction=l)}if(this._idNames={itemChoice:"item-choice"},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._onInput=this._onInput.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._onSelectKey=this._onSelectKey.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.passedElement.isActive)return this.config.silent||console.warn("Trying to initialise Choices on element already initialised",{element:t}),this.initialised=!0,void(this.initialisedOK=!1);this.init(),this._initialItems=this._store.items.map((function(e){return e.value}))}return Object.defineProperty(e,"defaults",{get:function(){return Object.preventExtensions({get options(){return Ve},get allOptions(){return x},get templates(){return V}})},enumerable:!1,configurable:!0}),e.prototype.init=function(){if(!this.initialised&&void 0===this.initialisedOK){var e;this._searcher=(e=this.config,new He(e)),this._loadChoices(),this._createTemplates(),this._createElements(),this._createStructure(),this._store.subscribe(this._render),this._render(),this._addEventListeners(),(this._isTextElement&&!this.config.addItems||this.passedElement.element.hasAttribute("disabled")||!!this.passedElement.element.closest("fieldset:disabled"))&&this.disable(),this.initialised=!0,this.initialisedOK=!0;var t=this.config.callbackOnInit;t&&"function"==typeof t&&t.call(this)}},e.prototype.destroy=function(){this.initialised&&(this._removeEventListeners(),this.passedElement.reveal(),this.containerOuter.unwrap(this.passedElement.element),this.clearStore(),this._stopSearch(),this._templates=V,this.initialised=!1,this.initialisedOK=void 0)},e.prototype.enable=function(){return this.passedElement.isDisabled&&this.passedElement.enable(),this.containerOuter.isDisabled&&(this._addEventListeners(),this.input.enable(),this.containerOuter.enable()),this},e.prototype.disable=function(){return this.passedElement.isDisabled||this.passedElement.disable(),this.containerOuter.isDisabled||(this._removeEventListeners(),this.input.disable(),this.containerOuter.disable()),this},e.prototype.highlightItem=function(e,t){if(void 0===t&&(t=!0),!e||!e.id)return this;var i=this._store.choices.find((function(t){return t.id===e.id}));return!i||i.highlighted||(this._store.dispatch(o(i,!0)),t&&this.passedElement.triggerEvent("highlightItem",this._getChoiceForOutput(i))),this},e.prototype.unhighlightItem=function(e,t){if(void 0===t&&(t=!0),!e||!e.id)return this;var i=this._store.choices.find((function(t){return t.id===e.id}));return i&&i.highlighted?(this._store.dispatch(o(i,!1)),t&&this.passedElement.triggerEvent("highlightItem",this._getChoiceForOutput(i)),this):this},e.prototype.highlightAll=function(){var e=this;return this._store.withTxn((function(){e._store.items.forEach((function(t){return e.highlightItem(t)}))})),this},e.prototype.unhighlightAll=function(){var e=this;return this._store.withTxn((function(){e._store.items.forEach((function(t){return e.unhighlightItem(t)}))})),this},e.prototype.removeActiveItemsByValue=function(e){var t=this;return this._store.withTxn((function(){t._store.items.filter((function(t){return t.value===e})).forEach((function(e){return t._removeItem(e)}))})),this},e.prototype.removeActiveItems=function(e){var t=this;return this._store.withTxn((function(){t._store.items.filter((function(t){return t.id!==e})).forEach((function(e){return t._removeItem(e)}))})),this},e.prototype.removeHighlightedItems=function(e){var t=this;return void 0===e&&(e=!1),this._store.withTxn((function(){t._store.highlightedActiveItems.forEach((function(i){t._removeItem(i),e&&t._triggerChange(i.value)}))})),this},e.prototype.showDropdown=function(e){var t=this;return this.dropdown.isActive||requestAnimationFrame((function(){t.dropdown.show(),t.containerOuter.open(t.dropdown.distanceFromTopWindow),!e&&t._canSearch&&t.input.focus(),t.passedElement.triggerEvent("showDropdown")})),this},e.prototype.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("hideDropdown")})),this):this},e.prototype.getValue=function(e){var t=this;void 0===e&&(e=!1);var i=this._store.items.reduce((function(i,n){var s=e?n.value:t._getChoiceForOutput(n);return i.push(s),i}),[]);return this._isSelectOneElement||this.config.singleModeForMultiSelect?i[0]:i},e.prototype.setValue=function(e){var t=this;return this.initialisedOK?(this._store.withTxn((function(){e.forEach((function(e){e&&t._addChoice(O(e,!1))}))})),this._searcher.reset(),this):(this._warnChoicesInitFailed("setValue"),this)},e.prototype.setChoiceByValue=function(e){var t=this;return this.initialisedOK?(this._isTextElement||(this._store.withTxn((function(){(Array.isArray(e)?e:[e]).forEach((function(e){return t._findAndSelectChoiceByValue(e)}))})),this._searcher.reset()),this):(this._warnChoicesInitFailed("setChoiceByValue"),this)},e.prototype.setChoices=function(e,t,n,s){var o=this;if(void 0===e&&(e=[]),void 0===t&&(t="value"),void 0===n&&(n="label"),void 0===s&&(s=!1),!this.initialisedOK)return this._warnChoicesInitFailed("setChoices"),this;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(s&&this.clearChoices(),"function"==typeof e){var r=e(this);if("function"==typeof Promise&&r instanceof Promise)return new Promise((function(e){return requestAnimationFrame(e)})).then((function(){return o._handleLoadingState(!0)})).then((function(){return r})).then((function(e){return o.setChoices(e,t,n,s)})).catch((function(e){o.config.silent||console.error(e)})).then((function(){return o._handleLoadingState(!1)})).then((function(){return o}));if(!Array.isArray(r))throw new TypeError(".setChoices first argument function must return either array of choices or Promise, got: ".concat(typeof r));return this.setChoices(r,t,n,!1)}if(!Array.isArray(e))throw new TypeError(".setChoices must be called either with array of choices with a function resulting into Promise of array of choices");return this.containerOuter.removeLoadingState(),this._store.withTxn((function(){var s="value"===t,r="label"===n;e.forEach((function(e){if("choices"in e){var c=e;r||(c=i(i({},c),{label:c[n]})),o._addGroup(O(c,!0))}else{var a=e;r&&s||(a=i(i({},a),{value:a[t],label:a[n]})),o._addChoice(O(a,!1))}}))})),this._searcher.reset(),this},e.prototype.refresh=function(e,t,i){var n=this;return void 0===e&&(e=!1),void 0===t&&(t=!1),void 0===i&&(i=!1),this._isSelectElement?(this._store.withTxn((function(){var s=n.passedElement.optionsAsChoices(),o=n._store.items,r={};i||o.forEach((function(e){e.id&&e.active&&e.selected&&!e.disabled&&(r[e.value]=!0)})),s.forEach((function(e){if(!("choices"in e)){var t=e;i?t.selected=!1:r[t.value]&&(t.selected=!0)}})),n.clearStore(),n._addPredefinedChoices(s,t,e),n._isSearching&&n._searchChoices(n.input.value)})),this):(this.config.silent||console.warn("refresh method can only be used on choices backed by a element"),this)},e.prototype.removeChoice=function(e){var t=this._store.choices.find((function(t){return t.value===e}));return t?(this._store.dispatch(function(e){return{type:"REMOVE_CHOICE",choice:e}}(t)),this._searcher.reset(),t.selected&&this.passedElement.triggerEvent("removeItem",this._getChoiceForOutput(t)),this):this},e.prototype.clearChoices=function(){return this.passedElement.element.innerHTML="",this._store.dispatch({type:"CLEAR_CHOICES"}),this._searcher.reset(),this},e.prototype.clearStore=function(){return this._store.resetStore(),this._lastAddedChoiceId=0,this._lastAddedGroupId=0,this._searcher.reset(),this},e.prototype.clearInput=function(){var e=!this._isSelectOneElement;return this.input.clear(e),this._isSearching&&this._stopSearch(),this},e.prototype._validateConfig=function(){var e,t,i,n,s=(e=this.config,t=x,i=Object.keys(e).sort(),n=Object.keys(t).sort(),i.filter((function(e){return n.indexOf(e)<0})));s.length&&console.warn("Unknown config option(s) passed",s.join(", ")),this.config.allowHTML&&this.config.allowHtmlUserInput&&(this.config.addItems&&console.warn("Warning: allowHTML/allowHtmlUserInput/addItems all being true is strongly not recommended and may lead to XSS attacks"),this.config.addChoices&&console.warn("Warning: allowHTML/allowHtmlUserInput/addChoices all being true is strongly not recommended and may lead to XSS attacks"))},e.prototype._render=function(e){if(!this._store.inTxn()){var t=null==e?void 0:e.items;((null==e?void 0:e.choices)||(null==e?void 0:e.groups)||t)&&(this._isSelectElement&&this._renderChoices(),t&&this._renderItems())}},e.prototype._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){if(!this._hasNonChoicePlaceholder){var o=n.filter((function(e){return e.placeholder&&-1===e.groupId}));o.length>=1&&(s=this._createChoicesFragment(o,s))}s=this._createGroupsFragment(i,n,s)}else n.length>=1&&(s=this._createChoicesFragment(n,s));var r=this.input.value,c=this._canAddItem(this._store.items,r);if(s.childNodes&&s.childNodes.length>0){var a=!c.response;if(c.response&&(this.choiceList.append(s),this._highlightChoice(),this._canAddUserChoices&&r&&c.notice&&(a=!n.find((function(t){return e.config.valueComparer(t.value,r)})))),a){var h=this._templates.notice(this.config,c.notice,this._canAddUserChoices?"add-choice":"");this.choiceList.prepend(h)}}else{var l=void 0;if(c.response&&this._canAddUserChoices&&r)l=this._templates.notice(this.config,c.notice,"add-choice");else if(this._isSearching){h="function"==typeof this.config.noResultsText?this.config.noResultsText():this.config.noResultsText;l=this._templates.notice(this.config,h,"no-results")}else{h="function"==typeof this.config.noChoicesText?this.config.noChoicesText():this.config.noChoicesText;l=this._templates.notice(this.config,h,"no-choices")}this.choiceList.append(l)}},e.prototype._renderItems=function(){var e=this._store.items||[];this.itemList.clear();var t=this._createItemsFragment(e);t.childNodes&&this.itemList.append(t)},e.prototype._createGroupsFragment=function(e,t,i){var n=this;void 0===i&&(i=document.createDocumentFragment());this.config.shouldSort&&e.sort(this.config.sorter);var s=t.filter((function(e){return 0===e.groupId}));return s.length>0&&this._createChoicesFragment(s,i,!1),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 o=n._templates.choiceGroup(n.config,e);i.appendChild(o),n._createChoicesFragment(s,i,!0)}})),i},e.prototype._createChoicesFragment=function(e,t,i){var s=this;void 0===t&&(t=document.createDocumentFragment()),void 0===i&&(i=!1);var o=this.config,r=o.renderSelectedChoices,c=o.searchResultLimit,a=o.renderChoiceLimit,h=[],u=this.config.appendGroupInSearch&&this._isSearching;u&&this._store.groups.forEach((function(e){h[e.id]=e.label}));var d=function(e){if("auto"!==r||(s._isSelectOneElement||!e.selected)){var i=s._templates.choice(s.config,e,s.config.itemSelectText);if(u&&e.groupId>0){var n=h[e.groupId];n&&(i.innerHTML+=" (".concat(n,")"))}t.appendChild(i)}},p=e;if("auto"!==r||this._isSelectOneElement||(p=e.filter((function(e){return!e.selected}))),this._isSelectElement){var f=e.filter((function(e){return!e.element}));0!==f.length&&this.passedElement.addOptions(f)}var m=[],g=[];this._hasNonChoicePlaceholder?g=p:p.forEach((function(e){e.placeholder?m.push(e):g.push(e)})),this._isSearching?g.sort(l):this.config.shouldSort&&g.sort(this.config.sorter);var v=p.length,_=this._isSelectOneElement&&0!==m.length?n(n([],m,!0),g,!0):g;this._isSearching?v=c:a&&a>0&&!i&&(v=a);for(var y=0;y0?this._store.getGroupById(e.groupId):null;return{id:e.id,highlighted:e.highlighted,labelClass:e.labelClass,labelDescription:e.labelDescription,customProperties:e.customProperties,disabled:e.disabled,active:e.active,label:e.label,placeholder:e.placeholder,value:e.value,groupValue:i&&i.label?i.label:void 0,element:e.element,keyCode:t}}},e.prototype._triggerChange=function(e){null!=e&&this.passedElement.triggerEvent("change",{value:e})},e.prototype._handleButtonAction=function(e,t){if(0!==e.length&&this.config.removeItems&&this.config.removeItemButton){var i=t&&De(t.parentNode),n=i&&e.find((function(e){return e.id===i}));if(n&&(this._removeItem(n),this._triggerChange(n.value),this._isSelectOneElement&&!this._hasNonChoicePlaceholder)){var s=this._store.choices.reverse().find((function(e){return!e.disabled&&e.placeholder}));s&&(this._addItem(s),s.value&&this._triggerChange(s.value))}}},e.prototype._handleItemAction=function(e,t,i){var n=this;if(void 0===i&&(i=!1),0!==e.length&&this.config.removeItems&&!this._isSelectOneElement){var s=De(t);s&&(e.forEach((function(e){e.id!==s||e.highlighted?!i&&e.highlighted&&n.unhighlightItem(e):n.highlightItem(e)})),this.input.focus())}},e.prototype._handleChoiceAction=function(e,t,i){var n=this,s=De(t),o=s&&this._store.getChoiceById(s);if(!o)return!1;var r=this.dropdown.isActive,c=!1;return this._store.withTxn((function(){if(!o.selected&&!o.disabled&&n._canAddItem(e,o.value).response){if(n.config.singleModeForMultiSelect&&0!==e.length){var t=e[e.length-1];n._removeItem(t)}n.passedElement.triggerEvent("choice",n._getChoiceForOutput(o,i)),n._addItem(o),n.clearInput(),c=!0}})),!!c&&(this._triggerChange(o.value),r&&(this.config.singleModeForMultiSelect||this._isSelectOneElement)&&(this.hideDropdown(!0),this.containerOuter.focus()),!0)},e.prototype._handleBackspace=function(e){if(this.config.removeItems&&0!==e.length){var t=e[e.length-1],i=e.some((function(e){return e.highlighted}));this.config.editItems&&!i&&t?(this.input.value=t.value,this.input.setWidth(),this._removeItem(t),this._triggerChange(t.value)):(i||this.highlightItem(t,!1),this.removeHighlightedItems(!0))}},e.prototype._loadChoices=function(){var e;if(this._isTextElement){this._presetChoices=this.config.items.map((function(e){return w(e,!1)}));var t=this.passedElement.value;if(t){var i=t.split(this.config.delimiter).map((function(e){return w(e,!1)}));this._presetChoices=this._presetChoices.concat(i)}this._presetChoices.forEach((function(e){e.selected=!0}))}else if(this._isSelectElement){this._presetChoices=this.config.choices.map((function(e){return w(e,!0)}));var n=this.passedElement.optionsAsChoices();n&&(e=this._presetChoices).push.apply(e,n)}},e.prototype._handleLoadingState=function(e){void 0===e&&(e=!0);var t=this.itemList.element.querySelector(d(this.config.classNames.placeholder));e?(this.disable(),this.containerOuter.addLoadingState(),this._isSelectOneElement?t?t.innerHTML=this.config.loadingText:(t=this._templates.placeholder(this.config,this.config.loadingText))&&this.itemList.append(t):this.input.placeholder=this.config.loadingText):(this.enable(),this.containerOuter.removeLoadingState(),this._isSelectOneElement?t&&(t.innerHTML=this._placeholderValue||""):this.input.placeholder=this._placeholderValue||"")},e.prototype._handleSearch=function(e){if(this.input.isFocussed){var t=this._store.choices,i=this.config,n=i.searchFloor,s=i.searchChoices,o=t.some((function(e){return!e.active}));if(null!=e&&e.length>=n){var r=s?this._searchChoices(e):0;null!==r&&this.passedElement.triggerEvent("search",{value:e,resultCount:r})}else o&&this._stopSearch()}},e.prototype._canAddItem=function(e,t){var i=this,n=!0,s="";(this.config.maxItemCount>0&&this.config.maxItemCount<=e.length&&(this.config.singleModeForMultiSelect||(n=!1,s="function"==typeof this.config.maxItemText?this.config.maxItemText(this.config.maxItemCount):this.config.maxItemText)),n&&this._canAddUserChoices&&""!==t&&"function"==typeof this.config.addItemFilter&&!this.config.addItemFilter(t)&&(n=!1,s="function"==typeof this.config.customAddItemText?this.config.customAddItemText(c(t),t):this.config.customAddItemText),!n||""===t||!this._isSelectElement&&this.config.duplicateItemsAllowed)||this._store.items.find((function(e){return i.config.valueComparer(e.value,t)}))&&(n=!1,s="function"==typeof this.config.uniqueItemText?this.config.uniqueItemText(c(t),t):this.config.uniqueItemText);return n&&(s="function"==typeof this.config.addItemText?this.config.addItemText(c(t),t):this.config.addItemText),{response:n,notice:{trusted:s}}},e.prototype._searchChoices=function(e){var t=e.trim().replace(/\s{2,}/," ");if(0===t.length||t===this._currentValue)return null;var i=this._searcher;i.isEmptyIndex()&&i.index(this._store.searchableChoices);var n=i.search(t);return this._currentValue=t,this._highlightPosition=0,this._isSearching=!0,this._store.dispatch(function(e){return{type:"FILTER_CHOICES",results:e}}(n)),n.length},e.prototype._stopSearch=function(){var e=this._isSearching;this._currentValue="",this._isSearching=!1,e&&this._store.dispatch({type:"ACTIVATE_CHOICES",active:!0})},e.prototype._addEventListeners=function(){var e=this.config.shadowRoot||document.documentElement;e.addEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.addEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.addEventListener("mousedown",this._onMouseDown,!0),e.addEventListener("click",this._onClick,{passive:!0}),e.addEventListener("touchmove",this._onTouchMove,{passive:!0}),this.dropdown.element.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("input",this._onInput,{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()},e.prototype._removeEventListeners=function(){var e=this.config.shadowRoot||document.documentElement;e.removeEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.removeEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.removeEventListener("mousedown",this._onMouseDown,!0),e.removeEventListener("click",this._onClick),e.removeEventListener("touchmove",this._onTouchMove),this.dropdown.element.removeEventListener("mouseover",this._onMouseOver),this._isSelectOneElement&&(this.containerOuter.element.removeEventListener("focus",this._onFocus),this.containerOuter.element.removeEventListener("blur",this._onBlur)),this.input.element.removeEventListener("keyup",this._onKeyUp),this.input.element.removeEventListener("input",this._onInput),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()},e.prototype._onKeyDown=function(e){var t=e.keyCode,i=this._store.items,n=this.input.isFocussed,s=this.dropdown.isActive,o=this.itemList.hasChildren(),r=1===e.key.length||2===e.key.length&&e.key.charCodeAt(0)>=55296||"Unidentified"===e.key;switch(this._isTextElement||s||(this.showDropdown(),!this.input.isFocussed&&r&&(this.input.value+=e.key)),t){case 65:return this._onSelectKey(e,o);case 13:return this._onEnterKey(e,i,s);case 27:return this._onEscapeKey(e,s);case 38:case 33:case 40:case 34:return this._onDirectionKey(e,s);case 8:case 46:return this._onDeleteKey(e,i,n)}},e.prototype._onKeyUp=function(){this._canSearch=this.config.searchEnabled},e.prototype._onInput=function(){var e=this.input.value;if(e){if(this._isTextElement){var t=this._canAddItem(this._store.items,e);t.notice&&(this._displayAddItemNotice(t),this.showDropdown(!0))}if(this._canSearch){this._handleSearch(e);var i=this._canAddItem(this._store.items,e);i.response||this._displayAddItemNotice(i),this._canAddUserChoices&&(this._highlightPosition=0,this._highlightChoice())}}else this._isTextElement?this.hideDropdown(!0):this._stopSearch()},e.prototype._displayAddItemNotice=function(e){var t=this._templates.notice(this.config,e.notice,"add-choice"),i="".concat(d(this.config.classNames.addChoice),"[data-choice-selectable]"),n=this.choiceList.element.querySelector(i);n?n.outerHTML=t.outerHTML:this.choiceList.prepend(t)},e.prototype._onSelectKey=function(e,t){var i=e.ctrlKey,n=e.metaKey;(i||n)&&t&&(this._canSearch=!1,this.config.removeItems&&!this.input.value&&this.input.element===document.activeElement&&this.highlightAll())},e.prototype._onEnterKey=function(e,t,i){var n=this,s=this.input.value,o=e.target;if(o&&o.hasAttribute("data-button"))return e.preventDefault(),void this._handleButtonAction(t,o);if(!i&&this._isSelectOneElement)return e.preventDefault(),void this.showDropdown();if(i){var r=this.dropdown.element.querySelector(d(this.config.classNames.highlightedState));if(r&&this._handleChoiceAction(t,r,13))return e.preventDefault(),void this.unhighlightAll();s||this.hideDropdown(!0)}o&&s&&this._canAddUserChoices&&(this._canAddItem(t,s).response&&(this._store.withTxn((function(){if((n._isSelectOneElement||n.config.singleModeForMultiSelect)&&0!==t.length){var e=t[t.length-1];n._removeItem(e)}var i=!0;if(!n._isSelectElement&&n.config.duplicateItemsAllowed||(i=!n._findAndSelectChoiceByValue(s)),i){var o=c(s),r=n.config.allowHtmlUserInput||o===s?s:{escaped:o,raw:s};n._addChoice(w({value:r,label:r,selected:!0},!1))}n.clearInput(),n.unhighlightAll(),n._triggerChange(s)})),(this._isTextElement||this._isSelectOneElement)&&this.hideDropdown(!0)))},e.prototype._onEscapeKey=function(e,t){t&&(e.stopPropagation(),this.hideDropdown(!0),this.containerOuter.focus())},e.prototype._onDirectionKey=function(e,t){var i,n,s,o=e.keyCode,r=e.metaKey;if(t||this._isSelectOneElement){this.showDropdown(),this._canSearch=!1;var c=40===o||34===o?1:-1,a="[data-choice-selectable]",h=void 0;if(r||34===o||33===o)h=c>0?this.dropdown.element.querySelector("".concat(a,":last-of-type")):this.dropdown.element.querySelector(a);else{var l=this.dropdown.element.querySelector(d(this.config.classNames.highlightedState));h=l?function(e,t,i){void 0===i&&(i=1);for(var n="".concat(i>0?"next":"previous","ElementSibling"),s=e[n];s;){if(s.matches(t))return s;s=s[n]}return s}(l,a,c):this.dropdown.element.querySelector(a)}h&&(i=h,n=this.choiceList.element,void 0===(s=c)&&(s=1),i&&(s>0?n.scrollTop+n.offsetHeight>=i.offsetTop+i.offsetHeight:i.offsetTop>=n.scrollTop)||this.choiceList.scrollToChildElement(h,c),this._highlightChoice(h)),e.preventDefault()}},e.prototype._onDeleteKey=function(e,t,i){var n=e.target;this._isSelectOneElement||n.value||!i||(this._handleBackspace(t),e.preventDefault())},e.prototype._onTouchMove=function(){this._wasTap&&(this._wasTap=!1)},e.prototype._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},e.prototype._onMouseDown=function(e){var t=e.target;if(t instanceof HTMLElement){if(Ne&&this.choiceList.element.contains(t)){var i=this.choiceList.element.firstElementChild;this._isScrollingOnIe="ltr"===this._direction?e.offsetX>=i.offsetWidth:e.offsetX0&&this.unhighlightAll(),this.containerOuter.removeFocusState(),this.hideDropdown(!0))},e.prototype._onFocus=function(e){var t,i=this,n=e.target;n&&this.containerOuter.element.contains(n)&&((t={})[m]=function(){n===i.input.element&&i.containerOuter.addFocusState()},t[g]=function(){i.containerOuter.addFocusState(),n===i.input.element&&i.showDropdown(!0)},t[v]=function(){n===i.input.element&&(i.showDropdown(!0),i.containerOuter.addFocusState())},t)[this._elementType]()},e.prototype._onBlur=function(e){var t,i=this,n=e.target;if(n&&this.containerOuter.element.contains(n)&&!this._isScrollingOnIe){var s=this._store.activeChoices.some((function(e){return e.highlighted}));((t={})[m]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),s&&i.unhighlightAll(),i.hideDropdown(!0))},t[g]=function(){i.containerOuter.removeFocusState(),(n===i.input.element||n===i.containerOuter.element&&!i._canSearch)&&i.hideDropdown(!0)},t[v]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),i.hideDropdown(!0),s&&i.unhighlightAll())},t)[this._elementType]()}else this._isScrollingOnIe=!1,this.input.element.focus()},e.prototype._onFormReset=function(){var e=this;this._store.withTxn((function(){e.clearInput(),e.hideDropdown(),e.refresh(!1,!1,!0),0!==e._initialItems.length&&e.setChoiceByValue(e._initialItems)}))},e.prototype._highlightChoice=function(e){var t,i=this;void 0===e&&(e=null);var n=Array.from(this.dropdown.element.querySelectorAll("[data-choice-selectable]"));if(n.length){var s=e;Array.from(this.dropdown.element.querySelectorAll(d(this.config.classNames.highlightedState))).forEach((function(e){var t;(t=e.classList).remove.apply(t,u(i.config.classNames.highlightedState)),e.setAttribute("aria-selected","false")})),s?this._highlightPosition=n.indexOf(s):(s=n.length>this._highlightPosition?n[this._highlightPosition]:n[n.length-1])||(s=n[0]),(t=s.classList).add.apply(t,u(this.config.classNames.highlightedState)),s.setAttribute("aria-selected","true"),this.passedElement.triggerEvent("highlightChoice",{el:s}),this.dropdown.isActive&&(this.input.setActiveDescendant(s.id),this.containerOuter.setActiveDescendant(s.id))}},e.prototype._addItem=function(e,t){void 0===t&&(t=!0);var i=e.id;if(0===i)throw new TypeError("item.id must be set before _addItem is called for a choice/item");this._store.dispatch(function(e){return{type:"ADD_ITEM",item:e}}(e)),this._isSelectOneElement&&this.removeActiveItems(i),t&&this.passedElement.triggerEvent("addItem",this._getChoiceForOutput(e))},e.prototype._removeItem=function(e){e.id&&(this._store.dispatch(function(e){return{type:"REMOVE_ITEM",item:e}}(e)),this.passedElement.triggerEvent("removeItem",this._getChoiceForOutput(e)))},e.prototype._addChoice=function(e,t){if(void 0===t&&(t=!0),0!==e.id)throw new TypeError("Can not re-add a choice which has already been added");var i=e;this._lastAddedChoiceId++,i.id=this._lastAddedChoiceId,i.elementId="".concat(this._baseId,"-").concat(this._idNames.itemChoice,"-").concat(i.id),this.config.prependValue&&(i.value=this.config.prependValue+i.value),this.config.appendValue&&(i.value+=this.config.appendValue.toString()),(this.config.prependValue||this.config.appendValue)&&i.element&&(i.element.value=i.value),this._store.dispatch(function(e){return{type:"ADD_CHOICE",choice:e}}(e)),e.selected&&this._addItem(e,t)},e.prototype._addGroup=function(e,t){var i=this;if(void 0===t&&(t=!0),0!==e.id)throw new TypeError("Can not re-add a group which has already been added");if(this._store.dispatch(function(e){return{type:"ADD_GROUP",group:e}}(e)),e.choices){var n=e;this._lastAddedGroupId++,n.id=this._lastAddedGroupId;var s=e.id,o=e.choices;n.choices=[],o.forEach((function(n){var o=n;o.groupId=s,e.disabled&&(o.disabled=!0),i._addChoice(o,t)}))}},e.prototype._createTemplates=function(){var e=this,t=this.config.callbackOnCreateTemplates,i={};t&&"function"==typeof t&&(i=t.call(this,a,M));var n={};Object.keys(F).forEach((function(t){n[t]=t in i?i[t].bind(e):F[t].bind(e)})),this._templates=n},e.prototype._createElements=function(){this.containerOuter=new _({element:this._templates.containerOuter(this.config,this._direction,this._isSelectElement,this._isSelectOneElement,this.config.searchEnabled,this._elementType,this.config.labelId),classNames:this.config.classNames,type:this._elementType,position:this.config.position}),this.containerInner=new _({element:this._templates.containerInner(this.config),classNames:this.config.classNames,type:this._elementType,position:this.config.position}),this.input=new y({element:this._templates.input(this.config,this._placeholderValue),classNames:this.config.classNames,type:this._elementType,preventPaste:!this.config.paste}),this.choiceList=new b({element:this._templates.choiceList(this.config,this._isSelectOneElement)}),this.itemList=new b({element:this._templates.itemList(this.config,this._isSelectOneElement)}),this.dropdown=new f({element:this._templates.dropdown(this.config),classNames:this.config.classNames,type:this._elementType})},e.prototype._createStructure=function(){this.passedElement.conceal(),this.containerInner.wrap(this.passedElement.element),this.containerOuter.wrap(this.containerInner.element),this._isSelectOneElement?this.input.placeholder=this.config.searchPlaceholderValue||"":(this._placeholderValue&&(this.input.placeholder=this._placeholderValue),this.input.setWidth()),this.containerOuter.element.appendChild(this.containerInner.element),this.containerOuter.element.appendChild(this.dropdown.element),this.containerInner.element.appendChild(this.itemList.element),this.dropdown.element.appendChild(this.choiceList.element),this._isSelectOneElement?this.config.searchEnabled&&this.dropdown.element.insertBefore(this.input.element,this.dropdown.element.firstChild):this.containerInner.element.appendChild(this.input.element),this._highlightPosition=0,this._isSearching=!1},e.prototype._initStore=function(){var e=this;this._store.subscribe(this._render),this._store.withTxn((function(){e._addPredefinedChoices(e._presetChoices,e._isSelectOneElement&&!e._hasNonChoicePlaceholder,!1)}))},e.prototype._addPredefinedChoices=function(e,t,i){var n=this;if(void 0===t&&(t=!1),void 0===i&&(i=!0),this.config.shouldSort&&e.sort(this.config.sorter),t){var s=-1===e.findIndex((function(e){return!!e.selected}));if(s){var o=e.findIndex((function(e){return void 0===e.disabled||!e.disabled}));if(-1!==o)e[o].selected=!0}}e.forEach((function(e){"choices"in e?n._isSelectElement&&n._addGroup(e,i):n._addChoice(e,i)}))},e.prototype._findAndSelectChoiceByValue=function(e){var t=this,i=this._store.choices.find((function(i){return t.config.valueComparer(i.value,e)}));return!(!i||i.selected)&&(this._addItem(i),!0)},e.prototype._generatePlaceholderValue=function(){if(!this.config.placeholder)return null;if(this._hasNonChoicePlaceholder)return this.config.placeholderValue;if(this._isSelectElement){var e=this.passedElement.placeholderOption;return e?e.text:null}return null},e.prototype._warnChoicesInitFailed=function(e){if(!this.config.silent){if(!this.initialised)throw new TypeError("".concat(e," called on a non-initialised instance of Choices"));if(!this.initialisedOK)throw new TypeError("".concat(e," called for an element which has multiple instances of Choices initialised on it"))}},e.version="11.0.0-rc5",e}();export{je as default}; diff --git a/public/assets/scripts/choices.mjs b/public/assets/scripts/choices.mjs index 6e49e19f..211a65cc 100644 --- a/public/assets/scripts/choices.mjs +++ b/public/assets/scripts/choices.mjs @@ -99,14 +99,6 @@ var highlightItem = function (item, highlighted) { return ({ highlighted: highlighted, }); }; -var clearAll = function () { return ({ - type: "CLEAR_ALL" /* ActionType.CLEAR_ALL */, -}); }; -var setTxn = function (txn) { return ({ - type: "SET_TRANSACTION" /* ActionType.SET_TRANSACTION */, - txn: txn, -}); }; - /* eslint-disable @typescript-eslint/no-explicit-any */ var getRandomNumber = function (min, max) { return Math.floor(Math.random() * (max - min) + min); @@ -234,9 +226,6 @@ var dispatchEvent = function (element, type, customArgs) { }); return element.dispatchEvent(event); }; -var cloneObject = function (obj) { - return obj !== undefined ? JSON.parse(JSON.stringify(obj)) : undefined; -}; /** * Returns an array of keys present on the first but missing on the second object */ @@ -974,447 +963,85 @@ var DEFAULT_CONFIG = { var ObjectsInConfig = ['fuseOptions', 'classNames']; -/** - * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js - * - * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes - * during build. - * @param {number} code - */ -function formatProdErrorMessage(code) { - return "Minified Redux error #" + code + "; visit https://redux.js.org/Errors?code=" + code + " for the full message or " + 'use the non-minified dev environment for full errors. '; -} - -// Inlined version of the `symbol-observable` polyfill -var $$observable = function () { - return typeof Symbol === 'function' && Symbol.observable || '@@observable'; -}(); - -/** - * These are private action types reserved by Redux. - * For any unknown actions, you must return the current state. - * If the current state is undefined, you must return the initial state. - * Do not reference these action types directly in your code. - */ -var randomString = function randomString() { - return Math.random().toString(36).substring(7).split('').join('.'); -}; -var ActionTypes = { - INIT: "@@redux/INIT" + randomString(), - REPLACE: "@@redux/REPLACE" + randomString(), - PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() { - return "@@redux/PROBE_UNKNOWN_ACTION" + randomString(); - } -}; - -/** - * @param {any} obj The object to inspect. - * @returns {boolean} True if the argument appears to be a plain object. - */ -function isPlainObject(obj) { - if (typeof obj !== 'object' || obj === null) return false; - var proto = obj; - while (Object.getPrototypeOf(proto) !== null) { - proto = Object.getPrototypeOf(proto); - } - return Object.getPrototypeOf(obj) === proto; -} - -/** - * @deprecated - * - * **We recommend using the `configureStore` method - * of the `@reduxjs/toolkit` package**, which replaces `createStore`. - * - * Redux Toolkit is our recommended approach for writing Redux logic today, - * including store setup, reducers, data fetching, and more. - * - * **For more details, please read this Redux docs page:** - * **https://redux.js.org/introduction/why-rtk-is-redux-today** - * - * `configureStore` from Redux Toolkit is an improved version of `createStore` that - * simplifies setup and helps avoid common bugs. - * - * You should not be using the `redux` core package by itself today, except for learning purposes. - * The `createStore` method from the core `redux` package will not be removed, but we encourage - * all users to migrate to using Redux Toolkit for all Redux code. - * - * If you want to use `createStore` without this visual deprecation warning, use - * the `legacy_createStore` import instead: - * - * `import { legacy_createStore as createStore} from 'redux'` - * - */ - -function createStore(reducer, preloadedState, enhancer) { - var _ref2; - if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') { - throw new Error(formatProdErrorMessage(0) ); - } - if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { - enhancer = preloadedState; - preloadedState = undefined; - } - if (typeof enhancer !== 'undefined') { - if (typeof enhancer !== 'function') { - throw new Error(formatProdErrorMessage(1) ); - } - return enhancer(createStore)(reducer, preloadedState); - } - if (typeof reducer !== 'function') { - throw new Error(formatProdErrorMessage(2) ); - } - var currentReducer = reducer; - var currentState = preloadedState; - var currentListeners = []; - var nextListeners = currentListeners; - var isDispatching = false; - /** - * This makes a shallow copy of currentListeners so we can use - * nextListeners as a temporary list while dispatching. - * - * This prevents any bugs around consumers calling - * subscribe/unsubscribe in the middle of a dispatch. - */ - - function ensureCanMutateNextListeners() { - if (nextListeners === currentListeners) { - nextListeners = currentListeners.slice(); - } - } - /** - * Reads the state tree managed by the store. - * - * @returns {any} The current state tree of your application. - */ - - function getState() { - if (isDispatching) { - throw new Error(formatProdErrorMessage(3) ); - } - return currentState; - } - /** - * Adds a change listener. It will be called any time an action is dispatched, - * and some part of the state tree may potentially have changed. You may then - * call `getState()` to read the current state tree inside the callback. - * - * You may call `dispatch()` from a change listener, with the following - * caveats: - * - * 1. The subscriptions are snapshotted just before every `dispatch()` call. - * If you subscribe or unsubscribe while the listeners are being invoked, this - * will not have any effect on the `dispatch()` that is currently in progress. - * However, the next `dispatch()` call, whether nested or not, will use a more - * recent snapshot of the subscription list. - * - * 2. The listener should not expect to see all state changes, as the state - * might have been updated multiple times during a nested `dispatch()` before - * the listener is called. It is, however, guaranteed that all subscribers - * registered before the `dispatch()` started will be called with the latest - * state by the time it exits. - * - * @param {Function} listener A callback to be invoked on every dispatch. - * @returns {Function} A function to remove this change listener. - */ - - function subscribe(listener) { - if (typeof listener !== 'function') { - throw new Error(formatProdErrorMessage(4) ); - } - if (isDispatching) { - throw new Error(formatProdErrorMessage(5) ); - } - var isSubscribed = true; - ensureCanMutateNextListeners(); - nextListeners.push(listener); - return function unsubscribe() { - if (!isSubscribed) { - return; - } - if (isDispatching) { - throw new Error(formatProdErrorMessage(6) ); - } - isSubscribed = false; - ensureCanMutateNextListeners(); - var index = nextListeners.indexOf(listener); - nextListeners.splice(index, 1); - currentListeners = null; - }; - } - /** - * Dispatches an action. It is the only way to trigger a state change. - * - * The `reducer` function, used to create the store, will be called with the - * current state tree and the given `action`. Its return value will - * be considered the **next** state of the tree, and the change listeners - * will be notified. - * - * The base implementation only supports plain object actions. If you want to - * dispatch a Promise, an Observable, a thunk, or something else, you need to - * wrap your store creating function into the corresponding middleware. For - * example, see the documentation for the `redux-thunk` package. Even the - * middleware will eventually dispatch plain object actions using this method. - * - * @param {Object} action A plain object representing “what changed”. It is - * a good idea to keep actions serializable so you can record and replay user - * sessions, or use the time travelling `redux-devtools`. An action must have - * a `type` property which may not be `undefined`. It is a good idea to use - * string constants for action types. - * - * @returns {Object} For convenience, the same action object you dispatched. - * - * Note that, if you use a custom middleware, it may wrap `dispatch()` to - * return something else (for example, a Promise you can await). - */ - - function dispatch(action) { - if (!isPlainObject(action)) { - throw new Error(formatProdErrorMessage(7) ); - } - if (typeof action.type === 'undefined') { - throw new Error(formatProdErrorMessage(8) ); - } - if (isDispatching) { - throw new Error(formatProdErrorMessage(9) ); - } - try { - isDispatching = true; - currentState = currentReducer(currentState, action); - } finally { - isDispatching = false; - } - var listeners = currentListeners = nextListeners; - for (var i = 0; i < listeners.length; i++) { - var listener = listeners[i]; - listener(); - } - return action; - } - /** - * Replaces the reducer currently used by the store to calculate the state. - * - * You might need this if your app implements code splitting and you want to - * load some of the reducers dynamically. You might also need this if you - * implement a hot reloading mechanism for Redux. - * - * @param {Function} nextReducer The reducer for the store to use instead. - * @returns {void} - */ - - function replaceReducer(nextReducer) { - if (typeof nextReducer !== 'function') { - throw new Error(formatProdErrorMessage(10) ); - } - currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT. - // Any reducers that existed in both the new and old rootReducer - // will receive the previous state. This effectively populates - // the new state tree with any relevant data from the old one. - - dispatch({ - type: ActionTypes.REPLACE - }); - } - /** - * Interoperability point for observable/reactive libraries. - * @returns {observable} A minimal observable of state changes. - * For more information, see the observable proposal: - * https://github.com/tc39/proposal-observable - */ - - function observable() { - var _ref; - var outerSubscribe = subscribe; - return _ref = { - /** - * The minimal observable subscription method. - * @param {Object} observer Any object that can be used as an observer. - * The observer object should have a `next` method. - * @returns {subscription} An object with an `unsubscribe` method that can - * be used to unsubscribe the observable from the store, and prevent further - * emission of values from the observable. - */ - subscribe: function subscribe(observer) { - if (typeof observer !== 'object' || observer === null) { - throw new Error(formatProdErrorMessage(11) ); - } - function observeState() { - if (observer.next) { - observer.next(getState()); - } - } - observeState(); - var unsubscribe = outerSubscribe(observeState); - return { - unsubscribe: unsubscribe - }; - } - }, _ref[$$observable] = function () { - return this; - }, _ref; - } // When a store is created, an "INIT" action is dispatched so that every - // reducer returns their initial state. This effectively populates - // the initial state tree. - - dispatch({ - type: ActionTypes.INIT - }); - return _ref2 = { - dispatch: dispatch, - subscribe: subscribe, - getState: getState, - replaceReducer: replaceReducer - }, _ref2[$$observable] = observable, _ref2; -} -function assertReducerShape(reducers) { - Object.keys(reducers).forEach(function (key) { - var reducer = reducers[key]; - var initialState = reducer(undefined, { - type: ActionTypes.INIT - }); - if (typeof initialState === 'undefined') { - throw new Error(formatProdErrorMessage(12) ); - } - if (typeof reducer(undefined, { - type: ActionTypes.PROBE_UNKNOWN_ACTION() - }) === 'undefined') { - throw new Error(formatProdErrorMessage(13) ); - } - }); -} -/** - * Turns an object whose values are different reducer functions, into a single - * reducer function. It will call every child reducer, and gather their results - * into a single state object, whose keys correspond to the keys of the passed - * reducer functions. - * - * @param {Object} reducers An object whose values correspond to different - * reducer functions that need to be combined into one. One handy way to obtain - * it is to use ES6 `import * as reducers` syntax. The reducers may never return - * undefined for any action. Instead, they should return their initial state - * if the state passed to them was undefined, and the current state for any - * unrecognized action. - * - * @returns {Function} A reducer function that invokes every reducer inside the - * passed object, and builds a state object with the same shape. - */ - -function combineReducers(reducers) { - var reducerKeys = Object.keys(reducers); - var finalReducers = {}; - for (var i = 0; i < reducerKeys.length; i++) { - var key = reducerKeys[i]; - if (typeof reducers[key] === 'function') { - finalReducers[key] = reducers[key]; - } - } - var finalReducerKeys = Object.keys(finalReducers); // This is used to make sure we don't warn about the same - var shapeAssertionError; - try { - assertReducerShape(finalReducers); - } catch (e) { - shapeAssertionError = e; - } - return function combination(state, action) { - if (state === void 0) { - state = {}; - } - if (shapeAssertionError) { - throw shapeAssertionError; - } - var hasChanged = false; - var nextState = {}; - for (var _i = 0; _i < finalReducerKeys.length; _i++) { - var _key = finalReducerKeys[_i]; - var reducer = finalReducers[_key]; - var previousStateForKey = state[_key]; - var nextStateForKey = reducer(previousStateForKey, action); - if (typeof nextStateForKey === 'undefined') { - action && action.type; - throw new Error(formatProdErrorMessage(14) ); - } - nextState[_key] = nextStateForKey; - hasChanged = hasChanged || nextStateForKey !== previousStateForKey; - } - hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length; - return hasChanged ? nextState : state; - }; -} - -function items(state, action) { - if (state === void 0) { state = []; } - if (action === void 0) { action = {}; } +function items(s, action) { + var state = s; + var update = false; switch (action.type) { case "ADD_ITEM" /* ActionType.ADD_ITEM */: { var item = action.item; - if (!item.id) { - return state; + if (item.id) { + item.selected = true; + var el = item.element; + if (el) { + el.selected = true; + el.setAttribute('selected', ''); + } + update = true; + state.push(item); + state.forEach(function (obj) { + // eslint-disable-next-line no-param-reassign + obj.highlighted = false; + }); } - item.selected = true; - var el = item.element; - if (el) { - el.selected = true; - el.setAttribute('selected', ''); - } - return __spreadArray(__spreadArray([], state, true), [item], false).map(function (obj) { - var choice = obj; - choice.highlighted = false; - return choice; - }); + break; } case "REMOVE_ITEM" /* ActionType.REMOVE_ITEM */: { var item_1 = action.item; - if (!item_1.id) { - return state; + if (item_1.id) { + item_1.selected = false; + var el = item_1.element; + if (el) { + el.selected = false; + el.removeAttribute('selected'); + } + update = true; + state = state.filter(function (choice) { return choice.id !== item_1.id; }); } - item_1.selected = false; - var el = item_1.element; - if (el) { - el.selected = false; - el.removeAttribute('selected'); - } - return state.filter(function (choice) { return choice.id !== item_1.id; }); + break; } case "REMOVE_CHOICE" /* ActionType.REMOVE_CHOICE */: { var choice_1 = action.choice; - return state.filter(function (item) { return item.id !== choice_1.id; }); + update = true; + state = state.filter(function (item) { return item.id !== choice_1.id; }); + break; } case "HIGHLIGHT_ITEM" /* ActionType.HIGHLIGHT_ITEM */: { var highlightItemAction_1 = action; - return state.map(function (obj) { + update = true; + state.forEach(function (obj) { var item = obj; if (item.id === highlightItemAction_1.item.id) { item.highlighted = highlightItemAction_1.highlighted; } - return item; }); - } - default: { - return state; + break; } } + return { state: state, update: update }; } -function groups(state, action) { - if (state === void 0) { state = []; } - if (action === void 0) { action = {}; } +function groups(s, action) { + var state = s; + var update = false; switch (action.type) { case "ADD_GROUP" /* ActionType.ADD_GROUP */: { var addGroupAction = action; - return __spreadArray(__spreadArray([], state, true), [addGroupAction.group], false); + update = true; + state.push(addGroupAction.group); + break; } case "CLEAR_CHOICES" /* ActionType.CLEAR_CHOICES */: { - return []; - } - default: { - return state; + update = true; + state = []; + break; } } + return { state: state, update: update }; } -function choices(state, action) { - if (state === void 0) { state = []; } - if (action === void 0) { action = {}; } +function choices(s, action) { + var state = s; + var update = false; switch (action.type) { case "ADD_CHOICE" /* ActionType.ADD_CHOICE */: { var choice = action.choice; @@ -1423,36 +1050,41 @@ function choices(state, action) { A selected choice has been added to the passed input's value (added as an item) An active choice appears within the choice dropdown */ - return __spreadArray(__spreadArray([], state, true), [choice], false); + state.push(choice); + update = true; + break; } case "REMOVE_CHOICE" /* ActionType.REMOVE_CHOICE */: { var choice_1 = action.choice; - return state.filter(function (obj) { return obj.id !== choice_1.id; }); + update = true; + state = state.filter(function (obj) { return obj.id !== choice_1.id; }); + break; } case "ADD_ITEM" /* ActionType.ADD_ITEM */: { var item = action.item; // trigger a rebuild of the choices list as the item can not be added multiple times if (item.id && item.selected) { - return __spreadArray([], state, true); + update = true; } - return state; + break; } case "REMOVE_ITEM" /* ActionType.REMOVE_ITEM */: { var item = action.item; // trigger a rebuild of the choices list as the item can be added if (item.id && !item.selected) { - return __spreadArray([], state, true); + update = true; } - return state; + break; } case "FILTER_CHOICES" /* ActionType.FILTER_CHOICES */: { var results = action.results; + update = true; // avoid O(n^2) algorithm complexity when searching/filtering choices var scoreLookup_1 = []; results.forEach(function (result) { scoreLookup_1[result.item.id] = result; }); - return state.map(function (obj) { + state.forEach(function (obj) { var choice = obj; var result = scoreLookup_1[choice.id]; if (result !== undefined) { @@ -1465,102 +1097,110 @@ function choices(state, action) { choice.rank = 0; choice.active = false; } - return choice; }); + break; } case "ACTIVATE_CHOICES" /* ActionType.ACTIVATE_CHOICES */: { var active_1 = action.active; - return state.map(function (obj) { + update = true; + state.forEach(function (obj) { var choice = obj; choice.active = active_1; return choice; }); + break; } case "CLEAR_CHOICES" /* ActionType.CLEAR_CHOICES */: { - return []; - } - default: { - return state; + update = true; + state = []; + break; } } + return { state: state, update: update }; } -var general = function (state, action) { - if (state === void 0) { state = 0; } - if (action === void 0) { action = {}; } - switch (action.type) { - case "SET_TRANSACTION" /* ActionType.SET_TRANSACTION */: { - if (action.txn) { - return state + 1; - } - return Math.max(0, state - 1); - } - default: { - return state; - } - } -}; - -var defaultState = { - groups: [], - items: [], - choices: [], - txn: 0, -}; -var appReducer = combineReducers({ - items: items, +var reducers = { groups: groups, + items: items, choices: choices, - txn: general, -}); -var rootReducer = function (passedState, action) { - var state = passedState; - // If we are clearing all items, groups and options we reassign - // state and then pass that state to our proper reducer. This isn't - // mutating our actual state - // See: http://stackoverflow.com/a/35641992 - if (action.type === "CLEAR_ALL" /* ActionType.CLEAR_ALL */) { - // preserve the txn state as to allow withTxn to work - var paused = state.txn; - state = cloneObject(defaultState); - state.txn = paused; - } - return appReducer(state, action); }; - -/* eslint-disable @typescript-eslint/no-explicit-any */ var Store = /** @class */ (function () { function Store() { - this._store = createStore(rootReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && - window.__REDUX_DEVTOOLS_EXTENSION__()); + this._store = this.defaultState; + this._listeners = []; + this._txn = 0; } - /** - * Subscribe store to function call (wrapped Redux method) - */ - Store.prototype.subscribe = function (onChange) { - this._store.subscribe(onChange); + Object.defineProperty(Store.prototype, "defaultState", { + // eslint-disable-next-line class-methods-use-this + get: function () { + return { + groups: [], + items: [], + choices: [], + }; + }, + enumerable: false, + configurable: true + }); + // eslint-disable-next-line class-methods-use-this + Store.prototype.changeSet = function (init) { + return { + groups: init, + items: init, + choices: init, + }; + }; + Store.prototype.resetStore = function () { + this._store = this.defaultState; + var changes = this.changeSet(true); + this._listeners.forEach(function (l) { return l(changes); }); + }; + Store.prototype.subscribe = function (onChange) { + this._listeners.push(onChange); }; - /** - * Dispatch event to store (wrapped Redux method) - */ Store.prototype.dispatch = function (action) { - this._store.dispatch(action); + var state = this._store; + var hasChanges = false; + var changes = this._outstandingChanges || this.changeSet(false); + Object.keys(reducers).forEach(function (key) { + var stateUpdate = reducers[key](state[key], action); + if (stateUpdate.update) { + hasChanges = true; + changes[key] = true; + state[key] = stateUpdate.state; + } + }); + if (hasChanges) { + if (this._txn) { + this._outstandingChanges = changes; + } + else { + this._listeners.forEach(function (l) { return l(changes); }); + } + } }; Store.prototype.withTxn = function (func) { - this._store.dispatch(setTxn(true)); + this._txn++; try { func(); } finally { - this._store.dispatch(setTxn(false)); + this._txn = Math.max(0, this._txn - 1); + if (!this._txn) { + var changeSet_1 = this._outstandingChanges; + if (changeSet_1) { + this._outstandingChanges = undefined; + this._listeners.forEach(function (l) { return l(changeSet_1); }); + } + } } }; Object.defineProperty(Store.prototype, "state", { /** - * Get store object (wrapping Redux method) + * Get store object */ get: function () { - return this._store.getState(); + return this._store; }, enumerable: false, configurable: true @@ -1630,10 +1270,10 @@ var Store = /** @class */ (function () { * Get active groups from store */ get: function () { - var _a = this, groups = _a.groups, choices = _a.choices; - return groups.filter(function (group) { + var _this = this; + return this.state.groups.filter(function (group) { var isActive = group.active && !group.disabled; - var hasActiveOptions = choices.some(function (choice) { return choice.active && !choice.disabled; }); + var hasActiveOptions = _this.state.choices.some(function (choice) { return choice.active && !choice.disabled; }); return isActive && hasActiveOptions; }, []); }, @@ -1641,7 +1281,7 @@ var Store = /** @class */ (function () { configurable: true }); Store.prototype.inTxn = function () { - return this.state.txn > 0; + return this._txn > 0; }; /** * Get single choice by it's ID @@ -3728,9 +3368,6 @@ var Choices = /** @class */ (function () { } this.initialised = false; this._store = new Store(); - this._initialState = defaultState; - this._currentState = defaultState; - this._prevState = defaultState; this._currentValue = ''; this.config.searchEnabled = (!this._isTextElement && this.config.searchEnabled) || @@ -3813,8 +3450,7 @@ var Choices = /** @class */ (function () { this._createTemplates(); this._createElements(); this._createStructure(); - this._store.subscribe(this._render); - this._render(); + this._initStore(); this._addEventListeners(); var shouldDisable = (this._isTextElement && !this.config.addItems) || this.passedElement.element.hasAttribute('disabled') || @@ -3838,6 +3474,7 @@ var Choices = /** @class */ (function () { this.passedElement.reveal(); this.containerOuter.unwrap(this.passedElement.element); this.clearStore(); + this._store._listeners = []; this._stopSearch(); this._templates = templates; this.initialised = false; @@ -4243,7 +3880,7 @@ var Choices = /** @class */ (function () { return this; }; Choices.prototype.clearStore = function () { - this._store.dispatch(clearAll()); + this._store.resetStore(); this._lastAddedChoiceId = 0; this._lastAddedGroupId = 0; // @todo integrate with Store @@ -4272,15 +3909,12 @@ var Choices = /** @class */ (function () { } } }; - Choices.prototype._render = function () { + Choices.prototype._render = function (changes) { if (this._store.inTxn()) { return; } - this._currentState = this._store.state; - var shouldRenderItems = this._currentState.items !== this._prevState.items; - var stateChanged = this._currentState.choices !== this._prevState.choices || - this._currentState.groups !== this._prevState.groups || - shouldRenderItems; + var shouldRenderItems = changes === null || changes === void 0 ? void 0 : changes.items; + var stateChanged = (changes === null || changes === void 0 ? void 0 : changes.choices) || (changes === null || changes === void 0 ? void 0 : changes.groups) || shouldRenderItems; if (!stateChanged) { return; } @@ -4290,7 +3924,6 @@ var Choices = /** @class */ (function () { if (shouldRenderItems) { this._renderItems(); } - this._prevState = this._currentState; }; Choices.prototype._renderChoices = function () { var _this = this; @@ -5509,7 +5142,6 @@ var Choices = /** @class */ (function () { }); }; Choices.prototype._createStructure = function () { - var _this = this; // Hide original element this.passedElement.conceal(); // Wrap input in container preserving DOM ordering @@ -5537,6 +5169,10 @@ var Choices = /** @class */ (function () { } this._highlightPosition = 0; this._isSearching = false; + }; + Choices.prototype._initStore = function () { + var _this = this; + this._store.subscribe(this._render); this._store.withTxn(function () { _this._addPredefinedChoices(_this._presetChoices, _this._isSelectOneElement && !_this._hasNonChoicePlaceholder, false); }); diff --git a/public/assets/scripts/choices.search-basic.js b/public/assets/scripts/choices.search-basic.js index a99f5665..1c0bd89a 100644 --- a/public/assets/scripts/choices.search-basic.js +++ b/public/assets/scripts/choices.search-basic.js @@ -105,14 +105,6 @@ highlighted: highlighted, }); }; - var clearAll = function () { return ({ - type: "CLEAR_ALL" /* ActionType.CLEAR_ALL */, - }); }; - var setTxn = function (txn) { return ({ - type: "SET_TRANSACTION" /* ActionType.SET_TRANSACTION */, - txn: txn, - }); }; - /* eslint-disable @typescript-eslint/no-explicit-any */ var getRandomNumber = function (min, max) { return Math.floor(Math.random() * (max - min) + min); @@ -240,9 +232,6 @@ }); return element.dispatchEvent(event); }; - var cloneObject = function (obj) { - return obj !== undefined ? JSON.parse(JSON.stringify(obj)) : undefined; - }; /** * Returns an array of keys present on the first but missing on the second object */ @@ -980,447 +969,85 @@ var ObjectsInConfig = ['fuseOptions', 'classNames']; - /** - * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js - * - * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes - * during build. - * @param {number} code - */ - function formatProdErrorMessage(code) { - return "Minified Redux error #" + code + "; visit https://redux.js.org/Errors?code=" + code + " for the full message or " + 'use the non-minified dev environment for full errors. '; - } - - // Inlined version of the `symbol-observable` polyfill - var $$observable = function () { - return typeof Symbol === 'function' && Symbol.observable || '@@observable'; - }(); - - /** - * These are private action types reserved by Redux. - * For any unknown actions, you must return the current state. - * If the current state is undefined, you must return the initial state. - * Do not reference these action types directly in your code. - */ - var randomString = function randomString() { - return Math.random().toString(36).substring(7).split('').join('.'); - }; - var ActionTypes = { - INIT: "@@redux/INIT" + randomString(), - REPLACE: "@@redux/REPLACE" + randomString(), - PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() { - return "@@redux/PROBE_UNKNOWN_ACTION" + randomString(); - } - }; - - /** - * @param {any} obj The object to inspect. - * @returns {boolean} True if the argument appears to be a plain object. - */ - function isPlainObject(obj) { - if (typeof obj !== 'object' || obj === null) return false; - var proto = obj; - while (Object.getPrototypeOf(proto) !== null) { - proto = Object.getPrototypeOf(proto); - } - return Object.getPrototypeOf(obj) === proto; - } - - /** - * @deprecated - * - * **We recommend using the `configureStore` method - * of the `@reduxjs/toolkit` package**, which replaces `createStore`. - * - * Redux Toolkit is our recommended approach for writing Redux logic today, - * including store setup, reducers, data fetching, and more. - * - * **For more details, please read this Redux docs page:** - * **https://redux.js.org/introduction/why-rtk-is-redux-today** - * - * `configureStore` from Redux Toolkit is an improved version of `createStore` that - * simplifies setup and helps avoid common bugs. - * - * You should not be using the `redux` core package by itself today, except for learning purposes. - * The `createStore` method from the core `redux` package will not be removed, but we encourage - * all users to migrate to using Redux Toolkit for all Redux code. - * - * If you want to use `createStore` without this visual deprecation warning, use - * the `legacy_createStore` import instead: - * - * `import { legacy_createStore as createStore} from 'redux'` - * - */ - - function createStore(reducer, preloadedState, enhancer) { - var _ref2; - if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') { - throw new Error(formatProdErrorMessage(0) ); - } - if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { - enhancer = preloadedState; - preloadedState = undefined; - } - if (typeof enhancer !== 'undefined') { - if (typeof enhancer !== 'function') { - throw new Error(formatProdErrorMessage(1) ); - } - return enhancer(createStore)(reducer, preloadedState); - } - if (typeof reducer !== 'function') { - throw new Error(formatProdErrorMessage(2) ); - } - var currentReducer = reducer; - var currentState = preloadedState; - var currentListeners = []; - var nextListeners = currentListeners; - var isDispatching = false; - /** - * This makes a shallow copy of currentListeners so we can use - * nextListeners as a temporary list while dispatching. - * - * This prevents any bugs around consumers calling - * subscribe/unsubscribe in the middle of a dispatch. - */ - - function ensureCanMutateNextListeners() { - if (nextListeners === currentListeners) { - nextListeners = currentListeners.slice(); - } - } - /** - * Reads the state tree managed by the store. - * - * @returns {any} The current state tree of your application. - */ - - function getState() { - if (isDispatching) { - throw new Error(formatProdErrorMessage(3) ); - } - return currentState; - } - /** - * Adds a change listener. It will be called any time an action is dispatched, - * and some part of the state tree may potentially have changed. You may then - * call `getState()` to read the current state tree inside the callback. - * - * You may call `dispatch()` from a change listener, with the following - * caveats: - * - * 1. The subscriptions are snapshotted just before every `dispatch()` call. - * If you subscribe or unsubscribe while the listeners are being invoked, this - * will not have any effect on the `dispatch()` that is currently in progress. - * However, the next `dispatch()` call, whether nested or not, will use a more - * recent snapshot of the subscription list. - * - * 2. The listener should not expect to see all state changes, as the state - * might have been updated multiple times during a nested `dispatch()` before - * the listener is called. It is, however, guaranteed that all subscribers - * registered before the `dispatch()` started will be called with the latest - * state by the time it exits. - * - * @param {Function} listener A callback to be invoked on every dispatch. - * @returns {Function} A function to remove this change listener. - */ - - function subscribe(listener) { - if (typeof listener !== 'function') { - throw new Error(formatProdErrorMessage(4) ); - } - if (isDispatching) { - throw new Error(formatProdErrorMessage(5) ); - } - var isSubscribed = true; - ensureCanMutateNextListeners(); - nextListeners.push(listener); - return function unsubscribe() { - if (!isSubscribed) { - return; - } - if (isDispatching) { - throw new Error(formatProdErrorMessage(6) ); - } - isSubscribed = false; - ensureCanMutateNextListeners(); - var index = nextListeners.indexOf(listener); - nextListeners.splice(index, 1); - currentListeners = null; - }; - } - /** - * Dispatches an action. It is the only way to trigger a state change. - * - * The `reducer` function, used to create the store, will be called with the - * current state tree and the given `action`. Its return value will - * be considered the **next** state of the tree, and the change listeners - * will be notified. - * - * The base implementation only supports plain object actions. If you want to - * dispatch a Promise, an Observable, a thunk, or something else, you need to - * wrap your store creating function into the corresponding middleware. For - * example, see the documentation for the `redux-thunk` package. Even the - * middleware will eventually dispatch plain object actions using this method. - * - * @param {Object} action A plain object representing “what changed”. It is - * a good idea to keep actions serializable so you can record and replay user - * sessions, or use the time travelling `redux-devtools`. An action must have - * a `type` property which may not be `undefined`. It is a good idea to use - * string constants for action types. - * - * @returns {Object} For convenience, the same action object you dispatched. - * - * Note that, if you use a custom middleware, it may wrap `dispatch()` to - * return something else (for example, a Promise you can await). - */ - - function dispatch(action) { - if (!isPlainObject(action)) { - throw new Error(formatProdErrorMessage(7) ); - } - if (typeof action.type === 'undefined') { - throw new Error(formatProdErrorMessage(8) ); - } - if (isDispatching) { - throw new Error(formatProdErrorMessage(9) ); - } - try { - isDispatching = true; - currentState = currentReducer(currentState, action); - } finally { - isDispatching = false; - } - var listeners = currentListeners = nextListeners; - for (var i = 0; i < listeners.length; i++) { - var listener = listeners[i]; - listener(); - } - return action; - } - /** - * Replaces the reducer currently used by the store to calculate the state. - * - * You might need this if your app implements code splitting and you want to - * load some of the reducers dynamically. You might also need this if you - * implement a hot reloading mechanism for Redux. - * - * @param {Function} nextReducer The reducer for the store to use instead. - * @returns {void} - */ - - function replaceReducer(nextReducer) { - if (typeof nextReducer !== 'function') { - throw new Error(formatProdErrorMessage(10) ); - } - currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT. - // Any reducers that existed in both the new and old rootReducer - // will receive the previous state. This effectively populates - // the new state tree with any relevant data from the old one. - - dispatch({ - type: ActionTypes.REPLACE - }); - } - /** - * Interoperability point for observable/reactive libraries. - * @returns {observable} A minimal observable of state changes. - * For more information, see the observable proposal: - * https://github.com/tc39/proposal-observable - */ - - function observable() { - var _ref; - var outerSubscribe = subscribe; - return _ref = { - /** - * The minimal observable subscription method. - * @param {Object} observer Any object that can be used as an observer. - * The observer object should have a `next` method. - * @returns {subscription} An object with an `unsubscribe` method that can - * be used to unsubscribe the observable from the store, and prevent further - * emission of values from the observable. - */ - subscribe: function subscribe(observer) { - if (typeof observer !== 'object' || observer === null) { - throw new Error(formatProdErrorMessage(11) ); - } - function observeState() { - if (observer.next) { - observer.next(getState()); - } - } - observeState(); - var unsubscribe = outerSubscribe(observeState); - return { - unsubscribe: unsubscribe - }; - } - }, _ref[$$observable] = function () { - return this; - }, _ref; - } // When a store is created, an "INIT" action is dispatched so that every - // reducer returns their initial state. This effectively populates - // the initial state tree. - - dispatch({ - type: ActionTypes.INIT - }); - return _ref2 = { - dispatch: dispatch, - subscribe: subscribe, - getState: getState, - replaceReducer: replaceReducer - }, _ref2[$$observable] = observable, _ref2; - } - function assertReducerShape(reducers) { - Object.keys(reducers).forEach(function (key) { - var reducer = reducers[key]; - var initialState = reducer(undefined, { - type: ActionTypes.INIT - }); - if (typeof initialState === 'undefined') { - throw new Error(formatProdErrorMessage(12) ); - } - if (typeof reducer(undefined, { - type: ActionTypes.PROBE_UNKNOWN_ACTION() - }) === 'undefined') { - throw new Error(formatProdErrorMessage(13) ); - } - }); - } - /** - * Turns an object whose values are different reducer functions, into a single - * reducer function. It will call every child reducer, and gather their results - * into a single state object, whose keys correspond to the keys of the passed - * reducer functions. - * - * @param {Object} reducers An object whose values correspond to different - * reducer functions that need to be combined into one. One handy way to obtain - * it is to use ES6 `import * as reducers` syntax. The reducers may never return - * undefined for any action. Instead, they should return their initial state - * if the state passed to them was undefined, and the current state for any - * unrecognized action. - * - * @returns {Function} A reducer function that invokes every reducer inside the - * passed object, and builds a state object with the same shape. - */ - - function combineReducers(reducers) { - var reducerKeys = Object.keys(reducers); - var finalReducers = {}; - for (var i = 0; i < reducerKeys.length; i++) { - var key = reducerKeys[i]; - if (typeof reducers[key] === 'function') { - finalReducers[key] = reducers[key]; - } - } - var finalReducerKeys = Object.keys(finalReducers); // This is used to make sure we don't warn about the same - var shapeAssertionError; - try { - assertReducerShape(finalReducers); - } catch (e) { - shapeAssertionError = e; - } - return function combination(state, action) { - if (state === void 0) { - state = {}; - } - if (shapeAssertionError) { - throw shapeAssertionError; - } - var hasChanged = false; - var nextState = {}; - for (var _i = 0; _i < finalReducerKeys.length; _i++) { - var _key = finalReducerKeys[_i]; - var reducer = finalReducers[_key]; - var previousStateForKey = state[_key]; - var nextStateForKey = reducer(previousStateForKey, action); - if (typeof nextStateForKey === 'undefined') { - action && action.type; - throw new Error(formatProdErrorMessage(14) ); - } - nextState[_key] = nextStateForKey; - hasChanged = hasChanged || nextStateForKey !== previousStateForKey; - } - hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length; - return hasChanged ? nextState : state; - }; - } - - function items(state, action) { - if (state === void 0) { state = []; } - if (action === void 0) { action = {}; } + function items(s, action) { + var state = s; + var update = false; switch (action.type) { case "ADD_ITEM" /* ActionType.ADD_ITEM */: { var item = action.item; - if (!item.id) { - return state; + if (item.id) { + item.selected = true; + var el = item.element; + if (el) { + el.selected = true; + el.setAttribute('selected', ''); + } + update = true; + state.push(item); + state.forEach(function (obj) { + // eslint-disable-next-line no-param-reassign + obj.highlighted = false; + }); } - item.selected = true; - var el = item.element; - if (el) { - el.selected = true; - el.setAttribute('selected', ''); - } - return __spreadArray(__spreadArray([], state, true), [item], false).map(function (obj) { - var choice = obj; - choice.highlighted = false; - return choice; - }); + break; } case "REMOVE_ITEM" /* ActionType.REMOVE_ITEM */: { var item_1 = action.item; - if (!item_1.id) { - return state; + if (item_1.id) { + item_1.selected = false; + var el = item_1.element; + if (el) { + el.selected = false; + el.removeAttribute('selected'); + } + update = true; + state = state.filter(function (choice) { return choice.id !== item_1.id; }); } - item_1.selected = false; - var el = item_1.element; - if (el) { - el.selected = false; - el.removeAttribute('selected'); - } - return state.filter(function (choice) { return choice.id !== item_1.id; }); + break; } case "REMOVE_CHOICE" /* ActionType.REMOVE_CHOICE */: { var choice_1 = action.choice; - return state.filter(function (item) { return item.id !== choice_1.id; }); + update = true; + state = state.filter(function (item) { return item.id !== choice_1.id; }); + break; } case "HIGHLIGHT_ITEM" /* ActionType.HIGHLIGHT_ITEM */: { var highlightItemAction_1 = action; - return state.map(function (obj) { + update = true; + state.forEach(function (obj) { var item = obj; if (item.id === highlightItemAction_1.item.id) { item.highlighted = highlightItemAction_1.highlighted; } - return item; }); - } - default: { - return state; + break; } } + return { state: state, update: update }; } - function groups(state, action) { - if (state === void 0) { state = []; } - if (action === void 0) { action = {}; } + function groups(s, action) { + var state = s; + var update = false; switch (action.type) { case "ADD_GROUP" /* ActionType.ADD_GROUP */: { var addGroupAction = action; - return __spreadArray(__spreadArray([], state, true), [addGroupAction.group], false); + update = true; + state.push(addGroupAction.group); + break; } case "CLEAR_CHOICES" /* ActionType.CLEAR_CHOICES */: { - return []; - } - default: { - return state; + update = true; + state = []; + break; } } + return { state: state, update: update }; } - function choices(state, action) { - if (state === void 0) { state = []; } - if (action === void 0) { action = {}; } + function choices(s, action) { + var state = s; + var update = false; switch (action.type) { case "ADD_CHOICE" /* ActionType.ADD_CHOICE */: { var choice = action.choice; @@ -1429,36 +1056,41 @@ A selected choice has been added to the passed input's value (added as an item) An active choice appears within the choice dropdown */ - return __spreadArray(__spreadArray([], state, true), [choice], false); + state.push(choice); + update = true; + break; } case "REMOVE_CHOICE" /* ActionType.REMOVE_CHOICE */: { var choice_1 = action.choice; - return state.filter(function (obj) { return obj.id !== choice_1.id; }); + update = true; + state = state.filter(function (obj) { return obj.id !== choice_1.id; }); + break; } case "ADD_ITEM" /* ActionType.ADD_ITEM */: { var item = action.item; // trigger a rebuild of the choices list as the item can not be added multiple times if (item.id && item.selected) { - return __spreadArray([], state, true); + update = true; } - return state; + break; } case "REMOVE_ITEM" /* ActionType.REMOVE_ITEM */: { var item = action.item; // trigger a rebuild of the choices list as the item can be added if (item.id && !item.selected) { - return __spreadArray([], state, true); + update = true; } - return state; + break; } case "FILTER_CHOICES" /* ActionType.FILTER_CHOICES */: { var results = action.results; + update = true; // avoid O(n^2) algorithm complexity when searching/filtering choices var scoreLookup_1 = []; results.forEach(function (result) { scoreLookup_1[result.item.id] = result; }); - return state.map(function (obj) { + state.forEach(function (obj) { var choice = obj; var result = scoreLookup_1[choice.id]; if (result !== undefined) { @@ -1471,102 +1103,110 @@ choice.rank = 0; choice.active = false; } - return choice; }); + break; } case "ACTIVATE_CHOICES" /* ActionType.ACTIVATE_CHOICES */: { var active_1 = action.active; - return state.map(function (obj) { + update = true; + state.forEach(function (obj) { var choice = obj; choice.active = active_1; return choice; }); + break; } case "CLEAR_CHOICES" /* ActionType.CLEAR_CHOICES */: { - return []; - } - default: { - return state; + update = true; + state = []; + break; } } + return { state: state, update: update }; } - var general = function (state, action) { - if (state === void 0) { state = 0; } - if (action === void 0) { action = {}; } - switch (action.type) { - case "SET_TRANSACTION" /* ActionType.SET_TRANSACTION */: { - if (action.txn) { - return state + 1; - } - return Math.max(0, state - 1); - } - default: { - return state; - } - } - }; - - var defaultState = { - groups: [], - items: [], - choices: [], - txn: 0, - }; - var appReducer = combineReducers({ - items: items, + var reducers = { groups: groups, + items: items, choices: choices, - txn: general, - }); - var rootReducer = function (passedState, action) { - var state = passedState; - // If we are clearing all items, groups and options we reassign - // state and then pass that state to our proper reducer. This isn't - // mutating our actual state - // See: http://stackoverflow.com/a/35641992 - if (action.type === "CLEAR_ALL" /* ActionType.CLEAR_ALL */) { - // preserve the txn state as to allow withTxn to work - var paused = state.txn; - state = cloneObject(defaultState); - state.txn = paused; - } - return appReducer(state, action); }; - - /* eslint-disable @typescript-eslint/no-explicit-any */ var Store = /** @class */ (function () { function Store() { - this._store = createStore(rootReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && - window.__REDUX_DEVTOOLS_EXTENSION__()); + this._store = this.defaultState; + this._listeners = []; + this._txn = 0; } - /** - * Subscribe store to function call (wrapped Redux method) - */ - Store.prototype.subscribe = function (onChange) { - this._store.subscribe(onChange); + Object.defineProperty(Store.prototype, "defaultState", { + // eslint-disable-next-line class-methods-use-this + get: function () { + return { + groups: [], + items: [], + choices: [], + }; + }, + enumerable: false, + configurable: true + }); + // eslint-disable-next-line class-methods-use-this + Store.prototype.changeSet = function (init) { + return { + groups: init, + items: init, + choices: init, + }; + }; + Store.prototype.resetStore = function () { + this._store = this.defaultState; + var changes = this.changeSet(true); + this._listeners.forEach(function (l) { return l(changes); }); + }; + Store.prototype.subscribe = function (onChange) { + this._listeners.push(onChange); }; - /** - * Dispatch event to store (wrapped Redux method) - */ Store.prototype.dispatch = function (action) { - this._store.dispatch(action); + var state = this._store; + var hasChanges = false; + var changes = this._outstandingChanges || this.changeSet(false); + Object.keys(reducers).forEach(function (key) { + var stateUpdate = reducers[key](state[key], action); + if (stateUpdate.update) { + hasChanges = true; + changes[key] = true; + state[key] = stateUpdate.state; + } + }); + if (hasChanges) { + if (this._txn) { + this._outstandingChanges = changes; + } + else { + this._listeners.forEach(function (l) { return l(changes); }); + } + } }; Store.prototype.withTxn = function (func) { - this._store.dispatch(setTxn(true)); + this._txn++; try { func(); } finally { - this._store.dispatch(setTxn(false)); + this._txn = Math.max(0, this._txn - 1); + if (!this._txn) { + var changeSet_1 = this._outstandingChanges; + if (changeSet_1) { + this._outstandingChanges = undefined; + this._listeners.forEach(function (l) { return l(changeSet_1); }); + } + } } }; Object.defineProperty(Store.prototype, "state", { /** - * Get store object (wrapping Redux method) + * Get store object */ get: function () { - return this._store.getState(); + return this._store; }, enumerable: false, configurable: true @@ -1636,10 +1276,10 @@ * Get active groups from store */ get: function () { - var _a = this, groups = _a.groups, choices = _a.choices; - return groups.filter(function (group) { + var _this = this; + return this.state.groups.filter(function (group) { var isActive = group.active && !group.disabled; - var hasActiveOptions = choices.some(function (choice) { return choice.active && !choice.disabled; }); + var hasActiveOptions = _this.state.choices.some(function (choice) { return choice.active && !choice.disabled; }); return isActive && hasActiveOptions; }, []); }, @@ -1647,7 +1287,7 @@ configurable: true }); Store.prototype.inTxn = function () { - return this.state.txn > 0; + return this._txn > 0; }; /** * Get single choice by it's ID @@ -3252,9 +2892,6 @@ } this.initialised = false; this._store = new Store(); - this._initialState = defaultState; - this._currentState = defaultState; - this._prevState = defaultState; this._currentValue = ''; this.config.searchEnabled = (!this._isTextElement && this.config.searchEnabled) || @@ -3337,8 +2974,7 @@ this._createTemplates(); this._createElements(); this._createStructure(); - this._store.subscribe(this._render); - this._render(); + this._initStore(); this._addEventListeners(); var shouldDisable = (this._isTextElement && !this.config.addItems) || this.passedElement.element.hasAttribute('disabled') || @@ -3362,6 +2998,7 @@ this.passedElement.reveal(); this.containerOuter.unwrap(this.passedElement.element); this.clearStore(); + this._store._listeners = []; this._stopSearch(); this._templates = templates; this.initialised = false; @@ -3767,7 +3404,7 @@ return this; }; Choices.prototype.clearStore = function () { - this._store.dispatch(clearAll()); + this._store.resetStore(); this._lastAddedChoiceId = 0; this._lastAddedGroupId = 0; // @todo integrate with Store @@ -3796,15 +3433,12 @@ } } }; - Choices.prototype._render = function () { + Choices.prototype._render = function (changes) { if (this._store.inTxn()) { return; } - this._currentState = this._store.state; - var shouldRenderItems = this._currentState.items !== this._prevState.items; - var stateChanged = this._currentState.choices !== this._prevState.choices || - this._currentState.groups !== this._prevState.groups || - shouldRenderItems; + var shouldRenderItems = changes === null || changes === void 0 ? void 0 : changes.items; + var stateChanged = (changes === null || changes === void 0 ? void 0 : changes.choices) || (changes === null || changes === void 0 ? void 0 : changes.groups) || shouldRenderItems; if (!stateChanged) { return; } @@ -3814,7 +3448,6 @@ if (shouldRenderItems) { this._renderItems(); } - this._prevState = this._currentState; }; Choices.prototype._renderChoices = function () { var _this = this; @@ -5033,7 +4666,6 @@ }); }; Choices.prototype._createStructure = function () { - var _this = this; // Hide original element this.passedElement.conceal(); // Wrap input in container preserving DOM ordering @@ -5061,6 +4693,10 @@ } this._highlightPosition = 0; this._isSearching = false; + }; + Choices.prototype._initStore = function () { + var _this = this; + this._store.subscribe(this._render); this._store.withTxn(function () { _this._addPredefinedChoices(_this._presetChoices, _this._isSelectOneElement && !_this._hasNonChoicePlaceholder, false); }); diff --git a/public/assets/scripts/choices.search-basic.min.js b/public/assets/scripts/choices.search-basic.min.js index 92b9c70f..1229fb5b 100644 --- a/public/assets/scripts/choices.search-basic.min.js +++ b/public/assets/scripts/choices.search-basic.min.js @@ -1,2 +1,2 @@ /*! choices.js v11.0.0-rc5 | © 2024 Josh Johnson | https://github.com/jshjohnson/Choices#readme */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).Choices=t()}(this,(function(){"use strict";var e=function(t,i){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},e(t,i)};function t(t,i){if("function"!=typeof i&&null!==i)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");function n(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(n.prototype=i.prototype,new n)}var i=function(){return i=Object.assign||function(e){for(var t,i=1,n=arguments.length;i/g,">").replace(/0?this.element.scrollTop+r-s:e.offsetTop;requestAnimationFrame((function(){i._animateScroll(c,t)}))}},e.prototype._scrollDown=function(e,t,i){var n=(i-e)/t,s=n>1?n:1;this.element.scrollTop=e+s},e.prototype._scrollUp=function(e,t,i){var n=(e-i)/t,s=n>1?n:1;this.element.scrollTop=e-s},e.prototype._animateScroll=function(e,t){var i=this,n=this.element.scrollTop,s=!1;t>0?(this._scrollDown(n,4,e),ne&&(s=!0)),s&&requestAnimationFrame((function(){i._animateScroll(e,t)}))},e}(),w=function(){function e(e){var t=e.element,i=e.classNames;this.element=t,this.classNames=i,this.isDisabled=!1}return Object.defineProperty(e.prototype,"isActive",{get:function(){return"active"===this.element.dataset.choice},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dir",{get:function(){return this.element.dir},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.element.value},set:function(e){this.element.setAttribute("value",e),this.element.value=e},enumerable:!1,configurable:!0}),e.prototype.conceal=function(){var e;(e=this.element.classList).add.apply(e,d(this.classNames.input)),this.element.hidden=!0,this.element.tabIndex=-1;var t=this.element.getAttribute("style");t&&this.element.setAttribute("data-choice-orig-style",t),this.element.setAttribute("data-choice","active")},e.prototype.reveal=function(){var e;(e=this.element.classList).remove.apply(e,d(this.classNames.input)),this.element.hidden=!1,this.element.removeAttribute("tabindex");var t=this.element.getAttribute("data-choice-orig-style");t?(this.element.removeAttribute("data-choice-orig-style"),this.element.setAttribute("style",t)):this.element.removeAttribute("style"),this.element.removeAttribute("data-choice"),this.element.value=this.element.value},e.prototype.enable=function(){this.element.removeAttribute("disabled"),this.element.disabled=!1,this.isDisabled=!1},e.prototype.disable=function(){this.element.setAttribute("disabled",""),this.element.disabled=!0,this.isDisabled=!0},e.prototype.triggerEvent=function(e,t){!function(e,t,i){void 0===i&&(i=null);var n=new CustomEvent(t,{detail:i,bubbles:!0,cancelable:!0});e.dispatchEvent(n)}(this.element,e,t||{})},e}(),C=function(e){function i(){return null!==e&&e.apply(this,arguments)||this}return t(i,e),i}(w),I=function(e,t){return void 0===t&&(t=!0),void 0===e?t:!!e},S=function(e){if("string"==typeof e&&(e=e.split(" ").filter((function(e){return 0!==e.length}))),Array.isArray(e)&&0!==e.length)return e},O=function(e,t){if("string"==typeof e)return O({value:e,label:e},!1);var i=e;if("choices"in i){if(!t)throw new TypeError("optGroup is not allowed");var n=i,s=n.choices.map((function(e){return O(e,!1)}));return{id:0,label:l(n.label)||n.value,active:0!==s.length,disabled:!!n.disabled,choices:s}}var o=i;return{id:0,groupId:0,score:0,rank:0,value:o.value,label:o.label||o.value,active:I(o.active),selected:I(o.selected,!1),disabled:I(o.disabled,!1),placeholder:I(o.placeholder,!1),highlighted:!1,labelClass:S(o.labelClass),labelDescription:o.labelDescription,customProperties:o.customProperties}},A=function(e){function i(t){var i=t.element,n=t.classNames,s=t.template,o=t.extractPlaceholder,r=e.call(this,{element:i,classNames:n})||this;return r.template=s,r.extractPlaceholder=o,r}return t(i,e),Object.defineProperty(i.prototype,"placeholderOption",{get:function(){return this.element.querySelector('option[value=""]')||this.element.querySelector("option[placeholder]")},enumerable:!1,configurable:!0}),i.prototype.addOptions=function(e){var t=this;e.forEach((function(e){var i=e;if(!i.element){var n=t.template(i);t.element.appendChild(n),i.element=n}}))},i.prototype.optionsAsChoices=function(){var e=this,t=[];return this.element.querySelectorAll(":scope > option, :scope > optgroup").forEach((function(i){!function(e){return"OPTION"===e.tagName}(i)?function(e){return"OPTGROUP"===e.tagName}(i)&&t.push(e._optgroupToChoice(i)):t.push(e._optionToChoice(i))})),t},i.prototype._optionToChoice=function(e){return{id:0,groupId:0,score:0,rank:0,value:e.value,label:e.innerHTML,element:e,active:!0,selected:this.extractPlaceholder?e.selected:e.hasAttribute("selected"),disabled:e.disabled,highlighted:!1,placeholder:this.extractPlaceholder&&(""===e.value||e.hasAttribute("placeholder")),labelClass:void 0!==e.dataset.labelClass?S(e.dataset.labelClass):void 0,labelDescription:void 0!==e.dataset.labelDescription?e.dataset.labelDescription:void 0,customProperties:f(e.dataset.customProperties)}},i.prototype._optgroupToChoice=function(e){var t=this,i=e.querySelectorAll("option"),n=Array.from(i).map((function(e){return t._optionToChoice(e)}));return{id:0,label:e.label||"",element:e,active:0!==n.length,disabled:e.disabled,choices:n}},i}(w),T={items:[],choices:[],silent:!1,renderChoiceLimit:-1,maxItemCount:-1,singleModeForMultiSelect:!1,addChoices:!1,addItems:!0,addItemFilter:function(e){return!!e&&""!==e},removeItems:!0,removeItemButton:!1,removeItemButtonAlignLeft:!1,editItems:!1,allowHTML:!1,allowHtmlUserInput:!1,duplicateItemsAllowed:!0,delimiter:",",paste:!0,searchEnabled:!0,searchChoices:!0,searchFloor:1,searchResultLimit:4,searchFields:["label","value"],position:"auto",resetScrollPosition:!0,shouldSort:!0,shouldSortItems:!1,sorter:function(e,t){var i=e.value,n=e.label,s=void 0===n?i:n,o=t.value,r=t.label,c=void 0===r?o:r;return l(s).localeCompare(l(c),[],{sensitivity:"base",ignorePunctuation:!0,numeric:!0})},shadowRoot:null,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 "'.concat(e,'"')},removeItemIconText:function(){return"Remove item"},removeItemLabelText:function(e){return"Remove item: ".concat(e)},maxItemText:function(e){return"Only ".concat(e," values can be added")},valueComparer:function(e,t){return e===t},fuseOptions:{includeScore:!0},labelId:"",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"],description:["choices__description"],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"],selectedState:["is-selected"],flippedState:["is-flipped"],loadingState:["is-loading"],addChoice:["choices__item","choices__item--selectable","add-choice"],noResults:["has-no-results"],noChoices:["has-no-choices"]},appendGroupInSearch:!1},L=["fuseOptions","classNames"];function x(e){return"Minified Redux error #"+e+"; visit https://redux.js.org/Errors?code="+e+" for the full message or use the non-minified dev environment for full errors. "}var N="function"==typeof Symbol&&Symbol.observable||"@@observable",M=function(){return Math.random().toString(36).substring(7).split("").join(".")},F={INIT:"@@redux/INIT"+M(),REPLACE:"@@redux/REPLACE"+M(),PROBE_UNKNOWN_ACTION:function(){return"@@redux/PROBE_UNKNOWN_ACTION"+M()}};function j(e,t,i){var n;if("function"==typeof t&&"function"==typeof i||"function"==typeof i&&"function"==typeof arguments[3])throw new Error(x(0));if("function"==typeof t&&void 0===i&&(i=t,t=void 0),void 0!==i){if("function"!=typeof i)throw new Error(x(1));return i(j)(e,t)}if("function"!=typeof e)throw new Error(x(2));var s=e,o=t,r=[],c=r,a=!1;function h(){c===r&&(c=r.slice())}function l(){if(a)throw new Error(x(3));return o}function u(e){if("function"!=typeof e)throw new Error(x(4));if(a)throw new Error(x(5));var t=!0;return h(),c.push(e),function(){if(t){if(a)throw new Error(x(6));t=!1,h();var i=c.indexOf(e);c.splice(i,1),r=null}}}function d(e){if(!function(e){if("object"!=typeof e||null===e)return!1;for(var t=e;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}(e))throw new Error(x(7));if(void 0===e.type)throw new Error(x(8));if(a)throw new Error(x(9));try{a=!0,o=s(o,e)}finally{a=!1}for(var t=r=c,i=0;i0},e.prototype.getChoiceById=function(e){return this.activeChoices.find((function(t){return t.id===e}))},e.prototype.getGroupById=function(e){return this.groups.find((function(t){return t.id===e}))},e}(),R=function(e,t){return e?function(e){if("string"==typeof e)return e;if("object"==typeof e){if("escaped"in e)return e.escaped;if("trusted"in e)return e.trusted}return""}(t):a(t)},K=function(e,t){if(t){var i=e.dataset;"string"==typeof t?i.customProperties=t:"object"!=typeof t||function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}(t)||(i.customProperties=JSON.stringify(t))}},V={containerOuter:function(e,t,i,n,s,o,r){var c=e.classNames.containerOuter,a=Object.assign(document.createElement("div"),{className:d(c).join(" ")});return a.dataset.type=o,t&&(a.dir=t),n&&(a.tabIndex=0),i&&(a.setAttribute("role",s?"combobox":"listbox"),s&&a.setAttribute("aria-autocomplete","list")),a.setAttribute("aria-haspopup","true"),a.setAttribute("aria-expanded","false"),r&&a.setAttribute("aria-labelledby",r),a},containerInner:function(e){var t=e.classNames.containerInner;return Object.assign(document.createElement("div"),{className:d(t).join(" ")})},itemList:function(e,t){var i=e.classNames,n=i.list,s=i.listSingle,o=i.listItems;return Object.assign(document.createElement("div"),{className:"".concat(d(n).join(" ")," ").concat(t?d(s).join(" "):d(o).join(" "))})},placeholder:function(e,t){var i=e.allowHTML,n=e.classNames.placeholder;return Object.assign(document.createElement("div"),{className:d(n).join(" "),innerHTML:R(i,t)})},item:function(e,t,i){var n,s,o,r=e.allowHTML,c=e.removeItemButtonAlignLeft,h=e.classNames,l=h.item,u=h.button,p=h.highlightedState,f=h.itemSelectable,m=h.placeholder,g=t.id,v=t.value,_=t.label,y=t.labelClass,b=t.labelDescription,E=t.customProperties,w=t.active,C=t.disabled,I=t.highlighted,S=t.placeholder,O=Object.assign(document.createElement("div"),{className:d(l).join(" ")});if(y){var A=Object.assign(document.createElement("span"),{innerHTML:R(r,_),className:d(y).join(" ")});O.appendChild(A)}else O.innerHTML=R(r,_);if(Object.assign(O.dataset,{item:"",id:g,value:v}),y&&(O.dataset.labelClass=d(y).join(" ")),b&&(O.dataset.labelDescription=b),K(O,E),w&&O.setAttribute("aria-selected","true"),C&&O.setAttribute("aria-disabled","true"),S&&((n=O.classList).add.apply(n,d(m)),O.dataset.placeholder=""),(s=O.classList).add.apply(s,d(I?p:f)),i){C&&(o=O.classList).remove.apply(o,d(f)),O.dataset.deletable="";var T="function"==typeof this.config.removeItemIconText?this.config.removeItemIconText(a(v),v):this.config.removeItemIconText,L="function"==typeof this.config.removeItemLabelText?this.config.removeItemLabelText(a(v),v):this.config.removeItemLabelText,x=Object.assign(document.createElement("button"),{type:"button",className:d(u).join(" "),innerHTML:T});L&&x.setAttribute("aria-label",L),x.dataset.button="",c?O.insertAdjacentElement("afterbegin",x):O.appendChild(x)}return O},choiceList:function(e,t){var i=e.classNames.list,n=Object.assign(document.createElement("div"),{className:d(i).join(" ")});return t||n.setAttribute("aria-multiselectable","true"),n.setAttribute("role","listbox"),n},choiceGroup:function(e,t){var i=e.allowHTML,n=e.classNames,s=n.group,o=n.groupHeading,r=n.itemDisabled,c=t.id,a=t.label,h=t.disabled,l=Object.assign(document.createElement("div"),{className:"".concat(d(s).join(" ")," ").concat(h?d(r).join(" "):"")});return l.setAttribute("role","group"),Object.assign(l.dataset,{group:"",id:c,value:a}),h&&l.setAttribute("aria-disabled","true"),l.appendChild(Object.assign(document.createElement("div"),{className:d(o).join(" "),innerHTML:R(i,a)})),l},choice:function(e,t,i){var n,s,o,r,c,a=e.allowHTML,h=e.classNames,l=h.item,u=h.itemChoice,p=h.itemSelectable,f=h.selectedState,m=h.itemDisabled,g=h.description,v=h.placeholder,_=t.id,y=t.value,b=t.label,E=t.groupId,w=t.elementId,C=t.labelClass,I=t.labelDescription,S=t.disabled,O=t.selected,A=t.placeholder,T=Object.assign(document.createElement("div"),{id:w,className:"".concat(d(l).join(" ")," ").concat(d(u).join(" "))}),L=T;if(C){var x=Object.assign(document.createElement("span"),{innerHTML:R(a,b),className:d(C).join(" ")});L=x,T.appendChild(x)}else T.innerHTML=R(a,b);if(I){var N="".concat(w,"-description");L.setAttribute("aria-describedby",N);var M=Object.assign(document.createElement("span"),{innerHTML:R(a,I),id:N});(n=M.classList).add.apply(n,d(g)),T.appendChild(M)}return O&&(s=T.classList).add.apply(s,d(f)),A&&(o=T.classList).add.apply(o,d(v)),T.setAttribute("role",E&&E>0?"treeitem":"option"),Object.assign(T.dataset,{choice:"",id:_,value:y,selectText:i}),C&&(T.dataset.labelClass=d(C).join(" ")),I&&(T.dataset.labelDescription=I),S?((r=T.classList).add.apply(r,d(m)),T.dataset.choiceDisabled="",T.setAttribute("aria-disabled","true")):((c=T.classList).add.apply(c,d(p)),T.dataset.choiceSelectable=""),T},input:function(e,t){var i=e.classNames,n=i.input,s=i.inputCloned,o=Object.assign(document.createElement("input"),{type:"search",className:"".concat(d(n).join(" ")," ").concat(d(s).join(" ")),autocomplete:"off",autocapitalize:"off",spellcheck:!1});return o.setAttribute("role","textbox"),o.setAttribute("aria-autocomplete","list"),t&&o.setAttribute("aria-label",t),o},dropdown:function(e){var t,i,n=e.classNames,s=n.list,o=n.listDropdown,r=document.createElement("div");return(t=r.classList).add.apply(t,d(s)),(i=r.classList).add.apply(i,d(o)),r.setAttribute("aria-expanded","false"),r},notice:function(e,t,i){var s=e.allowHTML,o=e.classNames,r=o.item,c=o.itemChoice,a=o.addChoice,h=o.noResults,l=o.noChoices;void 0===i&&(i="");var u=n(n([],d(r),!0),d(c),!0);switch(i){case"add-choice":u.push.apply(u,d(a));break;case"no-results":u.push.apply(u,d(h));break;case"no-choices":u.push.apply(u,d(l))}var p=Object.assign(document.createElement("div"),{innerHTML:R(s,t),className:u.join(" ")});return"add-choice"===i&&(p.dataset.choiceSelectable="",p.dataset.choice=""),p},option:function(e){var t=e.label,i=e.value,n=e.labelClass,s=e.labelDescription,o=e.customProperties,r=e.active,c=e.disabled,a=l(t),h=new Option(a,i,!1,r);return n&&(h.dataset.labelClass=d(n).join(" ")),s&&(h.dataset.labelDescription=s),K(h,o),h.disabled=c,h}};function B(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function U(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function q(e){for(var t=1;t`Missing ${e} property in key`,ie=e=>`Property 'weight' in key '${e}' must be a positive integer`,ne=Object.prototype.hasOwnProperty;class se{constructor(e){this._keys=[],this._keyMap={};let t=0;e.forEach((e=>{let i=oe(e);this._keys.push(i),this._keyMap[i.id]=i,t+=i.weight})),this._keys.forEach((e=>{e.weight/=t}))}get(e){return this._keyMap[e]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function oe(e){let t=null,i=null,n=null,s=1,o=null;if(X(e)||G(e))n=e,t=re(e),i=ce(e);else{if(!ne.call(e,"name"))throw new Error(te("name"));const r=e.name;if(n=r,ne.call(e,"weight")&&(s=e.weight,s<=0))throw new Error(ie(r));t=re(r),i=ce(r),o=e.getFn}return{path:t,id:i,weight:s,src:n,getFn:o}}function re(e){return G(e)?e:e.split(".")}function ce(e){return G(e)?e.join("."):e}const ae={useExtendedSearch:!1,getFn:function(e,t){let i=[],n=!1;const s=(e,t,o)=>{if(Y(e))if(t[o]){const r=e[t[o]];if(!Y(r))return;if(o===t.length-1&&(X(r)||J(r)||z(r)))i.push($(r));else if(G(r)){n=!0;for(let e=0,i=r.length;ee.score===t.score?e.idx{this._keysMap[e.id]=t}))}create(){!this.isCreated&&this.docs.length&&(this.isCreated=!0,X(this.docs[0])?this.docs.forEach(((e,t)=>{this._addString(e,t)})):this.docs.forEach(((e,t)=>{this._addObject(e,t)})),this.norm.clear())}add(e){const t=this.size();X(e)?this._addString(e,t):this._addObject(e,t)}removeAt(e){this.records.splice(e,1);for(let t=e,i=this.size();t{let s=t.getFn?t.getFn(e):this.getFn(e,t.path);if(Y(s))if(G(s)){let e=[];const t=[{nestedArrIndex:-1,value:s}];for(;t.length;){const{nestedArrIndex:i,value:n}=t.pop();if(Y(n))if(X(n)&&!Z(n)){let t={v:n,i:i,n:this.norm.get(n)};e.push(t)}else G(n)&&n.forEach(((e,i)=>{t.push({nestedArrIndex:i,value:e})}))}i.$[n]=e}else if(X(s)&&!Z(s)){let e={v:s,n:this.norm.get(s)};i.$[n]=e}})),this.records.push(i)}toJSON(){return{keys:this.keys,records:this.records}}}function de(e,t,{getFn:i=he.getFn,fieldNormWeight:n=he.fieldNormWeight}={}){const s=new ue({getFn:i,fieldNormWeight:n});return s.setKeys(e.map(oe)),s.setSources(t),s.create(),s}function pe(e,{errors:t=0,currentLocation:i=0,expectedLocation:n=0,distance:s=he.distance,ignoreLocation:o=he.ignoreLocation}={}){const r=t/e.length;if(o)return r;const c=Math.abs(n-i);return s?r+c/s:c?1:r}const fe=32;function me(e,t,i,{location:n=he.location,distance:s=he.distance,threshold:o=he.threshold,findAllMatches:r=he.findAllMatches,minMatchCharLength:c=he.minMatchCharLength,includeMatches:a=he.includeMatches,ignoreLocation:h=he.ignoreLocation}={}){if(t.length>fe)throw new Error(`Pattern length exceeds max of ${fe}.`);const l=t.length,u=e.length,d=Math.max(0,Math.min(n,u));let p=o,f=d;const m=c>1||a,g=m?Array(u):[];let v;for(;(v=e.indexOf(t,f))>-1;){let e=pe(t,{currentLocation:v,expectedLocation:d,distance:s,ignoreLocation:h});if(p=Math.min(e,p),f=v+l,m){let e=0;for(;e=a;o-=1){let r=o-1,c=i[e.charAt(r)];if(m&&(g[r]=+!!c),w[o]=(w[o+1]<<1|1)&c,n&&(w[o]|=(_[o+1]|_[o])<<1|1|_[o+1]),w[o]&E&&(y=pe(t,{errors:n,currentLocation:r,expectedLocation:d,distance:s,ignoreLocation:h}),y<=p)){if(p=y,f=r,f<=d)break;a=Math.max(1,2*d-f)}}if(pe(t,{errors:n+1,currentLocation:d,expectedLocation:d,distance:s,ignoreLocation:h})>p)break;_=w}const w={isMatch:f>=0,score:Math.max(.001,y)};if(m){const e=function(e=[],t=he.minMatchCharLength){let i=[],n=-1,s=-1,o=0;for(let r=e.length;o=t&&i.push([n,s]),n=-1)}return e[o-1]&&o-n>=t&&i.push([n,o-1]),i}(g,c);e.length?a&&(w.indices=e):w.isMatch=!1}return w}function ge(e){let t={};for(let i=0,n=e.length;i{this.chunks.push({pattern:e,alphabet:ge(e),startIndex:t})},l=this.pattern.length;if(l>fe){let e=0;const t=l%fe,i=l-t;for(;e{const{isMatch:f,score:m,indices:g}=me(e,t,d,{location:n+p,distance:s,threshold:o,findAllMatches:r,minMatchCharLength:c,includeMatches:i,ignoreLocation:a});f&&(u=!0),l+=m,f&&g&&(h=[...h,...g])}));let d={isMatch:u,score:u?l/this.chunks.length:1};return u&&i&&(d.indices=h),d}}const _e=[];function ye(e,t){for(let i=0,n=_e.length;i!(!e[be]&&!e[Ee]),Se=e=>({[be]:Object.keys(e).map((t=>({[t]:e[t]})))});function Oe(e,t){const i=e.matches;t.matches=[],Y(i)&&i.forEach((e=>{if(!Y(e.indices)||!e.indices.length)return;const{indices:i,value:n}=e;let s={indices:i,value:n};e.key&&(s.key=e.key.src),e.idx>-1&&(s.refIndex=e.idx),t.matches.push(s)}))}function Ae(e,t){t.score=e.score}class Te{constructor(e,t={},i){if(this.options=q(q({},he),t),this.options.useExtendedSearch)throw new Error("Extended search is not available");this._keyStore=new se(this.options.keys),this.setCollection(e,i)}setCollection(e,t){if(this._docs=e,t&&!(t instanceof ue))throw new Error("Incorrect 'index' type");this._myIndex=t||de(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(e){Y(e)&&(this._docs.push(e),this._myIndex.add(e))}remove(e=()=>!1){const t=[];for(let i=0,n=this._docs.length;i{let i=1;e.matches.forEach((({key:e,norm:n,score:s})=>{const o=e?e.weight:null;i*=Math.pow(0===s&&o?Number.EPSILON:s,(o||1)*(t?1:n))})),e.score=i}))}(c,{ignoreFieldNorm:r}),s&&c.sort(o),J(t)&&t>-1&&(c=c.slice(0,t)),function(e,t,{includeMatches:i=he.includeMatches,includeScore:n=he.includeScore}={}){const s=[];return i&&s.push(Oe),n&&s.push(Ae),e.map((e=>{const{idx:i}=e,n={item:t[i],refIndex:i};return s.length&&s.forEach((t=>{t(e,n)})),n}))}(c,this._docs,{includeMatches:i,includeScore:n})}_searchStringList(e){const t=ye(e,this.options),{records:i}=this._myIndex,n=[];return i.forEach((({v:e,i:i,n:s})=>{if(!Y(e))return;const{isMatch:o,score:r,indices:c}=t.searchIn(e);o&&n.push({item:e,idx:i,matches:[{score:r,value:e,norm:s,indices:c}]})})),n}_searchLogical(e){throw new Error("Logical search is not available")}_searchObjectList(e){const t=ye(e,this.options),{keys:i,records:n}=this._myIndex,s=[];return n.forEach((({$:e,i:n})=>{if(!Y(e))return;let o=[];i.forEach(((i,n)=>{o.push(...this._findMatches({key:i,value:e[n],searcher:t}))})),o.length&&s.push({idx:n,item:e,matches:o})})),s}_findMatches({key:e,value:t,searcher:i}){if(!Y(t))return[];let n=[];if(G(t))t.forEach((({v:t,i:s,n:o})=>{if(!Y(t))return;const{isMatch:r,score:c,indices:a}=i.searchIn(t);r&&n.push({score:c,key:e,value:t,idx:s,norm:o,indices:a})}));else{const{v:s,n:o}=t,{isMatch:r,score:c,indices:a}=i.searchIn(s);r&&n.push({score:c,key:e,value:s,norm:o,indices:a})}return n}}Te.version="7.0.0",Te.createIndex=de,Te.parseIndex=function(e,{getFn:t=he.getFn,fieldNormWeight:i=he.fieldNormWeight}={}){const{keys:n,records:s}=e,o=new ue({getFn:t,fieldNormWeight:i});return o.setKeys(n),o.setIndexRecords(s),o},Te.config=he,Te.parseQuery=function(e,t,{auto:i=!0}={}){const n=e=>{let s=Object.keys(e);const o=(e=>!!e[we])(e);if(!o&&s.length>1&&!Ie(e))return n(Se(e));if((e=>!G(e)&&Q(e)&&!Ie(e))(e)){const n=o?e[we]:s[0],r=o?e[Ce]:e[n];if(!X(r))throw new Error((e=>`Invalid value for key ${e}`)(n));const c={keyId:ce(n),pattern:r};return i&&(c.searcher=ye(r,t)),c}let r={children:[],operator:s[0]};return s.forEach((t=>{const i=e[t];G(i)&&i.forEach((e=>{r.children.push(n(e))}))})),r};return Ie(e)||(e=Se(e)),n(e)};var Le=function(){function e(e){this._haystack=[],this._fuseOptions=i(i({},e.fuseOptions),{keys:n([],e.searchFields,!0),includeMatches:!0})}return e.prototype.index=function(e){this._haystack=e,this._fuse&&this._fuse.setCollection(e)},e.prototype.reset=function(){this._haystack=[],this._fuse=void 0},e.prototype.isEmptyIndex=function(){return 0===this._haystack.length},e.prototype.search=function(e){return this._fuse||(this._fuse=new Te(this._haystack,this._fuseOptions)),this._fuse.search(e).map((function(e,t){return{item:e.item,score:e.score||0,rank:t}}))},e}();var xe="-ms-scroll-limit"in document.documentElement.style&&"-ms-ime-align"in document.documentElement.style,Ne={},Me=function(e){if(e){var t=e.dataset.id;return t?parseInt(t,10):void 0}},Fe=function(){function e(t,n){void 0===t&&(t="[data-choice]"),void 0===n&&(n={});var s=this;this.initialisedOK=void 0,this._hasNonChoicePlaceholder=!1,this._lastAddedChoiceId=0,this._lastAddedGroupId=0,this.config=i(i(i({},e.defaults.allOptions),e.defaults.options),n),L.forEach((function(t){s.config[t]=i(i(i({},e.defaults.allOptions[t]),e.defaults.options[t]),n[t])})),this.config.silent||this._validateConfig();var o=this.config.shadowRoot||document.documentElement,r="string"==typeof t?o.querySelector(t):t;if(!r||"object"!=typeof r||"INPUT"!==r.tagName&&!function(e){return"SELECT"===e.tagName}(r)){if(!r&&"string"==typeof t)throw TypeError("Selector ".concat(t," failed to find an element"));throw TypeError("Expected one of the following types text|select-one|select-multiple")}if(this._elementType=r.type,this._isTextElement=this._elementType===g,(this._isTextElement||1!==this.config.maxItemCount)&&(this.config.singleModeForMultiSelect=!1),this.config.singleModeForMultiSelect&&(this._elementType=_),this._isSelectOneElement=this._elementType===v,this._isSelectMultipleElement=this._elementType===_,this._isSelectElement=this._isSelectOneElement||this._isSelectMultipleElement,this._canAddUserChoices=this._isTextElement&&this.config.addItems||this._isSelectElement&&this.config.addChoices,["auto","always"].includes("".concat(this.config.renderSelectedChoices))||(this.config.renderSelectedChoices="auto"),this.config.placeholder&&(this.config.placeholderValue?this._hasNonChoicePlaceholder=!0:r.dataset.placeholder&&(this._hasNonChoicePlaceholder=!0,this.config.placeholderValue=r.dataset.placeholder)),n.addItemFilter&&"function"!=typeof n.addItemFilter){var a=n.addItemFilter instanceof RegExp?n.addItemFilter:new RegExp(n.addItemFilter);this.config.addItemFilter=a.test.bind(a)}if(this._isTextElement)this.passedElement=new C({element:r,classNames:this.config.classNames});else{var h=r;this.passedElement=new A({element:h,classNames:this.config.classNames,template:function(e){return s._templates.option(e)},extractPlaceholder:this.config.placeholder&&!this._hasNonChoicePlaceholder})}if(this.initialised=!1,this._store=new H,this._initialState=D,this._currentState=D,this._prevState=D,this._currentValue="",this.config.searchEnabled=!this._isTextElement&&this.config.searchEnabled||this._elementType===_,this._canSearch=this.config.searchEnabled,this._isScrollingOnIe=!1,this._highlightPosition=0,this._wasTap=!0,this._placeholderValue=this._generatePlaceholderValue(),this._baseId=function(e,t){var i=e.id||e.name&&"".concat(e.name,"-").concat(c(2))||c(4);return i=i.replace(/(:|\.|\[|\]|,)/g,""),"".concat(t,"-").concat(i)}(this.passedElement.element,"choices-"),this._direction=this.passedElement.dir,!this._direction){var l=window.getComputedStyle(this.passedElement.element).direction;l!==window.getComputedStyle(document.documentElement).direction&&(this._direction=l)}if(this._idNames={itemChoice:"item-choice"},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._onInput=this._onInput.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._onSelectKey=this._onSelectKey.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.passedElement.isActive)return this.config.silent||console.warn("Trying to initialise Choices on element already initialised",{element:t}),this.initialised=!0,void(this.initialisedOK=!1);this.init(),this._initialItems=this._store.items.map((function(e){return e.value}))}return Object.defineProperty(e,"defaults",{get:function(){return Object.preventExtensions({get options(){return Ne},get allOptions(){return T},get templates(){return V}})},enumerable:!1,configurable:!0}),e.prototype.init=function(){if(!this.initialised&&void 0===this.initialisedOK){var e;this._searcher=(e=this.config,new Le(e)),this._loadChoices(),this._createTemplates(),this._createElements(),this._createStructure(),this._store.subscribe(this._render),this._render(),this._addEventListeners(),(this._isTextElement&&!this.config.addItems||this.passedElement.element.hasAttribute("disabled")||!!this.passedElement.element.closest("fieldset:disabled"))&&this.disable(),this.initialised=!0,this.initialisedOK=!0;var t=this.config.callbackOnInit;t&&"function"==typeof t&&t.call(this)}},e.prototype.destroy=function(){this.initialised&&(this._removeEventListeners(),this.passedElement.reveal(),this.containerOuter.unwrap(this.passedElement.element),this.clearStore(),this._stopSearch(),this._templates=V,this.initialised=!1,this.initialisedOK=void 0)},e.prototype.enable=function(){return this.passedElement.isDisabled&&this.passedElement.enable(),this.containerOuter.isDisabled&&(this._addEventListeners(),this.input.enable(),this.containerOuter.enable()),this},e.prototype.disable=function(){return this.passedElement.isDisabled||this.passedElement.disable(),this.containerOuter.isDisabled||(this._removeEventListeners(),this.input.disable(),this.containerOuter.disable()),this},e.prototype.highlightItem=function(e,t){if(void 0===t&&(t=!0),!e||!e.id)return this;var i=this._store.choices.find((function(t){return t.id===e.id}));return!i||i.highlighted||(this._store.dispatch(o(i,!0)),t&&this.passedElement.triggerEvent("highlightItem",this._getChoiceForOutput(i))),this},e.prototype.unhighlightItem=function(e,t){if(void 0===t&&(t=!0),!e||!e.id)return this;var i=this._store.choices.find((function(t){return t.id===e.id}));return i&&i.highlighted?(this._store.dispatch(o(i,!1)),t&&this.passedElement.triggerEvent("highlightItem",this._getChoiceForOutput(i)),this):this},e.prototype.highlightAll=function(){var e=this;return this._store.withTxn((function(){e._store.items.forEach((function(t){return e.highlightItem(t)}))})),this},e.prototype.unhighlightAll=function(){var e=this;return this._store.withTxn((function(){e._store.items.forEach((function(t){return e.unhighlightItem(t)}))})),this},e.prototype.removeActiveItemsByValue=function(e){var t=this;return this._store.withTxn((function(){t._store.items.filter((function(t){return t.value===e})).forEach((function(e){return t._removeItem(e)}))})),this},e.prototype.removeActiveItems=function(e){var t=this;return this._store.withTxn((function(){t._store.items.filter((function(t){return t.id!==e})).forEach((function(e){return t._removeItem(e)}))})),this},e.prototype.removeHighlightedItems=function(e){var t=this;return void 0===e&&(e=!1),this._store.withTxn((function(){t._store.highlightedActiveItems.forEach((function(i){t._removeItem(i),e&&t._triggerChange(i.value)}))})),this},e.prototype.showDropdown=function(e){var t=this;return this.dropdown.isActive||requestAnimationFrame((function(){t.dropdown.show(),t.containerOuter.open(t.dropdown.distanceFromTopWindow),!e&&t._canSearch&&t.input.focus(),t.passedElement.triggerEvent("showDropdown")})),this},e.prototype.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("hideDropdown")})),this):this},e.prototype.getValue=function(e){var t=this;void 0===e&&(e=!1);var i=this._store.items.reduce((function(i,n){var s=e?n.value:t._getChoiceForOutput(n);return i.push(s),i}),[]);return this._isSelectOneElement||this.config.singleModeForMultiSelect?i[0]:i},e.prototype.setValue=function(e){var t=this;return this.initialisedOK?(this._store.withTxn((function(){e.forEach((function(e){e&&t._addChoice(O(e,!1))}))})),this._searcher.reset(),this):(this._warnChoicesInitFailed("setValue"),this)},e.prototype.setChoiceByValue=function(e){var t=this;return this.initialisedOK?(this._isTextElement||(this._store.withTxn((function(){(Array.isArray(e)?e:[e]).forEach((function(e){return t._findAndSelectChoiceByValue(e)}))})),this._searcher.reset()),this):(this._warnChoicesInitFailed("setChoiceByValue"),this)},e.prototype.setChoices=function(e,t,n,s){var o=this;if(void 0===e&&(e=[]),void 0===t&&(t="value"),void 0===n&&(n="label"),void 0===s&&(s=!1),!this.initialisedOK)return this._warnChoicesInitFailed("setChoices"),this;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(s&&this.clearChoices(),"function"==typeof e){var r=e(this);if("function"==typeof Promise&&r instanceof Promise)return new Promise((function(e){return requestAnimationFrame(e)})).then((function(){return o._handleLoadingState(!0)})).then((function(){return r})).then((function(e){return o.setChoices(e,t,n,s)})).catch((function(e){o.config.silent||console.error(e)})).then((function(){return o._handleLoadingState(!1)})).then((function(){return o}));if(!Array.isArray(r))throw new TypeError(".setChoices first argument function must return either array of choices or Promise, got: ".concat(typeof r));return this.setChoices(r,t,n,!1)}if(!Array.isArray(e))throw new TypeError(".setChoices must be called either with array of choices with a function resulting into Promise of array of choices");return this.containerOuter.removeLoadingState(),this._store.withTxn((function(){var s="value"===t,r="label"===n;e.forEach((function(e){if("choices"in e){var c=e;r||(c=i(i({},c),{label:c[n]})),o._addGroup(O(c,!0))}else{var a=e;r&&s||(a=i(i({},a),{value:a[t],label:a[n]})),o._addChoice(O(a,!1))}}))})),this._searcher.reset(),this},e.prototype.refresh=function(e,t,i){var n=this;return void 0===e&&(e=!1),void 0===t&&(t=!1),void 0===i&&(i=!1),this._isSelectElement?(this._store.withTxn((function(){var s=n.passedElement.optionsAsChoices(),o=n._store.items,r={};i||o.forEach((function(e){e.id&&e.active&&e.selected&&!e.disabled&&(r[e.value]=!0)})),s.forEach((function(e){if(!("choices"in e)){var t=e;i?t.selected=!1:r[t.value]&&(t.selected=!0)}})),n.clearStore(),n._addPredefinedChoices(s,t,e),n._isSearching&&n._searchChoices(n.input.value)})),this):(this.config.silent||console.warn("refresh method can only be used on choices backed by a element"),this)},e.prototype.removeChoice=function(e){var t=this._store.choices.find((function(t){return t.value===e}));return t?(this._store.dispatch(function(e){return{type:"REMOVE_CHOICE",choice:e}}(t)),this._searcher.reset(),t.selected&&this.passedElement.triggerEvent("removeItem",this._getChoiceForOutput(t)),this):this},e.prototype.clearChoices=function(){return this.passedElement.element.innerHTML="",this._store.dispatch({type:"CLEAR_CHOICES"}),this._searcher.reset(),this},e.prototype.clearStore=function(){return this._store.resetStore(),this._lastAddedChoiceId=0,this._lastAddedGroupId=0,this._searcher.reset(),this},e.prototype.clearInput=function(){var e=!this._isSelectOneElement;return this.input.clear(e),this._isSearching&&this._stopSearch(),this},e.prototype._validateConfig=function(){var e,t,i,n,s=(e=this.config,t=A,i=Object.keys(e).sort(),n=Object.keys(t).sort(),i.filter((function(e){return n.indexOf(e)<0})));s.length&&console.warn("Unknown config option(s) passed",s.join(", ")),this.config.allowHTML&&this.config.allowHtmlUserInput&&(this.config.addItems&&console.warn("Warning: allowHTML/allowHtmlUserInput/addItems all being true is strongly not recommended and may lead to XSS attacks"),this.config.addChoices&&console.warn("Warning: allowHTML/allowHtmlUserInput/addChoices all being true is strongly not recommended and may lead to XSS attacks"))},e.prototype._render=function(e){if(!this._store.inTxn()){var t=null==e?void 0:e.items;((null==e?void 0:e.choices)||(null==e?void 0:e.groups)||t)&&(this._isSelectElement&&this._renderChoices(),t&&this._renderItems())}},e.prototype._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){if(!this._hasNonChoicePlaceholder){var o=n.filter((function(e){return e.placeholder&&-1===e.groupId}));o.length>=1&&(s=this._createChoicesFragment(o,s))}s=this._createGroupsFragment(i,n,s)}else n.length>=1&&(s=this._createChoicesFragment(n,s));var r=this.input.value,a=this._canAddItem(this._store.items,r);if(s.childNodes&&s.childNodes.length>0){var c=!a.response;if(a.response&&(this.choiceList.append(s),this._highlightChoice(),this._canAddUserChoices&&r&&a.notice&&(c=!n.find((function(t){return e.config.valueComparer(t.value,r)})))),c){var h=this._templates.notice(this.config,a.notice,this._canAddUserChoices?"add-choice":"");this.choiceList.prepend(h)}}else{var l=void 0;if(a.response&&this._canAddUserChoices&&r)l=this._templates.notice(this.config,a.notice,"add-choice");else if(this._isSearching){h="function"==typeof this.config.noResultsText?this.config.noResultsText():this.config.noResultsText;l=this._templates.notice(this.config,h,"no-results")}else{h="function"==typeof this.config.noChoicesText?this.config.noChoicesText():this.config.noChoicesText;l=this._templates.notice(this.config,h,"no-choices")}this.choiceList.append(l)}},e.prototype._renderItems=function(){var e=this._store.items||[];this.itemList.clear();var t=this._createItemsFragment(e);t.childNodes&&this.itemList.append(t)},e.prototype._createGroupsFragment=function(e,t,i){var n=this;void 0===i&&(i=document.createDocumentFragment());this.config.shouldSort&&e.sort(this.config.sorter);var s=t.filter((function(e){return 0===e.groupId}));return s.length>0&&this._createChoicesFragment(s,i,!1),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 o=n._templates.choiceGroup(n.config,e);i.appendChild(o),n._createChoicesFragment(s,i,!0)}})),i},e.prototype._createChoicesFragment=function(e,t,i){var s=this;void 0===t&&(t=document.createDocumentFragment()),void 0===i&&(i=!1);var o=this.config,r=o.renderSelectedChoices,a=o.searchResultLimit,c=o.renderChoiceLimit,h=[],u=this.config.appendGroupInSearch&&this._isSearching;u&&this._store.groups.forEach((function(e){h[e.id]=e.label}));var d=function(e){if("auto"!==r||(s._isSelectOneElement||!e.selected)){var i=s._templates.choice(s.config,e,s.config.itemSelectText);if(u&&e.groupId>0){var n=h[e.groupId];n&&(i.innerHTML+=" (".concat(n,")"))}t.appendChild(i)}},p=e;if("auto"!==r||this._isSelectOneElement||(p=e.filter((function(e){return!e.selected}))),this._isSelectElement){var f=e.filter((function(e){return!e.element}));0!==f.length&&this.passedElement.addOptions(f)}var m=[],g=[];this._hasNonChoicePlaceholder?g=p:p.forEach((function(e){e.placeholder?m.push(e):g.push(e)})),this._isSearching?g.sort(l):this.config.shouldSort&&g.sort(this.config.sorter);var v=p.length,_=this._isSelectOneElement&&0!==m.length?n(n([],m,!0),g,!0):g;this._isSearching?v=a:c&&c>0&&!i&&(v=c);for(var y=0;y0?this._store.getGroupById(e.groupId):null;return{id:e.id,highlighted:e.highlighted,labelClass:e.labelClass,labelDescription:e.labelDescription,customProperties:e.customProperties,disabled:e.disabled,active:e.active,label:e.label,placeholder:e.placeholder,value:e.value,groupValue:i&&i.label?i.label:void 0,element:e.element,keyCode:t}}},e.prototype._triggerChange=function(e){null!=e&&this.passedElement.triggerEvent("change",{value:e})},e.prototype._handleButtonAction=function(e,t){if(0!==e.length&&this.config.removeItems&&this.config.removeItemButton){var i=t&&we(t.parentNode),n=i&&e.find((function(e){return e.id===i}));if(n&&(this._removeItem(n),this._triggerChange(n.value),this._isSelectOneElement&&!this._hasNonChoicePlaceholder)){var s=this._store.choices.reverse().find((function(e){return!e.disabled&&e.placeholder}));s&&(this._addItem(s),s.value&&this._triggerChange(s.value))}}},e.prototype._handleItemAction=function(e,t,i){var n=this;if(void 0===i&&(i=!1),0!==e.length&&this.config.removeItems&&!this._isSelectOneElement){var s=we(t);s&&(e.forEach((function(e){e.id!==s||e.highlighted?!i&&e.highlighted&&n.unhighlightItem(e):n.highlightItem(e)})),this.input.focus())}},e.prototype._handleChoiceAction=function(e,t,i){var n=this,s=we(t),o=s&&this._store.getChoiceById(s);if(!o)return!1;var r=this.dropdown.isActive,a=!1;return this._store.withTxn((function(){if(!o.selected&&!o.disabled&&n._canAddItem(e,o.value).response){if(n.config.singleModeForMultiSelect&&0!==e.length){var t=e[e.length-1];n._removeItem(t)}n.passedElement.triggerEvent("choice",n._getChoiceForOutput(o,i)),n._addItem(o),n.clearInput(),a=!0}})),!!a&&(this._triggerChange(o.value),r&&(this.config.singleModeForMultiSelect||this._isSelectOneElement)&&(this.hideDropdown(!0),this.containerOuter.focus()),!0)},e.prototype._handleBackspace=function(e){if(this.config.removeItems&&0!==e.length){var t=e[e.length-1],i=e.some((function(e){return e.highlighted}));this.config.editItems&&!i&&t?(this.input.value=t.value,this.input.setWidth(),this._removeItem(t),this._triggerChange(t.value)):(i||this.highlightItem(t,!1),this.removeHighlightedItems(!0))}},e.prototype._loadChoices=function(){var e;if(this._isTextElement){this._presetChoices=this.config.items.map((function(e){return S(e,!1)}));var t=this.passedElement.value;if(t){var i=t.split(this.config.delimiter).map((function(e){return S(e,!1)}));this._presetChoices=this._presetChoices.concat(i)}this._presetChoices.forEach((function(e){e.selected=!0}))}else if(this._isSelectElement){this._presetChoices=this.config.choices.map((function(e){return S(e,!0)}));var n=this.passedElement.optionsAsChoices();n&&(e=this._presetChoices).push.apply(e,n)}},e.prototype._handleLoadingState=function(e){void 0===e&&(e=!0);var t=this.itemList.element.querySelector(d(this.config.classNames.placeholder));e?(this.disable(),this.containerOuter.addLoadingState(),this._isSelectOneElement?t?t.innerHTML=this.config.loadingText:(t=this._templates.placeholder(this.config,this.config.loadingText))&&this.itemList.append(t):this.input.placeholder=this.config.loadingText):(this.enable(),this.containerOuter.removeLoadingState(),this._isSelectOneElement?t&&(t.innerHTML=this._placeholderValue||""):this.input.placeholder=this._placeholderValue||"")},e.prototype._handleSearch=function(e){if(this.input.isFocussed){var t=this._store.choices,i=this.config,n=i.searchFloor,s=i.searchChoices,o=t.some((function(e){return!e.active}));if(null!=e&&e.length>=n){var r=s?this._searchChoices(e):0;null!==r&&this.passedElement.triggerEvent("search",{value:e,resultCount:r})}else o&&this._stopSearch()}},e.prototype._canAddItem=function(e,t){var i=this,n=!0,s="";(this.config.maxItemCount>0&&this.config.maxItemCount<=e.length&&(this.config.singleModeForMultiSelect||(n=!1,s="function"==typeof this.config.maxItemText?this.config.maxItemText(this.config.maxItemCount):this.config.maxItemText)),n&&this._canAddUserChoices&&""!==t&&"function"==typeof this.config.addItemFilter&&!this.config.addItemFilter(t)&&(n=!1,s="function"==typeof this.config.customAddItemText?this.config.customAddItemText(a(t),t):this.config.customAddItemText),!n||""===t||!this._isSelectElement&&this.config.duplicateItemsAllowed)||this._store.items.find((function(e){return i.config.valueComparer(e.value,t)}))&&(n=!1,s="function"==typeof this.config.uniqueItemText?this.config.uniqueItemText(a(t),t):this.config.uniqueItemText);return n&&(s="function"==typeof this.config.addItemText?this.config.addItemText(a(t),t):this.config.addItemText),{response:n,notice:{trusted:s}}},e.prototype._searchChoices=function(e){var t=e.trim().replace(/\s{2,}/," ");if(0===t.length||t===this._currentValue)return null;var i=this._searcher;i.isEmptyIndex()&&i.index(this._store.searchableChoices);var n=i.search(t);return this._currentValue=t,this._highlightPosition=0,this._isSearching=!0,this._store.dispatch(function(e){return{type:"FILTER_CHOICES",results:e}}(n)),n.length},e.prototype._stopSearch=function(){var e=this._isSearching;this._currentValue="",this._isSearching=!1,e&&this._store.dispatch({type:"ACTIVATE_CHOICES",active:!0})},e.prototype._addEventListeners=function(){var e=this.config.shadowRoot||document.documentElement;e.addEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.addEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.addEventListener("mousedown",this._onMouseDown,!0),e.addEventListener("click",this._onClick,{passive:!0}),e.addEventListener("touchmove",this._onTouchMove,{passive:!0}),this.dropdown.element.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("input",this._onInput,{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()},e.prototype._removeEventListeners=function(){var e=this.config.shadowRoot||document.documentElement;e.removeEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.removeEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.removeEventListener("mousedown",this._onMouseDown,!0),e.removeEventListener("click",this._onClick),e.removeEventListener("touchmove",this._onTouchMove),this.dropdown.element.removeEventListener("mouseover",this._onMouseOver),this._isSelectOneElement&&(this.containerOuter.element.removeEventListener("focus",this._onFocus),this.containerOuter.element.removeEventListener("blur",this._onBlur)),this.input.element.removeEventListener("keyup",this._onKeyUp),this.input.element.removeEventListener("input",this._onInput),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()},e.prototype._onKeyDown=function(e){var t=e.keyCode,i=this._store.items,n=this.input.isFocussed,s=this.dropdown.isActive,o=this.itemList.hasChildren(),r=1===e.key.length||2===e.key.length&&e.key.charCodeAt(0)>=55296||"Unidentified"===e.key;switch(this._isTextElement||s||(this.showDropdown(),!this.input.isFocussed&&r&&(this.input.value+=e.key)),t){case 65:return this._onSelectKey(e,o);case 13:return this._onEnterKey(e,i,s);case 27:return this._onEscapeKey(e,s);case 38:case 33:case 40:case 34:return this._onDirectionKey(e,s);case 8:case 46:return this._onDeleteKey(e,i,n)}},e.prototype._onKeyUp=function(){this._canSearch=this.config.searchEnabled},e.prototype._onInput=function(){var e=this.input.value;if(e){if(this._isTextElement){var t=this._canAddItem(this._store.items,e);t.notice&&(this._displayAddItemNotice(t),this.showDropdown(!0))}if(this._canSearch){this._handleSearch(e);var i=this._canAddItem(this._store.items,e);i.response||this._displayAddItemNotice(i),this._canAddUserChoices&&(this._highlightPosition=0,this._highlightChoice())}}else this._isTextElement?this.hideDropdown(!0):this._stopSearch()},e.prototype._displayAddItemNotice=function(e){var t=this._templates.notice(this.config,e.notice,"add-choice"),i="".concat(d(this.config.classNames.addChoice),"[data-choice-selectable]"),n=this.choiceList.element.querySelector(i);n?n.outerHTML=t.outerHTML:this.choiceList.prepend(t)},e.prototype._onSelectKey=function(e,t){var i=e.ctrlKey,n=e.metaKey;(i||n)&&t&&(this._canSearch=!1,this.config.removeItems&&!this.input.value&&this.input.element===document.activeElement&&this.highlightAll())},e.prototype._onEnterKey=function(e,t,i){var n=this,s=this.input.value,o=e.target;if(o&&o.hasAttribute("data-button"))return e.preventDefault(),void this._handleButtonAction(t,o);if(!i&&this._isSelectOneElement)return e.preventDefault(),void this.showDropdown();if(i){var r=this.dropdown.element.querySelector(d(this.config.classNames.highlightedState));if(r&&this._handleChoiceAction(t,r,13))return e.preventDefault(),void this.unhighlightAll();s||this.hideDropdown(!0)}o&&s&&this._canAddUserChoices&&(this._canAddItem(t,s).response&&(this._store.withTxn((function(){if((n._isSelectOneElement||n.config.singleModeForMultiSelect)&&0!==t.length){var e=t[t.length-1];n._removeItem(e)}var i=!0;if(!n._isSelectElement&&n.config.duplicateItemsAllowed||(i=!n._findAndSelectChoiceByValue(s)),i){var o=a(s),r=n.config.allowHtmlUserInput||o===s?s:{escaped:o,raw:s};n._addChoice(S({value:r,label:r,selected:!0},!1))}n.clearInput(),n.unhighlightAll(),n._triggerChange(s)})),(this._isTextElement||this._isSelectOneElement)&&this.hideDropdown(!0)))},e.prototype._onEscapeKey=function(e,t){t&&(e.stopPropagation(),this.hideDropdown(!0),this.containerOuter.focus())},e.prototype._onDirectionKey=function(e,t){var i,n,s,o=e.keyCode,r=e.metaKey;if(t||this._isSelectOneElement){this.showDropdown(),this._canSearch=!1;var a=40===o||34===o?1:-1,c="[data-choice-selectable]",h=void 0;if(r||34===o||33===o)h=a>0?this.dropdown.element.querySelector("".concat(c,":last-of-type")):this.dropdown.element.querySelector(c);else{var l=this.dropdown.element.querySelector(d(this.config.classNames.highlightedState));h=l?function(e,t,i){void 0===i&&(i=1);for(var n="".concat(i>0?"next":"previous","ElementSibling"),s=e[n];s;){if(s.matches(t))return s;s=s[n]}return s}(l,c,a):this.dropdown.element.querySelector(c)}h&&(i=h,n=this.choiceList.element,void 0===(s=a)&&(s=1),i&&(s>0?n.scrollTop+n.offsetHeight>=i.offsetTop+i.offsetHeight:i.offsetTop>=n.scrollTop)||this.choiceList.scrollToChildElement(h,a),this._highlightChoice(h)),e.preventDefault()}},e.prototype._onDeleteKey=function(e,t,i){var n=e.target;this._isSelectOneElement||n.value||!i||(this._handleBackspace(t),e.preventDefault())},e.prototype._onTouchMove=function(){this._wasTap&&(this._wasTap=!1)},e.prototype._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},e.prototype._onMouseDown=function(e){var t=e.target;if(t instanceof HTMLElement){if(Ce&&this.choiceList.element.contains(t)){var i=this.choiceList.element.firstElementChild;this._isScrollingOnIe="ltr"===this._direction?e.offsetX>=i.offsetWidth:e.offsetX0&&this.unhighlightAll(),this.containerOuter.removeFocusState(),this.hideDropdown(!0))},e.prototype._onFocus=function(e){var t,i=this,n=e.target;n&&this.containerOuter.element.contains(n)&&((t={})[m]=function(){n===i.input.element&&i.containerOuter.addFocusState()},t[g]=function(){i.containerOuter.addFocusState(),n===i.input.element&&i.showDropdown(!0)},t[v]=function(){n===i.input.element&&(i.showDropdown(!0),i.containerOuter.addFocusState())},t)[this._elementType]()},e.prototype._onBlur=function(e){var t,i=this,n=e.target;if(n&&this.containerOuter.element.contains(n)&&!this._isScrollingOnIe){var s=this._store.activeChoices.some((function(e){return e.highlighted}));((t={})[m]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),s&&i.unhighlightAll(),i.hideDropdown(!0))},t[g]=function(){i.containerOuter.removeFocusState(),(n===i.input.element||n===i.containerOuter.element&&!i._canSearch)&&i.hideDropdown(!0)},t[v]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),i.hideDropdown(!0),s&&i.unhighlightAll())},t)[this._elementType]()}else this._isScrollingOnIe=!1,this.input.element.focus()},e.prototype._onFormReset=function(){var e=this;this._store.withTxn((function(){e.clearInput(),e.hideDropdown(),e.refresh(!1,!1,!0),0!==e._initialItems.length&&e.setChoiceByValue(e._initialItems)}))},e.prototype._highlightChoice=function(e){var t,i=this;void 0===e&&(e=null);var n=Array.from(this.dropdown.element.querySelectorAll("[data-choice-selectable]"));if(n.length){var s=e;Array.from(this.dropdown.element.querySelectorAll(d(this.config.classNames.highlightedState))).forEach((function(e){var t;(t=e.classList).remove.apply(t,u(i.config.classNames.highlightedState)),e.setAttribute("aria-selected","false")})),s?this._highlightPosition=n.indexOf(s):(s=n.length>this._highlightPosition?n[this._highlightPosition]:n[n.length-1])||(s=n[0]),(t=s.classList).add.apply(t,u(this.config.classNames.highlightedState)),s.setAttribute("aria-selected","true"),this.passedElement.triggerEvent("highlightChoice",{el:s}),this.dropdown.isActive&&(this.input.setActiveDescendant(s.id),this.containerOuter.setActiveDescendant(s.id))}},e.prototype._addItem=function(e,t){void 0===t&&(t=!0);var i=e.id;if(0===i)throw new TypeError("item.id must be set before _addItem is called for a choice/item");this._store.dispatch(function(e){return{type:"ADD_ITEM",item:e}}(e)),this._isSelectOneElement&&this.removeActiveItems(i),t&&this.passedElement.triggerEvent("addItem",this._getChoiceForOutput(e))},e.prototype._removeItem=function(e){e.id&&(this._store.dispatch(function(e){return{type:"REMOVE_ITEM",item:e}}(e)),this.passedElement.triggerEvent("removeItem",this._getChoiceForOutput(e)))},e.prototype._addChoice=function(e,t){if(void 0===t&&(t=!0),0!==e.id)throw new TypeError("Can not re-add a choice which has already been added");var i=e;this._lastAddedChoiceId++,i.id=this._lastAddedChoiceId,i.elementId="".concat(this._baseId,"-").concat(this._idNames.itemChoice,"-").concat(i.id),this.config.prependValue&&(i.value=this.config.prependValue+i.value),this.config.appendValue&&(i.value+=this.config.appendValue.toString()),(this.config.prependValue||this.config.appendValue)&&i.element&&(i.element.value=i.value),this._store.dispatch(function(e){return{type:"ADD_CHOICE",choice:e}}(e)),e.selected&&this._addItem(e,t)},e.prototype._addGroup=function(e,t){var i=this;if(void 0===t&&(t=!0),0!==e.id)throw new TypeError("Can not re-add a group which has already been added");if(this._store.dispatch(function(e){return{type:"ADD_GROUP",group:e}}(e)),e.choices){var n=e;this._lastAddedGroupId++,n.id=this._lastAddedGroupId;var s=e.id,o=e.choices;n.choices=[],o.forEach((function(n){var o=n;o.groupId=s,e.disabled&&(o.disabled=!0),i._addChoice(o,t)}))}},e.prototype._createTemplates=function(){var e=this,t=this.config.callbackOnCreateTemplates,i={};t&&"function"==typeof t&&(i=t.call(this,c,M));var n={};Object.keys(F).forEach((function(t){n[t]=t in i?i[t].bind(e):F[t].bind(e)})),this._templates=n},e.prototype._createElements=function(){this.containerOuter=new _({element:this._templates.containerOuter(this.config,this._direction,this._isSelectElement,this._isSelectOneElement,this.config.searchEnabled,this._elementType,this.config.labelId),classNames:this.config.classNames,type:this._elementType,position:this.config.position}),this.containerInner=new _({element:this._templates.containerInner(this.config),classNames:this.config.classNames,type:this._elementType,position:this.config.position}),this.input=new y({element:this._templates.input(this.config,this._placeholderValue),classNames:this.config.classNames,type:this._elementType,preventPaste:!this.config.paste}),this.choiceList=new b({element:this._templates.choiceList(this.config,this._isSelectOneElement)}),this.itemList=new b({element:this._templates.itemList(this.config,this._isSelectOneElement)}),this.dropdown=new f({element:this._templates.dropdown(this.config),classNames:this.config.classNames,type:this._elementType})},e.prototype._createStructure=function(){this.passedElement.conceal(),this.containerInner.wrap(this.passedElement.element),this.containerOuter.wrap(this.containerInner.element),this._isSelectOneElement?this.input.placeholder=this.config.searchPlaceholderValue||"":(this._placeholderValue&&(this.input.placeholder=this._placeholderValue),this.input.setWidth()),this.containerOuter.element.appendChild(this.containerInner.element),this.containerOuter.element.appendChild(this.dropdown.element),this.containerInner.element.appendChild(this.itemList.element),this.dropdown.element.appendChild(this.choiceList.element),this._isSelectOneElement?this.config.searchEnabled&&this.dropdown.element.insertBefore(this.input.element,this.dropdown.element.firstChild):this.containerInner.element.appendChild(this.input.element),this._highlightPosition=0,this._isSearching=!1},e.prototype._initStore=function(){var e=this;this._store.subscribe(this._render),this._store.withTxn((function(){e._addPredefinedChoices(e._presetChoices,e._isSelectOneElement&&!e._hasNonChoicePlaceholder,!1)}))},e.prototype._addPredefinedChoices=function(e,t,i){var n=this;if(void 0===t&&(t=!1),void 0===i&&(i=!0),this.config.shouldSort&&e.sort(this.config.sorter),t){var s=-1===e.findIndex((function(e){return!!e.selected}));if(s){var o=e.findIndex((function(e){return void 0===e.disabled||!e.disabled}));if(-1!==o)e[o].selected=!0}}e.forEach((function(e){"choices"in e?n._isSelectElement&&n._addGroup(e,i):n._addChoice(e,i)}))},e.prototype._findAndSelectChoiceByValue=function(e){var t=this,i=this._store.choices.find((function(i){return t.config.valueComparer(i.value,e)}));return!(!i||i.selected)&&(this._addItem(i),!0)},e.prototype._generatePlaceholderValue=function(){if(!this.config.placeholder)return null;if(this._hasNonChoicePlaceholder)return this.config.placeholderValue;if(this._isSelectElement){var e=this.passedElement.placeholderOption;return e?e.text:null}return null},e.prototype._warnChoicesInitFailed=function(e){if(!this.config.silent){if(!this.initialised)throw new TypeError("".concat(e," called on a non-initialised instance of Choices"));if(!this.initialisedOK)throw new TypeError("".concat(e," called for an element which has multiple instances of Choices initialised on it"))}},e.version="11.0.0-rc5",e}();return Se})); diff --git a/public/assets/scripts/choices.search-basic.min.mjs b/public/assets/scripts/choices.search-basic.min.mjs index 69ea49d5..56f6a906 100644 --- a/public/assets/scripts/choices.search-basic.min.mjs +++ b/public/assets/scripts/choices.search-basic.min.mjs @@ -1,2 +1,2 @@ /*! choices.js v11.0.0-rc5 | © 2024 Josh Johnson | https://github.com/jshjohnson/Choices#readme */ -var e=function(t,i){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},e(t,i)};function t(t,i){if("function"!=typeof i&&null!==i)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");function n(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(n.prototype=i.prototype,new n)}var i=function(){return i=Object.assign||function(e){for(var t,i=1,n=arguments.length;i/g,">").replace(/0?this.element.scrollTop+r-s:e.offsetTop;requestAnimationFrame((function(){i._animateScroll(c,t)}))}},e.prototype._scrollDown=function(e,t,i){var n=(i-e)/t,s=n>1?n:1;this.element.scrollTop=e+s},e.prototype._scrollUp=function(e,t,i){var n=(e-i)/t,s=n>1?n:1;this.element.scrollTop=e-s},e.prototype._animateScroll=function(e,t){var i=this,n=this.element.scrollTop,s=!1;t>0?(this._scrollDown(n,4,e),ne&&(s=!0)),s&&requestAnimationFrame((function(){i._animateScroll(e,t)}))},e}(),w=function(){function e(e){var t=e.element,i=e.classNames;this.element=t,this.classNames=i,this.isDisabled=!1}return Object.defineProperty(e.prototype,"isActive",{get:function(){return"active"===this.element.dataset.choice},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dir",{get:function(){return this.element.dir},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.element.value},set:function(e){this.element.setAttribute("value",e),this.element.value=e},enumerable:!1,configurable:!0}),e.prototype.conceal=function(){var e;(e=this.element.classList).add.apply(e,d(this.classNames.input)),this.element.hidden=!0,this.element.tabIndex=-1;var t=this.element.getAttribute("style");t&&this.element.setAttribute("data-choice-orig-style",t),this.element.setAttribute("data-choice","active")},e.prototype.reveal=function(){var e;(e=this.element.classList).remove.apply(e,d(this.classNames.input)),this.element.hidden=!1,this.element.removeAttribute("tabindex");var t=this.element.getAttribute("data-choice-orig-style");t?(this.element.removeAttribute("data-choice-orig-style"),this.element.setAttribute("style",t)):this.element.removeAttribute("style"),this.element.removeAttribute("data-choice"),this.element.value=this.element.value},e.prototype.enable=function(){this.element.removeAttribute("disabled"),this.element.disabled=!1,this.isDisabled=!1},e.prototype.disable=function(){this.element.setAttribute("disabled",""),this.element.disabled=!0,this.isDisabled=!0},e.prototype.triggerEvent=function(e,t){!function(e,t,i){void 0===i&&(i=null);var n=new CustomEvent(t,{detail:i,bubbles:!0,cancelable:!0});e.dispatchEvent(n)}(this.element,e,t||{})},e}(),C=function(e){function i(){return null!==e&&e.apply(this,arguments)||this}return t(i,e),i}(w),I=function(e,t){return void 0===t&&(t=!0),void 0===e?t:!!e},S=function(e){if("string"==typeof e&&(e=e.split(" ").filter((function(e){return 0!==e.length}))),Array.isArray(e)&&0!==e.length)return e},O=function(e,t){if("string"==typeof e)return O({value:e,label:e},!1);var i=e;if("choices"in i){if(!t)throw new TypeError("optGroup is not allowed");var n=i,s=n.choices.map((function(e){return O(e,!1)}));return{id:0,label:l(n.label)||n.value,active:0!==s.length,disabled:!!n.disabled,choices:s}}var o=i;return{id:0,groupId:0,score:0,rank:0,value:o.value,label:o.label||o.value,active:I(o.active),selected:I(o.selected,!1),disabled:I(o.disabled,!1),placeholder:I(o.placeholder,!1),highlighted:!1,labelClass:S(o.labelClass),labelDescription:o.labelDescription,customProperties:o.customProperties}},A=function(e){function i(t){var i=t.element,n=t.classNames,s=t.template,o=t.extractPlaceholder,r=e.call(this,{element:i,classNames:n})||this;return r.template=s,r.extractPlaceholder=o,r}return t(i,e),Object.defineProperty(i.prototype,"placeholderOption",{get:function(){return this.element.querySelector('option[value=""]')||this.element.querySelector("option[placeholder]")},enumerable:!1,configurable:!0}),i.prototype.addOptions=function(e){var t=this;e.forEach((function(e){var i=e;if(!i.element){var n=t.template(i);t.element.appendChild(n),i.element=n}}))},i.prototype.optionsAsChoices=function(){var e=this,t=[];return this.element.querySelectorAll(":scope > option, :scope > optgroup").forEach((function(i){!function(e){return"OPTION"===e.tagName}(i)?function(e){return"OPTGROUP"===e.tagName}(i)&&t.push(e._optgroupToChoice(i)):t.push(e._optionToChoice(i))})),t},i.prototype._optionToChoice=function(e){return{id:0,groupId:0,score:0,rank:0,value:e.value,label:e.innerHTML,element:e,active:!0,selected:this.extractPlaceholder?e.selected:e.hasAttribute("selected"),disabled:e.disabled,highlighted:!1,placeholder:this.extractPlaceholder&&(""===e.value||e.hasAttribute("placeholder")),labelClass:void 0!==e.dataset.labelClass?S(e.dataset.labelClass):void 0,labelDescription:void 0!==e.dataset.labelDescription?e.dataset.labelDescription:void 0,customProperties:f(e.dataset.customProperties)}},i.prototype._optgroupToChoice=function(e){var t=this,i=e.querySelectorAll("option"),n=Array.from(i).map((function(e){return t._optionToChoice(e)}));return{id:0,label:e.label||"",element:e,active:0!==n.length,disabled:e.disabled,choices:n}},i}(w),T={items:[],choices:[],silent:!1,renderChoiceLimit:-1,maxItemCount:-1,singleModeForMultiSelect:!1,addChoices:!1,addItems:!0,addItemFilter:function(e){return!!e&&""!==e},removeItems:!0,removeItemButton:!1,removeItemButtonAlignLeft:!1,editItems:!1,allowHTML:!1,allowHtmlUserInput:!1,duplicateItemsAllowed:!0,delimiter:",",paste:!0,searchEnabled:!0,searchChoices:!0,searchFloor:1,searchResultLimit:4,searchFields:["label","value"],position:"auto",resetScrollPosition:!0,shouldSort:!0,shouldSortItems:!1,sorter:function(e,t){var i=e.value,n=e.label,s=void 0===n?i:n,o=t.value,r=t.label,c=void 0===r?o:r;return l(s).localeCompare(l(c),[],{sensitivity:"base",ignorePunctuation:!0,numeric:!0})},shadowRoot:null,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 "'.concat(e,'"')},removeItemIconText:function(){return"Remove item"},removeItemLabelText:function(e){return"Remove item: ".concat(e)},maxItemText:function(e){return"Only ".concat(e," values can be added")},valueComparer:function(e,t){return e===t},fuseOptions:{includeScore:!0},labelId:"",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"],description:["choices__description"],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"],selectedState:["is-selected"],flippedState:["is-flipped"],loadingState:["is-loading"],addChoice:["choices__item","choices__item--selectable","add-choice"],noResults:["has-no-results"],noChoices:["has-no-choices"]},appendGroupInSearch:!1},L=["fuseOptions","classNames"];function x(e){return"Minified Redux error #"+e+"; visit https://redux.js.org/Errors?code="+e+" for the full message or use the non-minified dev environment for full errors. "}var N="function"==typeof Symbol&&Symbol.observable||"@@observable",M=function(){return Math.random().toString(36).substring(7).split("").join(".")},F={INIT:"@@redux/INIT"+M(),REPLACE:"@@redux/REPLACE"+M(),PROBE_UNKNOWN_ACTION:function(){return"@@redux/PROBE_UNKNOWN_ACTION"+M()}};function j(e,t,i){var n;if("function"==typeof t&&"function"==typeof i||"function"==typeof i&&"function"==typeof arguments[3])throw new Error(x(0));if("function"==typeof t&&void 0===i&&(i=t,t=void 0),void 0!==i){if("function"!=typeof i)throw new Error(x(1));return i(j)(e,t)}if("function"!=typeof e)throw new Error(x(2));var s=e,o=t,r=[],c=r,a=!1;function h(){c===r&&(c=r.slice())}function l(){if(a)throw new Error(x(3));return o}function u(e){if("function"!=typeof e)throw new Error(x(4));if(a)throw new Error(x(5));var t=!0;return h(),c.push(e),function(){if(t){if(a)throw new Error(x(6));t=!1,h();var i=c.indexOf(e);c.splice(i,1),r=null}}}function d(e){if(!function(e){if("object"!=typeof e||null===e)return!1;for(var t=e;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}(e))throw new Error(x(7));if(void 0===e.type)throw new Error(x(8));if(a)throw new Error(x(9));try{a=!0,o=s(o,e)}finally{a=!1}for(var t=r=c,i=0;i0},e.prototype.getChoiceById=function(e){return this.activeChoices.find((function(t){return t.id===e}))},e.prototype.getGroupById=function(e){return this.groups.find((function(t){return t.id===e}))},e}(),R=function(e,t){return e?function(e){if("string"==typeof e)return e;if("object"==typeof e){if("escaped"in e)return e.escaped;if("trusted"in e)return e.trusted}return""}(t):a(t)},K=function(e,t){if(t){var i=e.dataset;"string"==typeof t?i.customProperties=t:"object"!=typeof t||function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}(t)||(i.customProperties=JSON.stringify(t))}},V={containerOuter:function(e,t,i,n,s,o,r){var c=e.classNames.containerOuter,a=Object.assign(document.createElement("div"),{className:d(c).join(" ")});return a.dataset.type=o,t&&(a.dir=t),n&&(a.tabIndex=0),i&&(a.setAttribute("role",s?"combobox":"listbox"),s&&a.setAttribute("aria-autocomplete","list")),a.setAttribute("aria-haspopup","true"),a.setAttribute("aria-expanded","false"),r&&a.setAttribute("aria-labelledby",r),a},containerInner:function(e){var t=e.classNames.containerInner;return Object.assign(document.createElement("div"),{className:d(t).join(" ")})},itemList:function(e,t){var i=e.classNames,n=i.list,s=i.listSingle,o=i.listItems;return Object.assign(document.createElement("div"),{className:"".concat(d(n).join(" ")," ").concat(t?d(s).join(" "):d(o).join(" "))})},placeholder:function(e,t){var i=e.allowHTML,n=e.classNames.placeholder;return Object.assign(document.createElement("div"),{className:d(n).join(" "),innerHTML:R(i,t)})},item:function(e,t,i){var n,s,o,r=e.allowHTML,c=e.removeItemButtonAlignLeft,h=e.classNames,l=h.item,u=h.button,p=h.highlightedState,f=h.itemSelectable,m=h.placeholder,g=t.id,v=t.value,_=t.label,y=t.labelClass,b=t.labelDescription,E=t.customProperties,w=t.active,C=t.disabled,I=t.highlighted,S=t.placeholder,O=Object.assign(document.createElement("div"),{className:d(l).join(" ")});if(y){var A=Object.assign(document.createElement("span"),{innerHTML:R(r,_),className:d(y).join(" ")});O.appendChild(A)}else O.innerHTML=R(r,_);if(Object.assign(O.dataset,{item:"",id:g,value:v}),y&&(O.dataset.labelClass=d(y).join(" ")),b&&(O.dataset.labelDescription=b),K(O,E),w&&O.setAttribute("aria-selected","true"),C&&O.setAttribute("aria-disabled","true"),S&&((n=O.classList).add.apply(n,d(m)),O.dataset.placeholder=""),(s=O.classList).add.apply(s,d(I?p:f)),i){C&&(o=O.classList).remove.apply(o,d(f)),O.dataset.deletable="";var T="function"==typeof this.config.removeItemIconText?this.config.removeItemIconText(a(v),v):this.config.removeItemIconText,L="function"==typeof this.config.removeItemLabelText?this.config.removeItemLabelText(a(v),v):this.config.removeItemLabelText,x=Object.assign(document.createElement("button"),{type:"button",className:d(u).join(" "),innerHTML:T});L&&x.setAttribute("aria-label",L),x.dataset.button="",c?O.insertAdjacentElement("afterbegin",x):O.appendChild(x)}return O},choiceList:function(e,t){var i=e.classNames.list,n=Object.assign(document.createElement("div"),{className:d(i).join(" ")});return t||n.setAttribute("aria-multiselectable","true"),n.setAttribute("role","listbox"),n},choiceGroup:function(e,t){var i=e.allowHTML,n=e.classNames,s=n.group,o=n.groupHeading,r=n.itemDisabled,c=t.id,a=t.label,h=t.disabled,l=Object.assign(document.createElement("div"),{className:"".concat(d(s).join(" ")," ").concat(h?d(r).join(" "):"")});return l.setAttribute("role","group"),Object.assign(l.dataset,{group:"",id:c,value:a}),h&&l.setAttribute("aria-disabled","true"),l.appendChild(Object.assign(document.createElement("div"),{className:d(o).join(" "),innerHTML:R(i,a)})),l},choice:function(e,t,i){var n,s,o,r,c,a=e.allowHTML,h=e.classNames,l=h.item,u=h.itemChoice,p=h.itemSelectable,f=h.selectedState,m=h.itemDisabled,g=h.description,v=h.placeholder,_=t.id,y=t.value,b=t.label,E=t.groupId,w=t.elementId,C=t.labelClass,I=t.labelDescription,S=t.disabled,O=t.selected,A=t.placeholder,T=Object.assign(document.createElement("div"),{id:w,className:"".concat(d(l).join(" ")," ").concat(d(u).join(" "))}),L=T;if(C){var x=Object.assign(document.createElement("span"),{innerHTML:R(a,b),className:d(C).join(" ")});L=x,T.appendChild(x)}else T.innerHTML=R(a,b);if(I){var N="".concat(w,"-description");L.setAttribute("aria-describedby",N);var M=Object.assign(document.createElement("span"),{innerHTML:R(a,I),id:N});(n=M.classList).add.apply(n,d(g)),T.appendChild(M)}return O&&(s=T.classList).add.apply(s,d(f)),A&&(o=T.classList).add.apply(o,d(v)),T.setAttribute("role",E&&E>0?"treeitem":"option"),Object.assign(T.dataset,{choice:"",id:_,value:y,selectText:i}),C&&(T.dataset.labelClass=d(C).join(" ")),I&&(T.dataset.labelDescription=I),S?((r=T.classList).add.apply(r,d(m)),T.dataset.choiceDisabled="",T.setAttribute("aria-disabled","true")):((c=T.classList).add.apply(c,d(p)),T.dataset.choiceSelectable=""),T},input:function(e,t){var i=e.classNames,n=i.input,s=i.inputCloned,o=Object.assign(document.createElement("input"),{type:"search",className:"".concat(d(n).join(" ")," ").concat(d(s).join(" ")),autocomplete:"off",autocapitalize:"off",spellcheck:!1});return o.setAttribute("role","textbox"),o.setAttribute("aria-autocomplete","list"),t&&o.setAttribute("aria-label",t),o},dropdown:function(e){var t,i,n=e.classNames,s=n.list,o=n.listDropdown,r=document.createElement("div");return(t=r.classList).add.apply(t,d(s)),(i=r.classList).add.apply(i,d(o)),r.setAttribute("aria-expanded","false"),r},notice:function(e,t,i){var s=e.allowHTML,o=e.classNames,r=o.item,c=o.itemChoice,a=o.addChoice,h=o.noResults,l=o.noChoices;void 0===i&&(i="");var u=n(n([],d(r),!0),d(c),!0);switch(i){case"add-choice":u.push.apply(u,d(a));break;case"no-results":u.push.apply(u,d(h));break;case"no-choices":u.push.apply(u,d(l))}var p=Object.assign(document.createElement("div"),{innerHTML:R(s,t),className:u.join(" ")});return"add-choice"===i&&(p.dataset.choiceSelectable="",p.dataset.choice=""),p},option:function(e){var t=e.label,i=e.value,n=e.labelClass,s=e.labelDescription,o=e.customProperties,r=e.active,c=e.disabled,a=l(t),h=new Option(a,i,!1,r);return n&&(h.dataset.labelClass=d(n).join(" ")),s&&(h.dataset.labelDescription=s),K(h,o),h.disabled=c,h}};function B(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function U(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function q(e){for(var t=1;t`Missing ${e} property in key`,ie=e=>`Property 'weight' in key '${e}' must be a positive integer`,ne=Object.prototype.hasOwnProperty;class se{constructor(e){this._keys=[],this._keyMap={};let t=0;e.forEach((e=>{let i=oe(e);this._keys.push(i),this._keyMap[i.id]=i,t+=i.weight})),this._keys.forEach((e=>{e.weight/=t}))}get(e){return this._keyMap[e]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function oe(e){let t=null,i=null,n=null,s=1,o=null;if(X(e)||G(e))n=e,t=re(e),i=ce(e);else{if(!ne.call(e,"name"))throw new Error(te("name"));const r=e.name;if(n=r,ne.call(e,"weight")&&(s=e.weight,s<=0))throw new Error(ie(r));t=re(r),i=ce(r),o=e.getFn}return{path:t,id:i,weight:s,src:n,getFn:o}}function re(e){return G(e)?e:e.split(".")}function ce(e){return G(e)?e.join("."):e}const ae={useExtendedSearch:!1,getFn:function(e,t){let i=[],n=!1;const s=(e,t,o)=>{if(Y(e))if(t[o]){const r=e[t[o]];if(!Y(r))return;if(o===t.length-1&&(X(r)||J(r)||z(r)))i.push($(r));else if(G(r)){n=!0;for(let e=0,i=r.length;ee.score===t.score?e.idx{this._keysMap[e.id]=t}))}create(){!this.isCreated&&this.docs.length&&(this.isCreated=!0,X(this.docs[0])?this.docs.forEach(((e,t)=>{this._addString(e,t)})):this.docs.forEach(((e,t)=>{this._addObject(e,t)})),this.norm.clear())}add(e){const t=this.size();X(e)?this._addString(e,t):this._addObject(e,t)}removeAt(e){this.records.splice(e,1);for(let t=e,i=this.size();t{let s=t.getFn?t.getFn(e):this.getFn(e,t.path);if(Y(s))if(G(s)){let e=[];const t=[{nestedArrIndex:-1,value:s}];for(;t.length;){const{nestedArrIndex:i,value:n}=t.pop();if(Y(n))if(X(n)&&!Z(n)){let t={v:n,i:i,n:this.norm.get(n)};e.push(t)}else G(n)&&n.forEach(((e,i)=>{t.push({nestedArrIndex:i,value:e})}))}i.$[n]=e}else if(X(s)&&!Z(s)){let e={v:s,n:this.norm.get(s)};i.$[n]=e}})),this.records.push(i)}toJSON(){return{keys:this.keys,records:this.records}}}function de(e,t,{getFn:i=he.getFn,fieldNormWeight:n=he.fieldNormWeight}={}){const s=new ue({getFn:i,fieldNormWeight:n});return s.setKeys(e.map(oe)),s.setSources(t),s.create(),s}function pe(e,{errors:t=0,currentLocation:i=0,expectedLocation:n=0,distance:s=he.distance,ignoreLocation:o=he.ignoreLocation}={}){const r=t/e.length;if(o)return r;const c=Math.abs(n-i);return s?r+c/s:c?1:r}const fe=32;function me(e,t,i,{location:n=he.location,distance:s=he.distance,threshold:o=he.threshold,findAllMatches:r=he.findAllMatches,minMatchCharLength:c=he.minMatchCharLength,includeMatches:a=he.includeMatches,ignoreLocation:h=he.ignoreLocation}={}){if(t.length>fe)throw new Error(`Pattern length exceeds max of ${fe}.`);const l=t.length,u=e.length,d=Math.max(0,Math.min(n,u));let p=o,f=d;const m=c>1||a,g=m?Array(u):[];let v;for(;(v=e.indexOf(t,f))>-1;){let e=pe(t,{currentLocation:v,expectedLocation:d,distance:s,ignoreLocation:h});if(p=Math.min(e,p),f=v+l,m){let e=0;for(;e=a;o-=1){let r=o-1,c=i[e.charAt(r)];if(m&&(g[r]=+!!c),w[o]=(w[o+1]<<1|1)&c,n&&(w[o]|=(_[o+1]|_[o])<<1|1|_[o+1]),w[o]&E&&(y=pe(t,{errors:n,currentLocation:r,expectedLocation:d,distance:s,ignoreLocation:h}),y<=p)){if(p=y,f=r,f<=d)break;a=Math.max(1,2*d-f)}}if(pe(t,{errors:n+1,currentLocation:d,expectedLocation:d,distance:s,ignoreLocation:h})>p)break;_=w}const w={isMatch:f>=0,score:Math.max(.001,y)};if(m){const e=function(e=[],t=he.minMatchCharLength){let i=[],n=-1,s=-1,o=0;for(let r=e.length;o=t&&i.push([n,s]),n=-1)}return e[o-1]&&o-n>=t&&i.push([n,o-1]),i}(g,c);e.length?a&&(w.indices=e):w.isMatch=!1}return w}function ge(e){let t={};for(let i=0,n=e.length;i{this.chunks.push({pattern:e,alphabet:ge(e),startIndex:t})},l=this.pattern.length;if(l>fe){let e=0;const t=l%fe,i=l-t;for(;e{const{isMatch:f,score:m,indices:g}=me(e,t,d,{location:n+p,distance:s,threshold:o,findAllMatches:r,minMatchCharLength:c,includeMatches:i,ignoreLocation:a});f&&(u=!0),l+=m,f&&g&&(h=[...h,...g])}));let d={isMatch:u,score:u?l/this.chunks.length:1};return u&&i&&(d.indices=h),d}}const _e=[];function ye(e,t){for(let i=0,n=_e.length;i!(!e[be]&&!e[Ee]),Se=e=>({[be]:Object.keys(e).map((t=>({[t]:e[t]})))});function Oe(e,t){const i=e.matches;t.matches=[],Y(i)&&i.forEach((e=>{if(!Y(e.indices)||!e.indices.length)return;const{indices:i,value:n}=e;let s={indices:i,value:n};e.key&&(s.key=e.key.src),e.idx>-1&&(s.refIndex=e.idx),t.matches.push(s)}))}function Ae(e,t){t.score=e.score}class Te{constructor(e,t={},i){if(this.options=q(q({},he),t),this.options.useExtendedSearch)throw new Error("Extended search is not available");this._keyStore=new se(this.options.keys),this.setCollection(e,i)}setCollection(e,t){if(this._docs=e,t&&!(t instanceof ue))throw new Error("Incorrect 'index' type");this._myIndex=t||de(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(e){Y(e)&&(this._docs.push(e),this._myIndex.add(e))}remove(e=()=>!1){const t=[];for(let i=0,n=this._docs.length;i{let i=1;e.matches.forEach((({key:e,norm:n,score:s})=>{const o=e?e.weight:null;i*=Math.pow(0===s&&o?Number.EPSILON:s,(o||1)*(t?1:n))})),e.score=i}))}(c,{ignoreFieldNorm:r}),s&&c.sort(o),J(t)&&t>-1&&(c=c.slice(0,t)),function(e,t,{includeMatches:i=he.includeMatches,includeScore:n=he.includeScore}={}){const s=[];return i&&s.push(Oe),n&&s.push(Ae),e.map((e=>{const{idx:i}=e,n={item:t[i],refIndex:i};return s.length&&s.forEach((t=>{t(e,n)})),n}))}(c,this._docs,{includeMatches:i,includeScore:n})}_searchStringList(e){const t=ye(e,this.options),{records:i}=this._myIndex,n=[];return i.forEach((({v:e,i:i,n:s})=>{if(!Y(e))return;const{isMatch:o,score:r,indices:c}=t.searchIn(e);o&&n.push({item:e,idx:i,matches:[{score:r,value:e,norm:s,indices:c}]})})),n}_searchLogical(e){throw new Error("Logical search is not available")}_searchObjectList(e){const t=ye(e,this.options),{keys:i,records:n}=this._myIndex,s=[];return n.forEach((({$:e,i:n})=>{if(!Y(e))return;let o=[];i.forEach(((i,n)=>{o.push(...this._findMatches({key:i,value:e[n],searcher:t}))})),o.length&&s.push({idx:n,item:e,matches:o})})),s}_findMatches({key:e,value:t,searcher:i}){if(!Y(t))return[];let n=[];if(G(t))t.forEach((({v:t,i:s,n:o})=>{if(!Y(t))return;const{isMatch:r,score:c,indices:a}=i.searchIn(t);r&&n.push({score:c,key:e,value:t,idx:s,norm:o,indices:a})}));else{const{v:s,n:o}=t,{isMatch:r,score:c,indices:a}=i.searchIn(s);r&&n.push({score:c,key:e,value:s,norm:o,indices:a})}return n}}Te.version="7.0.0",Te.createIndex=de,Te.parseIndex=function(e,{getFn:t=he.getFn,fieldNormWeight:i=he.fieldNormWeight}={}){const{keys:n,records:s}=e,o=new ue({getFn:t,fieldNormWeight:i});return o.setKeys(n),o.setIndexRecords(s),o},Te.config=he,Te.parseQuery=function(e,t,{auto:i=!0}={}){const n=e=>{let s=Object.keys(e);const o=(e=>!!e[we])(e);if(!o&&s.length>1&&!Ie(e))return n(Se(e));if((e=>!G(e)&&Q(e)&&!Ie(e))(e)){const n=o?e[we]:s[0],r=o?e[Ce]:e[n];if(!X(r))throw new Error((e=>`Invalid value for key ${e}`)(n));const c={keyId:ce(n),pattern:r};return i&&(c.searcher=ye(r,t)),c}let r={children:[],operator:s[0]};return s.forEach((t=>{const i=e[t];G(i)&&i.forEach((e=>{r.children.push(n(e))}))})),r};return Ie(e)||(e=Se(e)),n(e)};var Le=function(){function e(e){this._haystack=[],this._fuseOptions=i(i({},e.fuseOptions),{keys:n([],e.searchFields,!0),includeMatches:!0})}return e.prototype.index=function(e){this._haystack=e,this._fuse&&this._fuse.setCollection(e)},e.prototype.reset=function(){this._haystack=[],this._fuse=void 0},e.prototype.isEmptyIndex=function(){return 0===this._haystack.length},e.prototype.search=function(e){return this._fuse||(this._fuse=new Te(this._haystack,this._fuseOptions)),this._fuse.search(e).map((function(e,t){return{item:e.item,score:e.score||0,rank:t}}))},e}();var xe="-ms-scroll-limit"in document.documentElement.style&&"-ms-ime-align"in document.documentElement.style,Ne={},Me=function(e){if(e){var t=e.dataset.id;return t?parseInt(t,10):void 0}},Fe=function(){function e(t,n){void 0===t&&(t="[data-choice]"),void 0===n&&(n={});var s=this;this.initialisedOK=void 0,this._hasNonChoicePlaceholder=!1,this._lastAddedChoiceId=0,this._lastAddedGroupId=0,this.config=i(i(i({},e.defaults.allOptions),e.defaults.options),n),L.forEach((function(t){s.config[t]=i(i(i({},e.defaults.allOptions[t]),e.defaults.options[t]),n[t])})),this.config.silent||this._validateConfig();var o=this.config.shadowRoot||document.documentElement,r="string"==typeof t?o.querySelector(t):t;if(!r||"object"!=typeof r||"INPUT"!==r.tagName&&!function(e){return"SELECT"===e.tagName}(r)){if(!r&&"string"==typeof t)throw TypeError("Selector ".concat(t," failed to find an element"));throw TypeError("Expected one of the following types text|select-one|select-multiple")}if(this._elementType=r.type,this._isTextElement=this._elementType===g,(this._isTextElement||1!==this.config.maxItemCount)&&(this.config.singleModeForMultiSelect=!1),this.config.singleModeForMultiSelect&&(this._elementType=_),this._isSelectOneElement=this._elementType===v,this._isSelectMultipleElement=this._elementType===_,this._isSelectElement=this._isSelectOneElement||this._isSelectMultipleElement,this._canAddUserChoices=this._isTextElement&&this.config.addItems||this._isSelectElement&&this.config.addChoices,["auto","always"].includes("".concat(this.config.renderSelectedChoices))||(this.config.renderSelectedChoices="auto"),this.config.placeholder&&(this.config.placeholderValue?this._hasNonChoicePlaceholder=!0:r.dataset.placeholder&&(this._hasNonChoicePlaceholder=!0,this.config.placeholderValue=r.dataset.placeholder)),n.addItemFilter&&"function"!=typeof n.addItemFilter){var a=n.addItemFilter instanceof RegExp?n.addItemFilter:new RegExp(n.addItemFilter);this.config.addItemFilter=a.test.bind(a)}if(this._isTextElement)this.passedElement=new C({element:r,classNames:this.config.classNames});else{var h=r;this.passedElement=new A({element:h,classNames:this.config.classNames,template:function(e){return s._templates.option(e)},extractPlaceholder:this.config.placeholder&&!this._hasNonChoicePlaceholder})}if(this.initialised=!1,this._store=new H,this._initialState=D,this._currentState=D,this._prevState=D,this._currentValue="",this.config.searchEnabled=!this._isTextElement&&this.config.searchEnabled||this._elementType===_,this._canSearch=this.config.searchEnabled,this._isScrollingOnIe=!1,this._highlightPosition=0,this._wasTap=!0,this._placeholderValue=this._generatePlaceholderValue(),this._baseId=function(e,t){var i=e.id||e.name&&"".concat(e.name,"-").concat(c(2))||c(4);return i=i.replace(/(:|\.|\[|\]|,)/g,""),"".concat(t,"-").concat(i)}(this.passedElement.element,"choices-"),this._direction=this.passedElement.dir,!this._direction){var l=window.getComputedStyle(this.passedElement.element).direction;l!==window.getComputedStyle(document.documentElement).direction&&(this._direction=l)}if(this._idNames={itemChoice:"item-choice"},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._onInput=this._onInput.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._onSelectKey=this._onSelectKey.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.passedElement.isActive)return this.config.silent||console.warn("Trying to initialise Choices on element already initialised",{element:t}),this.initialised=!0,void(this.initialisedOK=!1);this.init(),this._initialItems=this._store.items.map((function(e){return e.value}))}return Object.defineProperty(e,"defaults",{get:function(){return Object.preventExtensions({get options(){return Ne},get allOptions(){return T},get templates(){return V}})},enumerable:!1,configurable:!0}),e.prototype.init=function(){if(!this.initialised&&void 0===this.initialisedOK){var e;this._searcher=(e=this.config,new Le(e)),this._loadChoices(),this._createTemplates(),this._createElements(),this._createStructure(),this._store.subscribe(this._render),this._render(),this._addEventListeners(),(this._isTextElement&&!this.config.addItems||this.passedElement.element.hasAttribute("disabled")||!!this.passedElement.element.closest("fieldset:disabled"))&&this.disable(),this.initialised=!0,this.initialisedOK=!0;var t=this.config.callbackOnInit;t&&"function"==typeof t&&t.call(this)}},e.prototype.destroy=function(){this.initialised&&(this._removeEventListeners(),this.passedElement.reveal(),this.containerOuter.unwrap(this.passedElement.element),this.clearStore(),this._stopSearch(),this._templates=V,this.initialised=!1,this.initialisedOK=void 0)},e.prototype.enable=function(){return this.passedElement.isDisabled&&this.passedElement.enable(),this.containerOuter.isDisabled&&(this._addEventListeners(),this.input.enable(),this.containerOuter.enable()),this},e.prototype.disable=function(){return this.passedElement.isDisabled||this.passedElement.disable(),this.containerOuter.isDisabled||(this._removeEventListeners(),this.input.disable(),this.containerOuter.disable()),this},e.prototype.highlightItem=function(e,t){if(void 0===t&&(t=!0),!e||!e.id)return this;var i=this._store.choices.find((function(t){return t.id===e.id}));return!i||i.highlighted||(this._store.dispatch(o(i,!0)),t&&this.passedElement.triggerEvent("highlightItem",this._getChoiceForOutput(i))),this},e.prototype.unhighlightItem=function(e,t){if(void 0===t&&(t=!0),!e||!e.id)return this;var i=this._store.choices.find((function(t){return t.id===e.id}));return i&&i.highlighted?(this._store.dispatch(o(i,!1)),t&&this.passedElement.triggerEvent("highlightItem",this._getChoiceForOutput(i)),this):this},e.prototype.highlightAll=function(){var e=this;return this._store.withTxn((function(){e._store.items.forEach((function(t){return e.highlightItem(t)}))})),this},e.prototype.unhighlightAll=function(){var e=this;return this._store.withTxn((function(){e._store.items.forEach((function(t){return e.unhighlightItem(t)}))})),this},e.prototype.removeActiveItemsByValue=function(e){var t=this;return this._store.withTxn((function(){t._store.items.filter((function(t){return t.value===e})).forEach((function(e){return t._removeItem(e)}))})),this},e.prototype.removeActiveItems=function(e){var t=this;return this._store.withTxn((function(){t._store.items.filter((function(t){return t.id!==e})).forEach((function(e){return t._removeItem(e)}))})),this},e.prototype.removeHighlightedItems=function(e){var t=this;return void 0===e&&(e=!1),this._store.withTxn((function(){t._store.highlightedActiveItems.forEach((function(i){t._removeItem(i),e&&t._triggerChange(i.value)}))})),this},e.prototype.showDropdown=function(e){var t=this;return this.dropdown.isActive||requestAnimationFrame((function(){t.dropdown.show(),t.containerOuter.open(t.dropdown.distanceFromTopWindow),!e&&t._canSearch&&t.input.focus(),t.passedElement.triggerEvent("showDropdown")})),this},e.prototype.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("hideDropdown")})),this):this},e.prototype.getValue=function(e){var t=this;void 0===e&&(e=!1);var i=this._store.items.reduce((function(i,n){var s=e?n.value:t._getChoiceForOutput(n);return i.push(s),i}),[]);return this._isSelectOneElement||this.config.singleModeForMultiSelect?i[0]:i},e.prototype.setValue=function(e){var t=this;return this.initialisedOK?(this._store.withTxn((function(){e.forEach((function(e){e&&t._addChoice(O(e,!1))}))})),this._searcher.reset(),this):(this._warnChoicesInitFailed("setValue"),this)},e.prototype.setChoiceByValue=function(e){var t=this;return this.initialisedOK?(this._isTextElement||(this._store.withTxn((function(){(Array.isArray(e)?e:[e]).forEach((function(e){return t._findAndSelectChoiceByValue(e)}))})),this._searcher.reset()),this):(this._warnChoicesInitFailed("setChoiceByValue"),this)},e.prototype.setChoices=function(e,t,n,s){var o=this;if(void 0===e&&(e=[]),void 0===t&&(t="value"),void 0===n&&(n="label"),void 0===s&&(s=!1),!this.initialisedOK)return this._warnChoicesInitFailed("setChoices"),this;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(s&&this.clearChoices(),"function"==typeof e){var r=e(this);if("function"==typeof Promise&&r instanceof Promise)return new Promise((function(e){return requestAnimationFrame(e)})).then((function(){return o._handleLoadingState(!0)})).then((function(){return r})).then((function(e){return o.setChoices(e,t,n,s)})).catch((function(e){o.config.silent||console.error(e)})).then((function(){return o._handleLoadingState(!1)})).then((function(){return o}));if(!Array.isArray(r))throw new TypeError(".setChoices first argument function must return either array of choices or Promise, got: ".concat(typeof r));return this.setChoices(r,t,n,!1)}if(!Array.isArray(e))throw new TypeError(".setChoices must be called either with array of choices with a function resulting into Promise of array of choices");return this.containerOuter.removeLoadingState(),this._store.withTxn((function(){var s="value"===t,r="label"===n;e.forEach((function(e){if("choices"in e){var c=e;r||(c=i(i({},c),{label:c[n]})),o._addGroup(O(c,!0))}else{var a=e;r&&s||(a=i(i({},a),{value:a[t],label:a[n]})),o._addChoice(O(a,!1))}}))})),this._searcher.reset(),this},e.prototype.refresh=function(e,t,i){var n=this;return void 0===e&&(e=!1),void 0===t&&(t=!1),void 0===i&&(i=!1),this._isSelectElement?(this._store.withTxn((function(){var s=n.passedElement.optionsAsChoices(),o=n._store.items,r={};i||o.forEach((function(e){e.id&&e.active&&e.selected&&!e.disabled&&(r[e.value]=!0)})),s.forEach((function(e){if(!("choices"in e)){var t=e;i?t.selected=!1:r[t.value]&&(t.selected=!0)}})),n.clearStore(),n._addPredefinedChoices(s,t,e),n._isSearching&&n._searchChoices(n.input.value)})),this):(this.config.silent||console.warn("refresh method can only be used on choices backed by a element"),this)},e.prototype.removeChoice=function(e){var t=this._store.choices.find((function(t){return t.value===e}));return t?(this._store.dispatch(function(e){return{type:"REMOVE_CHOICE",choice:e}}(t)),this._searcher.reset(),t.selected&&this.passedElement.triggerEvent("removeItem",this._getChoiceForOutput(t)),this):this},e.prototype.clearChoices=function(){return this.passedElement.element.innerHTML="",this._store.dispatch({type:"CLEAR_CHOICES"}),this._searcher.reset(),this},e.prototype.clearStore=function(){return this._store.resetStore(),this._lastAddedChoiceId=0,this._lastAddedGroupId=0,this._searcher.reset(),this},e.prototype.clearInput=function(){var e=!this._isSelectOneElement;return this.input.clear(e),this._isSearching&&this._stopSearch(),this},e.prototype._validateConfig=function(){var e,t,i,n,s=(e=this.config,t=A,i=Object.keys(e).sort(),n=Object.keys(t).sort(),i.filter((function(e){return n.indexOf(e)<0})));s.length&&console.warn("Unknown config option(s) passed",s.join(", ")),this.config.allowHTML&&this.config.allowHtmlUserInput&&(this.config.addItems&&console.warn("Warning: allowHTML/allowHtmlUserInput/addItems all being true is strongly not recommended and may lead to XSS attacks"),this.config.addChoices&&console.warn("Warning: allowHTML/allowHtmlUserInput/addChoices all being true is strongly not recommended and may lead to XSS attacks"))},e.prototype._render=function(e){if(!this._store.inTxn()){var t=null==e?void 0:e.items;((null==e?void 0:e.choices)||(null==e?void 0:e.groups)||t)&&(this._isSelectElement&&this._renderChoices(),t&&this._renderItems())}},e.prototype._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){if(!this._hasNonChoicePlaceholder){var o=n.filter((function(e){return e.placeholder&&-1===e.groupId}));o.length>=1&&(s=this._createChoicesFragment(o,s))}s=this._createGroupsFragment(i,n,s)}else n.length>=1&&(s=this._createChoicesFragment(n,s));var r=this.input.value,a=this._canAddItem(this._store.items,r);if(s.childNodes&&s.childNodes.length>0){var c=!a.response;if(a.response&&(this.choiceList.append(s),this._highlightChoice(),this._canAddUserChoices&&r&&a.notice&&(c=!n.find((function(t){return e.config.valueComparer(t.value,r)})))),c){var h=this._templates.notice(this.config,a.notice,this._canAddUserChoices?"add-choice":"");this.choiceList.prepend(h)}}else{var l=void 0;if(a.response&&this._canAddUserChoices&&r)l=this._templates.notice(this.config,a.notice,"add-choice");else if(this._isSearching){h="function"==typeof this.config.noResultsText?this.config.noResultsText():this.config.noResultsText;l=this._templates.notice(this.config,h,"no-results")}else{h="function"==typeof this.config.noChoicesText?this.config.noChoicesText():this.config.noChoicesText;l=this._templates.notice(this.config,h,"no-choices")}this.choiceList.append(l)}},e.prototype._renderItems=function(){var e=this._store.items||[];this.itemList.clear();var t=this._createItemsFragment(e);t.childNodes&&this.itemList.append(t)},e.prototype._createGroupsFragment=function(e,t,i){var n=this;void 0===i&&(i=document.createDocumentFragment());this.config.shouldSort&&e.sort(this.config.sorter);var s=t.filter((function(e){return 0===e.groupId}));return s.length>0&&this._createChoicesFragment(s,i,!1),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 o=n._templates.choiceGroup(n.config,e);i.appendChild(o),n._createChoicesFragment(s,i,!0)}})),i},e.prototype._createChoicesFragment=function(e,t,i){var s=this;void 0===t&&(t=document.createDocumentFragment()),void 0===i&&(i=!1);var o=this.config,r=o.renderSelectedChoices,a=o.searchResultLimit,c=o.renderChoiceLimit,h=[],u=this.config.appendGroupInSearch&&this._isSearching;u&&this._store.groups.forEach((function(e){h[e.id]=e.label}));var d=function(e){if("auto"!==r||(s._isSelectOneElement||!e.selected)){var i=s._templates.choice(s.config,e,s.config.itemSelectText);if(u&&e.groupId>0){var n=h[e.groupId];n&&(i.innerHTML+=" (".concat(n,")"))}t.appendChild(i)}},p=e;if("auto"!==r||this._isSelectOneElement||(p=e.filter((function(e){return!e.selected}))),this._isSelectElement){var f=e.filter((function(e){return!e.element}));0!==f.length&&this.passedElement.addOptions(f)}var m=[],g=[];this._hasNonChoicePlaceholder?g=p:p.forEach((function(e){e.placeholder?m.push(e):g.push(e)})),this._isSearching?g.sort(l):this.config.shouldSort&&g.sort(this.config.sorter);var v=p.length,_=this._isSelectOneElement&&0!==m.length?n(n([],m,!0),g,!0):g;this._isSearching?v=a:c&&c>0&&!i&&(v=c);for(var y=0;y0?this._store.getGroupById(e.groupId):null;return{id:e.id,highlighted:e.highlighted,labelClass:e.labelClass,labelDescription:e.labelDescription,customProperties:e.customProperties,disabled:e.disabled,active:e.active,label:e.label,placeholder:e.placeholder,value:e.value,groupValue:i&&i.label?i.label:void 0,element:e.element,keyCode:t}}},e.prototype._triggerChange=function(e){null!=e&&this.passedElement.triggerEvent("change",{value:e})},e.prototype._handleButtonAction=function(e,t){if(0!==e.length&&this.config.removeItems&&this.config.removeItemButton){var i=t&&we(t.parentNode),n=i&&e.find((function(e){return e.id===i}));if(n&&(this._removeItem(n),this._triggerChange(n.value),this._isSelectOneElement&&!this._hasNonChoicePlaceholder)){var s=this._store.choices.reverse().find((function(e){return!e.disabled&&e.placeholder}));s&&(this._addItem(s),s.value&&this._triggerChange(s.value))}}},e.prototype._handleItemAction=function(e,t,i){var n=this;if(void 0===i&&(i=!1),0!==e.length&&this.config.removeItems&&!this._isSelectOneElement){var s=we(t);s&&(e.forEach((function(e){e.id!==s||e.highlighted?!i&&e.highlighted&&n.unhighlightItem(e):n.highlightItem(e)})),this.input.focus())}},e.prototype._handleChoiceAction=function(e,t,i){var n=this,s=we(t),o=s&&this._store.getChoiceById(s);if(!o)return!1;var r=this.dropdown.isActive,a=!1;return this._store.withTxn((function(){if(!o.selected&&!o.disabled&&n._canAddItem(e,o.value).response){if(n.config.singleModeForMultiSelect&&0!==e.length){var t=e[e.length-1];n._removeItem(t)}n.passedElement.triggerEvent("choice",n._getChoiceForOutput(o,i)),n._addItem(o),n.clearInput(),a=!0}})),!!a&&(this._triggerChange(o.value),r&&(this.config.singleModeForMultiSelect||this._isSelectOneElement)&&(this.hideDropdown(!0),this.containerOuter.focus()),!0)},e.prototype._handleBackspace=function(e){if(this.config.removeItems&&0!==e.length){var t=e[e.length-1],i=e.some((function(e){return e.highlighted}));this.config.editItems&&!i&&t?(this.input.value=t.value,this.input.setWidth(),this._removeItem(t),this._triggerChange(t.value)):(i||this.highlightItem(t,!1),this.removeHighlightedItems(!0))}},e.prototype._loadChoices=function(){var e;if(this._isTextElement){this._presetChoices=this.config.items.map((function(e){return S(e,!1)}));var t=this.passedElement.value;if(t){var i=t.split(this.config.delimiter).map((function(e){return S(e,!1)}));this._presetChoices=this._presetChoices.concat(i)}this._presetChoices.forEach((function(e){e.selected=!0}))}else if(this._isSelectElement){this._presetChoices=this.config.choices.map((function(e){return S(e,!0)}));var n=this.passedElement.optionsAsChoices();n&&(e=this._presetChoices).push.apply(e,n)}},e.prototype._handleLoadingState=function(e){void 0===e&&(e=!0);var t=this.itemList.element.querySelector(d(this.config.classNames.placeholder));e?(this.disable(),this.containerOuter.addLoadingState(),this._isSelectOneElement?t?t.innerHTML=this.config.loadingText:(t=this._templates.placeholder(this.config,this.config.loadingText))&&this.itemList.append(t):this.input.placeholder=this.config.loadingText):(this.enable(),this.containerOuter.removeLoadingState(),this._isSelectOneElement?t&&(t.innerHTML=this._placeholderValue||""):this.input.placeholder=this._placeholderValue||"")},e.prototype._handleSearch=function(e){if(this.input.isFocussed){var t=this._store.choices,i=this.config,n=i.searchFloor,s=i.searchChoices,o=t.some((function(e){return!e.active}));if(null!=e&&e.length>=n){var r=s?this._searchChoices(e):0;null!==r&&this.passedElement.triggerEvent("search",{value:e,resultCount:r})}else o&&this._stopSearch()}},e.prototype._canAddItem=function(e,t){var i=this,n=!0,s="";(this.config.maxItemCount>0&&this.config.maxItemCount<=e.length&&(this.config.singleModeForMultiSelect||(n=!1,s="function"==typeof this.config.maxItemText?this.config.maxItemText(this.config.maxItemCount):this.config.maxItemText)),n&&this._canAddUserChoices&&""!==t&&"function"==typeof this.config.addItemFilter&&!this.config.addItemFilter(t)&&(n=!1,s="function"==typeof this.config.customAddItemText?this.config.customAddItemText(a(t),t):this.config.customAddItemText),!n||""===t||!this._isSelectElement&&this.config.duplicateItemsAllowed)||this._store.items.find((function(e){return i.config.valueComparer(e.value,t)}))&&(n=!1,s="function"==typeof this.config.uniqueItemText?this.config.uniqueItemText(a(t),t):this.config.uniqueItemText);return n&&(s="function"==typeof this.config.addItemText?this.config.addItemText(a(t),t):this.config.addItemText),{response:n,notice:{trusted:s}}},e.prototype._searchChoices=function(e){var t=e.trim().replace(/\s{2,}/," ");if(0===t.length||t===this._currentValue)return null;var i=this._searcher;i.isEmptyIndex()&&i.index(this._store.searchableChoices);var n=i.search(t);return this._currentValue=t,this._highlightPosition=0,this._isSearching=!0,this._store.dispatch(function(e){return{type:"FILTER_CHOICES",results:e}}(n)),n.length},e.prototype._stopSearch=function(){var e=this._isSearching;this._currentValue="",this._isSearching=!1,e&&this._store.dispatch({type:"ACTIVATE_CHOICES",active:!0})},e.prototype._addEventListeners=function(){var e=this.config.shadowRoot||document.documentElement;e.addEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.addEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.addEventListener("mousedown",this._onMouseDown,!0),e.addEventListener("click",this._onClick,{passive:!0}),e.addEventListener("touchmove",this._onTouchMove,{passive:!0}),this.dropdown.element.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("input",this._onInput,{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()},e.prototype._removeEventListeners=function(){var e=this.config.shadowRoot||document.documentElement;e.removeEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.removeEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.removeEventListener("mousedown",this._onMouseDown,!0),e.removeEventListener("click",this._onClick),e.removeEventListener("touchmove",this._onTouchMove),this.dropdown.element.removeEventListener("mouseover",this._onMouseOver),this._isSelectOneElement&&(this.containerOuter.element.removeEventListener("focus",this._onFocus),this.containerOuter.element.removeEventListener("blur",this._onBlur)),this.input.element.removeEventListener("keyup",this._onKeyUp),this.input.element.removeEventListener("input",this._onInput),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()},e.prototype._onKeyDown=function(e){var t=e.keyCode,i=this._store.items,n=this.input.isFocussed,s=this.dropdown.isActive,o=this.itemList.hasChildren(),r=1===e.key.length||2===e.key.length&&e.key.charCodeAt(0)>=55296||"Unidentified"===e.key;switch(this._isTextElement||s||(this.showDropdown(),!this.input.isFocussed&&r&&(this.input.value+=e.key)),t){case 65:return this._onSelectKey(e,o);case 13:return this._onEnterKey(e,i,s);case 27:return this._onEscapeKey(e,s);case 38:case 33:case 40:case 34:return this._onDirectionKey(e,s);case 8:case 46:return this._onDeleteKey(e,i,n)}},e.prototype._onKeyUp=function(){this._canSearch=this.config.searchEnabled},e.prototype._onInput=function(){var e=this.input.value;if(e){if(this._isTextElement){var t=this._canAddItem(this._store.items,e);t.notice&&(this._displayAddItemNotice(t),this.showDropdown(!0))}if(this._canSearch){this._handleSearch(e);var i=this._canAddItem(this._store.items,e);i.response||this._displayAddItemNotice(i),this._canAddUserChoices&&(this._highlightPosition=0,this._highlightChoice())}}else this._isTextElement?this.hideDropdown(!0):this._stopSearch()},e.prototype._displayAddItemNotice=function(e){var t=this._templates.notice(this.config,e.notice,"add-choice"),i="".concat(d(this.config.classNames.addChoice),"[data-choice-selectable]"),n=this.choiceList.element.querySelector(i);n?n.outerHTML=t.outerHTML:this.choiceList.prepend(t)},e.prototype._onSelectKey=function(e,t){var i=e.ctrlKey,n=e.metaKey;(i||n)&&t&&(this._canSearch=!1,this.config.removeItems&&!this.input.value&&this.input.element===document.activeElement&&this.highlightAll())},e.prototype._onEnterKey=function(e,t,i){var n=this,s=this.input.value,o=e.target;if(o&&o.hasAttribute("data-button"))return e.preventDefault(),void this._handleButtonAction(t,o);if(!i&&this._isSelectOneElement)return e.preventDefault(),void this.showDropdown();if(i){var r=this.dropdown.element.querySelector(d(this.config.classNames.highlightedState));if(r&&this._handleChoiceAction(t,r,13))return e.preventDefault(),void this.unhighlightAll();s||this.hideDropdown(!0)}o&&s&&this._canAddUserChoices&&(this._canAddItem(t,s).response&&(this._store.withTxn((function(){if((n._isSelectOneElement||n.config.singleModeForMultiSelect)&&0!==t.length){var e=t[t.length-1];n._removeItem(e)}var i=!0;if(!n._isSelectElement&&n.config.duplicateItemsAllowed||(i=!n._findAndSelectChoiceByValue(s)),i){var o=a(s),r=n.config.allowHtmlUserInput||o===s?s:{escaped:o,raw:s};n._addChoice(S({value:r,label:r,selected:!0},!1))}n.clearInput(),n.unhighlightAll(),n._triggerChange(s)})),(this._isTextElement||this._isSelectOneElement)&&this.hideDropdown(!0)))},e.prototype._onEscapeKey=function(e,t){t&&(e.stopPropagation(),this.hideDropdown(!0),this.containerOuter.focus())},e.prototype._onDirectionKey=function(e,t){var i,n,s,o=e.keyCode,r=e.metaKey;if(t||this._isSelectOneElement){this.showDropdown(),this._canSearch=!1;var a=40===o||34===o?1:-1,c="[data-choice-selectable]",h=void 0;if(r||34===o||33===o)h=a>0?this.dropdown.element.querySelector("".concat(c,":last-of-type")):this.dropdown.element.querySelector(c);else{var l=this.dropdown.element.querySelector(d(this.config.classNames.highlightedState));h=l?function(e,t,i){void 0===i&&(i=1);for(var n="".concat(i>0?"next":"previous","ElementSibling"),s=e[n];s;){if(s.matches(t))return s;s=s[n]}return s}(l,c,a):this.dropdown.element.querySelector(c)}h&&(i=h,n=this.choiceList.element,void 0===(s=a)&&(s=1),i&&(s>0?n.scrollTop+n.offsetHeight>=i.offsetTop+i.offsetHeight:i.offsetTop>=n.scrollTop)||this.choiceList.scrollToChildElement(h,a),this._highlightChoice(h)),e.preventDefault()}},e.prototype._onDeleteKey=function(e,t,i){var n=e.target;this._isSelectOneElement||n.value||!i||(this._handleBackspace(t),e.preventDefault())},e.prototype._onTouchMove=function(){this._wasTap&&(this._wasTap=!1)},e.prototype._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},e.prototype._onMouseDown=function(e){var t=e.target;if(t instanceof HTMLElement){if(Ce&&this.choiceList.element.contains(t)){var i=this.choiceList.element.firstElementChild;this._isScrollingOnIe="ltr"===this._direction?e.offsetX>=i.offsetWidth:e.offsetX0&&this.unhighlightAll(),this.containerOuter.removeFocusState(),this.hideDropdown(!0))},e.prototype._onFocus=function(e){var t,i=this,n=e.target;n&&this.containerOuter.element.contains(n)&&((t={})[m]=function(){n===i.input.element&&i.containerOuter.addFocusState()},t[g]=function(){i.containerOuter.addFocusState(),n===i.input.element&&i.showDropdown(!0)},t[v]=function(){n===i.input.element&&(i.showDropdown(!0),i.containerOuter.addFocusState())},t)[this._elementType]()},e.prototype._onBlur=function(e){var t,i=this,n=e.target;if(n&&this.containerOuter.element.contains(n)&&!this._isScrollingOnIe){var s=this._store.activeChoices.some((function(e){return e.highlighted}));((t={})[m]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),s&&i.unhighlightAll(),i.hideDropdown(!0))},t[g]=function(){i.containerOuter.removeFocusState(),(n===i.input.element||n===i.containerOuter.element&&!i._canSearch)&&i.hideDropdown(!0)},t[v]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),i.hideDropdown(!0),s&&i.unhighlightAll())},t)[this._elementType]()}else this._isScrollingOnIe=!1,this.input.element.focus()},e.prototype._onFormReset=function(){var e=this;this._store.withTxn((function(){e.clearInput(),e.hideDropdown(),e.refresh(!1,!1,!0),0!==e._initialItems.length&&e.setChoiceByValue(e._initialItems)}))},e.prototype._highlightChoice=function(e){var t,i=this;void 0===e&&(e=null);var n=Array.from(this.dropdown.element.querySelectorAll("[data-choice-selectable]"));if(n.length){var s=e;Array.from(this.dropdown.element.querySelectorAll(d(this.config.classNames.highlightedState))).forEach((function(e){var t;(t=e.classList).remove.apply(t,u(i.config.classNames.highlightedState)),e.setAttribute("aria-selected","false")})),s?this._highlightPosition=n.indexOf(s):(s=n.length>this._highlightPosition?n[this._highlightPosition]:n[n.length-1])||(s=n[0]),(t=s.classList).add.apply(t,u(this.config.classNames.highlightedState)),s.setAttribute("aria-selected","true"),this.passedElement.triggerEvent("highlightChoice",{el:s}),this.dropdown.isActive&&(this.input.setActiveDescendant(s.id),this.containerOuter.setActiveDescendant(s.id))}},e.prototype._addItem=function(e,t){void 0===t&&(t=!0);var i=e.id;if(0===i)throw new TypeError("item.id must be set before _addItem is called for a choice/item");this._store.dispatch(function(e){return{type:"ADD_ITEM",item:e}}(e)),this._isSelectOneElement&&this.removeActiveItems(i),t&&this.passedElement.triggerEvent("addItem",this._getChoiceForOutput(e))},e.prototype._removeItem=function(e){e.id&&(this._store.dispatch(function(e){return{type:"REMOVE_ITEM",item:e}}(e)),this.passedElement.triggerEvent("removeItem",this._getChoiceForOutput(e)))},e.prototype._addChoice=function(e,t){if(void 0===t&&(t=!0),0!==e.id)throw new TypeError("Can not re-add a choice which has already been added");var i=e;this._lastAddedChoiceId++,i.id=this._lastAddedChoiceId,i.elementId="".concat(this._baseId,"-").concat(this._idNames.itemChoice,"-").concat(i.id),this.config.prependValue&&(i.value=this.config.prependValue+i.value),this.config.appendValue&&(i.value+=this.config.appendValue.toString()),(this.config.prependValue||this.config.appendValue)&&i.element&&(i.element.value=i.value),this._store.dispatch(function(e){return{type:"ADD_CHOICE",choice:e}}(e)),e.selected&&this._addItem(e,t)},e.prototype._addGroup=function(e,t){var i=this;if(void 0===t&&(t=!0),0!==e.id)throw new TypeError("Can not re-add a group which has already been added");if(this._store.dispatch(function(e){return{type:"ADD_GROUP",group:e}}(e)),e.choices){var n=e;this._lastAddedGroupId++,n.id=this._lastAddedGroupId;var s=e.id,o=e.choices;n.choices=[],o.forEach((function(n){var o=n;o.groupId=s,e.disabled&&(o.disabled=!0),i._addChoice(o,t)}))}},e.prototype._createTemplates=function(){var e=this,t=this.config.callbackOnCreateTemplates,i={};t&&"function"==typeof t&&(i=t.call(this,c,M));var n={};Object.keys(F).forEach((function(t){n[t]=t in i?i[t].bind(e):F[t].bind(e)})),this._templates=n},e.prototype._createElements=function(){this.containerOuter=new _({element:this._templates.containerOuter(this.config,this._direction,this._isSelectElement,this._isSelectOneElement,this.config.searchEnabled,this._elementType,this.config.labelId),classNames:this.config.classNames,type:this._elementType,position:this.config.position}),this.containerInner=new _({element:this._templates.containerInner(this.config),classNames:this.config.classNames,type:this._elementType,position:this.config.position}),this.input=new y({element:this._templates.input(this.config,this._placeholderValue),classNames:this.config.classNames,type:this._elementType,preventPaste:!this.config.paste}),this.choiceList=new b({element:this._templates.choiceList(this.config,this._isSelectOneElement)}),this.itemList=new b({element:this._templates.itemList(this.config,this._isSelectOneElement)}),this.dropdown=new f({element:this._templates.dropdown(this.config),classNames:this.config.classNames,type:this._elementType})},e.prototype._createStructure=function(){this.passedElement.conceal(),this.containerInner.wrap(this.passedElement.element),this.containerOuter.wrap(this.containerInner.element),this._isSelectOneElement?this.input.placeholder=this.config.searchPlaceholderValue||"":(this._placeholderValue&&(this.input.placeholder=this._placeholderValue),this.input.setWidth()),this.containerOuter.element.appendChild(this.containerInner.element),this.containerOuter.element.appendChild(this.dropdown.element),this.containerInner.element.appendChild(this.itemList.element),this.dropdown.element.appendChild(this.choiceList.element),this._isSelectOneElement?this.config.searchEnabled&&this.dropdown.element.insertBefore(this.input.element,this.dropdown.element.firstChild):this.containerInner.element.appendChild(this.input.element),this._highlightPosition=0,this._isSearching=!1},e.prototype._initStore=function(){var e=this;this._store.subscribe(this._render),this._store.withTxn((function(){e._addPredefinedChoices(e._presetChoices,e._isSelectOneElement&&!e._hasNonChoicePlaceholder,!1)}))},e.prototype._addPredefinedChoices=function(e,t,i){var n=this;if(void 0===t&&(t=!1),void 0===i&&(i=!0),this.config.shouldSort&&e.sort(this.config.sorter),t){var s=-1===e.findIndex((function(e){return!!e.selected}));if(s){var o=e.findIndex((function(e){return void 0===e.disabled||!e.disabled}));if(-1!==o)e[o].selected=!0}}e.forEach((function(e){"choices"in e?n._isSelectElement&&n._addGroup(e,i):n._addChoice(e,i)}))},e.prototype._findAndSelectChoiceByValue=function(e){var t=this,i=this._store.choices.find((function(i){return t.config.valueComparer(i.value,e)}));return!(!i||i.selected)&&(this._addItem(i),!0)},e.prototype._generatePlaceholderValue=function(){if(!this.config.placeholder)return null;if(this._hasNonChoicePlaceholder)return this.config.placeholderValue;if(this._isSelectElement){var e=this.passedElement.placeholderOption;return e?e.text:null}return null},e.prototype._warnChoicesInitFailed=function(e){if(!this.config.silent){if(!this.initialised)throw new TypeError("".concat(e," called on a non-initialised instance of Choices"));if(!this.initialisedOK)throw new TypeError("".concat(e," called for an element which has multiple instances of Choices initialised on it"))}},e.version="11.0.0-rc5",e}();export{Se as default}; diff --git a/public/assets/scripts/choices.search-basic.mjs b/public/assets/scripts/choices.search-basic.mjs index dcf2517a..c157ba3d 100644 --- a/public/assets/scripts/choices.search-basic.mjs +++ b/public/assets/scripts/choices.search-basic.mjs @@ -99,14 +99,6 @@ var highlightItem = function (item, highlighted) { return ({ highlighted: highlighted, }); }; -var clearAll = function () { return ({ - type: "CLEAR_ALL" /* ActionType.CLEAR_ALL */, -}); }; -var setTxn = function (txn) { return ({ - type: "SET_TRANSACTION" /* ActionType.SET_TRANSACTION */, - txn: txn, -}); }; - /* eslint-disable @typescript-eslint/no-explicit-any */ var getRandomNumber = function (min, max) { return Math.floor(Math.random() * (max - min) + min); @@ -234,9 +226,6 @@ var dispatchEvent = function (element, type, customArgs) { }); return element.dispatchEvent(event); }; -var cloneObject = function (obj) { - return obj !== undefined ? JSON.parse(JSON.stringify(obj)) : undefined; -}; /** * Returns an array of keys present on the first but missing on the second object */ @@ -974,447 +963,85 @@ var DEFAULT_CONFIG = { var ObjectsInConfig = ['fuseOptions', 'classNames']; -/** - * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js - * - * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes - * during build. - * @param {number} code - */ -function formatProdErrorMessage(code) { - return "Minified Redux error #" + code + "; visit https://redux.js.org/Errors?code=" + code + " for the full message or " + 'use the non-minified dev environment for full errors. '; -} - -// Inlined version of the `symbol-observable` polyfill -var $$observable = function () { - return typeof Symbol === 'function' && Symbol.observable || '@@observable'; -}(); - -/** - * These are private action types reserved by Redux. - * For any unknown actions, you must return the current state. - * If the current state is undefined, you must return the initial state. - * Do not reference these action types directly in your code. - */ -var randomString = function randomString() { - return Math.random().toString(36).substring(7).split('').join('.'); -}; -var ActionTypes = { - INIT: "@@redux/INIT" + randomString(), - REPLACE: "@@redux/REPLACE" + randomString(), - PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() { - return "@@redux/PROBE_UNKNOWN_ACTION" + randomString(); - } -}; - -/** - * @param {any} obj The object to inspect. - * @returns {boolean} True if the argument appears to be a plain object. - */ -function isPlainObject(obj) { - if (typeof obj !== 'object' || obj === null) return false; - var proto = obj; - while (Object.getPrototypeOf(proto) !== null) { - proto = Object.getPrototypeOf(proto); - } - return Object.getPrototypeOf(obj) === proto; -} - -/** - * @deprecated - * - * **We recommend using the `configureStore` method - * of the `@reduxjs/toolkit` package**, which replaces `createStore`. - * - * Redux Toolkit is our recommended approach for writing Redux logic today, - * including store setup, reducers, data fetching, and more. - * - * **For more details, please read this Redux docs page:** - * **https://redux.js.org/introduction/why-rtk-is-redux-today** - * - * `configureStore` from Redux Toolkit is an improved version of `createStore` that - * simplifies setup and helps avoid common bugs. - * - * You should not be using the `redux` core package by itself today, except for learning purposes. - * The `createStore` method from the core `redux` package will not be removed, but we encourage - * all users to migrate to using Redux Toolkit for all Redux code. - * - * If you want to use `createStore` without this visual deprecation warning, use - * the `legacy_createStore` import instead: - * - * `import { legacy_createStore as createStore} from 'redux'` - * - */ - -function createStore(reducer, preloadedState, enhancer) { - var _ref2; - if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') { - throw new Error(formatProdErrorMessage(0) ); - } - if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { - enhancer = preloadedState; - preloadedState = undefined; - } - if (typeof enhancer !== 'undefined') { - if (typeof enhancer !== 'function') { - throw new Error(formatProdErrorMessage(1) ); - } - return enhancer(createStore)(reducer, preloadedState); - } - if (typeof reducer !== 'function') { - throw new Error(formatProdErrorMessage(2) ); - } - var currentReducer = reducer; - var currentState = preloadedState; - var currentListeners = []; - var nextListeners = currentListeners; - var isDispatching = false; - /** - * This makes a shallow copy of currentListeners so we can use - * nextListeners as a temporary list while dispatching. - * - * This prevents any bugs around consumers calling - * subscribe/unsubscribe in the middle of a dispatch. - */ - - function ensureCanMutateNextListeners() { - if (nextListeners === currentListeners) { - nextListeners = currentListeners.slice(); - } - } - /** - * Reads the state tree managed by the store. - * - * @returns {any} The current state tree of your application. - */ - - function getState() { - if (isDispatching) { - throw new Error(formatProdErrorMessage(3) ); - } - return currentState; - } - /** - * Adds a change listener. It will be called any time an action is dispatched, - * and some part of the state tree may potentially have changed. You may then - * call `getState()` to read the current state tree inside the callback. - * - * You may call `dispatch()` from a change listener, with the following - * caveats: - * - * 1. The subscriptions are snapshotted just before every `dispatch()` call. - * If you subscribe or unsubscribe while the listeners are being invoked, this - * will not have any effect on the `dispatch()` that is currently in progress. - * However, the next `dispatch()` call, whether nested or not, will use a more - * recent snapshot of the subscription list. - * - * 2. The listener should not expect to see all state changes, as the state - * might have been updated multiple times during a nested `dispatch()` before - * the listener is called. It is, however, guaranteed that all subscribers - * registered before the `dispatch()` started will be called with the latest - * state by the time it exits. - * - * @param {Function} listener A callback to be invoked on every dispatch. - * @returns {Function} A function to remove this change listener. - */ - - function subscribe(listener) { - if (typeof listener !== 'function') { - throw new Error(formatProdErrorMessage(4) ); - } - if (isDispatching) { - throw new Error(formatProdErrorMessage(5) ); - } - var isSubscribed = true; - ensureCanMutateNextListeners(); - nextListeners.push(listener); - return function unsubscribe() { - if (!isSubscribed) { - return; - } - if (isDispatching) { - throw new Error(formatProdErrorMessage(6) ); - } - isSubscribed = false; - ensureCanMutateNextListeners(); - var index = nextListeners.indexOf(listener); - nextListeners.splice(index, 1); - currentListeners = null; - }; - } - /** - * Dispatches an action. It is the only way to trigger a state change. - * - * The `reducer` function, used to create the store, will be called with the - * current state tree and the given `action`. Its return value will - * be considered the **next** state of the tree, and the change listeners - * will be notified. - * - * The base implementation only supports plain object actions. If you want to - * dispatch a Promise, an Observable, a thunk, or something else, you need to - * wrap your store creating function into the corresponding middleware. For - * example, see the documentation for the `redux-thunk` package. Even the - * middleware will eventually dispatch plain object actions using this method. - * - * @param {Object} action A plain object representing “what changed”. It is - * a good idea to keep actions serializable so you can record and replay user - * sessions, or use the time travelling `redux-devtools`. An action must have - * a `type` property which may not be `undefined`. It is a good idea to use - * string constants for action types. - * - * @returns {Object} For convenience, the same action object you dispatched. - * - * Note that, if you use a custom middleware, it may wrap `dispatch()` to - * return something else (for example, a Promise you can await). - */ - - function dispatch(action) { - if (!isPlainObject(action)) { - throw new Error(formatProdErrorMessage(7) ); - } - if (typeof action.type === 'undefined') { - throw new Error(formatProdErrorMessage(8) ); - } - if (isDispatching) { - throw new Error(formatProdErrorMessage(9) ); - } - try { - isDispatching = true; - currentState = currentReducer(currentState, action); - } finally { - isDispatching = false; - } - var listeners = currentListeners = nextListeners; - for (var i = 0; i < listeners.length; i++) { - var listener = listeners[i]; - listener(); - } - return action; - } - /** - * Replaces the reducer currently used by the store to calculate the state. - * - * You might need this if your app implements code splitting and you want to - * load some of the reducers dynamically. You might also need this if you - * implement a hot reloading mechanism for Redux. - * - * @param {Function} nextReducer The reducer for the store to use instead. - * @returns {void} - */ - - function replaceReducer(nextReducer) { - if (typeof nextReducer !== 'function') { - throw new Error(formatProdErrorMessage(10) ); - } - currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT. - // Any reducers that existed in both the new and old rootReducer - // will receive the previous state. This effectively populates - // the new state tree with any relevant data from the old one. - - dispatch({ - type: ActionTypes.REPLACE - }); - } - /** - * Interoperability point for observable/reactive libraries. - * @returns {observable} A minimal observable of state changes. - * For more information, see the observable proposal: - * https://github.com/tc39/proposal-observable - */ - - function observable() { - var _ref; - var outerSubscribe = subscribe; - return _ref = { - /** - * The minimal observable subscription method. - * @param {Object} observer Any object that can be used as an observer. - * The observer object should have a `next` method. - * @returns {subscription} An object with an `unsubscribe` method that can - * be used to unsubscribe the observable from the store, and prevent further - * emission of values from the observable. - */ - subscribe: function subscribe(observer) { - if (typeof observer !== 'object' || observer === null) { - throw new Error(formatProdErrorMessage(11) ); - } - function observeState() { - if (observer.next) { - observer.next(getState()); - } - } - observeState(); - var unsubscribe = outerSubscribe(observeState); - return { - unsubscribe: unsubscribe - }; - } - }, _ref[$$observable] = function () { - return this; - }, _ref; - } // When a store is created, an "INIT" action is dispatched so that every - // reducer returns their initial state. This effectively populates - // the initial state tree. - - dispatch({ - type: ActionTypes.INIT - }); - return _ref2 = { - dispatch: dispatch, - subscribe: subscribe, - getState: getState, - replaceReducer: replaceReducer - }, _ref2[$$observable] = observable, _ref2; -} -function assertReducerShape(reducers) { - Object.keys(reducers).forEach(function (key) { - var reducer = reducers[key]; - var initialState = reducer(undefined, { - type: ActionTypes.INIT - }); - if (typeof initialState === 'undefined') { - throw new Error(formatProdErrorMessage(12) ); - } - if (typeof reducer(undefined, { - type: ActionTypes.PROBE_UNKNOWN_ACTION() - }) === 'undefined') { - throw new Error(formatProdErrorMessage(13) ); - } - }); -} -/** - * Turns an object whose values are different reducer functions, into a single - * reducer function. It will call every child reducer, and gather their results - * into a single state object, whose keys correspond to the keys of the passed - * reducer functions. - * - * @param {Object} reducers An object whose values correspond to different - * reducer functions that need to be combined into one. One handy way to obtain - * it is to use ES6 `import * as reducers` syntax. The reducers may never return - * undefined for any action. Instead, they should return their initial state - * if the state passed to them was undefined, and the current state for any - * unrecognized action. - * - * @returns {Function} A reducer function that invokes every reducer inside the - * passed object, and builds a state object with the same shape. - */ - -function combineReducers(reducers) { - var reducerKeys = Object.keys(reducers); - var finalReducers = {}; - for (var i = 0; i < reducerKeys.length; i++) { - var key = reducerKeys[i]; - if (typeof reducers[key] === 'function') { - finalReducers[key] = reducers[key]; - } - } - var finalReducerKeys = Object.keys(finalReducers); // This is used to make sure we don't warn about the same - var shapeAssertionError; - try { - assertReducerShape(finalReducers); - } catch (e) { - shapeAssertionError = e; - } - return function combination(state, action) { - if (state === void 0) { - state = {}; - } - if (shapeAssertionError) { - throw shapeAssertionError; - } - var hasChanged = false; - var nextState = {}; - for (var _i = 0; _i < finalReducerKeys.length; _i++) { - var _key = finalReducerKeys[_i]; - var reducer = finalReducers[_key]; - var previousStateForKey = state[_key]; - var nextStateForKey = reducer(previousStateForKey, action); - if (typeof nextStateForKey === 'undefined') { - action && action.type; - throw new Error(formatProdErrorMessage(14) ); - } - nextState[_key] = nextStateForKey; - hasChanged = hasChanged || nextStateForKey !== previousStateForKey; - } - hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length; - return hasChanged ? nextState : state; - }; -} - -function items(state, action) { - if (state === void 0) { state = []; } - if (action === void 0) { action = {}; } +function items(s, action) { + var state = s; + var update = false; switch (action.type) { case "ADD_ITEM" /* ActionType.ADD_ITEM */: { var item = action.item; - if (!item.id) { - return state; + if (item.id) { + item.selected = true; + var el = item.element; + if (el) { + el.selected = true; + el.setAttribute('selected', ''); + } + update = true; + state.push(item); + state.forEach(function (obj) { + // eslint-disable-next-line no-param-reassign + obj.highlighted = false; + }); } - item.selected = true; - var el = item.element; - if (el) { - el.selected = true; - el.setAttribute('selected', ''); - } - return __spreadArray(__spreadArray([], state, true), [item], false).map(function (obj) { - var choice = obj; - choice.highlighted = false; - return choice; - }); + break; } case "REMOVE_ITEM" /* ActionType.REMOVE_ITEM */: { var item_1 = action.item; - if (!item_1.id) { - return state; + if (item_1.id) { + item_1.selected = false; + var el = item_1.element; + if (el) { + el.selected = false; + el.removeAttribute('selected'); + } + update = true; + state = state.filter(function (choice) { return choice.id !== item_1.id; }); } - item_1.selected = false; - var el = item_1.element; - if (el) { - el.selected = false; - el.removeAttribute('selected'); - } - return state.filter(function (choice) { return choice.id !== item_1.id; }); + break; } case "REMOVE_CHOICE" /* ActionType.REMOVE_CHOICE */: { var choice_1 = action.choice; - return state.filter(function (item) { return item.id !== choice_1.id; }); + update = true; + state = state.filter(function (item) { return item.id !== choice_1.id; }); + break; } case "HIGHLIGHT_ITEM" /* ActionType.HIGHLIGHT_ITEM */: { var highlightItemAction_1 = action; - return state.map(function (obj) { + update = true; + state.forEach(function (obj) { var item = obj; if (item.id === highlightItemAction_1.item.id) { item.highlighted = highlightItemAction_1.highlighted; } - return item; }); - } - default: { - return state; + break; } } + return { state: state, update: update }; } -function groups(state, action) { - if (state === void 0) { state = []; } - if (action === void 0) { action = {}; } +function groups(s, action) { + var state = s; + var update = false; switch (action.type) { case "ADD_GROUP" /* ActionType.ADD_GROUP */: { var addGroupAction = action; - return __spreadArray(__spreadArray([], state, true), [addGroupAction.group], false); + update = true; + state.push(addGroupAction.group); + break; } case "CLEAR_CHOICES" /* ActionType.CLEAR_CHOICES */: { - return []; - } - default: { - return state; + update = true; + state = []; + break; } } + return { state: state, update: update }; } -function choices(state, action) { - if (state === void 0) { state = []; } - if (action === void 0) { action = {}; } +function choices(s, action) { + var state = s; + var update = false; switch (action.type) { case "ADD_CHOICE" /* ActionType.ADD_CHOICE */: { var choice = action.choice; @@ -1423,36 +1050,41 @@ function choices(state, action) { A selected choice has been added to the passed input's value (added as an item) An active choice appears within the choice dropdown */ - return __spreadArray(__spreadArray([], state, true), [choice], false); + state.push(choice); + update = true; + break; } case "REMOVE_CHOICE" /* ActionType.REMOVE_CHOICE */: { var choice_1 = action.choice; - return state.filter(function (obj) { return obj.id !== choice_1.id; }); + update = true; + state = state.filter(function (obj) { return obj.id !== choice_1.id; }); + break; } case "ADD_ITEM" /* ActionType.ADD_ITEM */: { var item = action.item; // trigger a rebuild of the choices list as the item can not be added multiple times if (item.id && item.selected) { - return __spreadArray([], state, true); + update = true; } - return state; + break; } case "REMOVE_ITEM" /* ActionType.REMOVE_ITEM */: { var item = action.item; // trigger a rebuild of the choices list as the item can be added if (item.id && !item.selected) { - return __spreadArray([], state, true); + update = true; } - return state; + break; } case "FILTER_CHOICES" /* ActionType.FILTER_CHOICES */: { var results = action.results; + update = true; // avoid O(n^2) algorithm complexity when searching/filtering choices var scoreLookup_1 = []; results.forEach(function (result) { scoreLookup_1[result.item.id] = result; }); - return state.map(function (obj) { + state.forEach(function (obj) { var choice = obj; var result = scoreLookup_1[choice.id]; if (result !== undefined) { @@ -1465,102 +1097,110 @@ function choices(state, action) { choice.rank = 0; choice.active = false; } - return choice; }); + break; } case "ACTIVATE_CHOICES" /* ActionType.ACTIVATE_CHOICES */: { var active_1 = action.active; - return state.map(function (obj) { + update = true; + state.forEach(function (obj) { var choice = obj; choice.active = active_1; return choice; }); + break; } case "CLEAR_CHOICES" /* ActionType.CLEAR_CHOICES */: { - return []; - } - default: { - return state; + update = true; + state = []; + break; } } + return { state: state, update: update }; } -var general = function (state, action) { - if (state === void 0) { state = 0; } - if (action === void 0) { action = {}; } - switch (action.type) { - case "SET_TRANSACTION" /* ActionType.SET_TRANSACTION */: { - if (action.txn) { - return state + 1; - } - return Math.max(0, state - 1); - } - default: { - return state; - } - } -}; - -var defaultState = { - groups: [], - items: [], - choices: [], - txn: 0, -}; -var appReducer = combineReducers({ - items: items, +var reducers = { groups: groups, + items: items, choices: choices, - txn: general, -}); -var rootReducer = function (passedState, action) { - var state = passedState; - // If we are clearing all items, groups and options we reassign - // state and then pass that state to our proper reducer. This isn't - // mutating our actual state - // See: http://stackoverflow.com/a/35641992 - if (action.type === "CLEAR_ALL" /* ActionType.CLEAR_ALL */) { - // preserve the txn state as to allow withTxn to work - var paused = state.txn; - state = cloneObject(defaultState); - state.txn = paused; - } - return appReducer(state, action); }; - -/* eslint-disable @typescript-eslint/no-explicit-any */ var Store = /** @class */ (function () { function Store() { - this._store = createStore(rootReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && - window.__REDUX_DEVTOOLS_EXTENSION__()); + this._store = this.defaultState; + this._listeners = []; + this._txn = 0; } - /** - * Subscribe store to function call (wrapped Redux method) - */ - Store.prototype.subscribe = function (onChange) { - this._store.subscribe(onChange); + Object.defineProperty(Store.prototype, "defaultState", { + // eslint-disable-next-line class-methods-use-this + get: function () { + return { + groups: [], + items: [], + choices: [], + }; + }, + enumerable: false, + configurable: true + }); + // eslint-disable-next-line class-methods-use-this + Store.prototype.changeSet = function (init) { + return { + groups: init, + items: init, + choices: init, + }; + }; + Store.prototype.resetStore = function () { + this._store = this.defaultState; + var changes = this.changeSet(true); + this._listeners.forEach(function (l) { return l(changes); }); + }; + Store.prototype.subscribe = function (onChange) { + this._listeners.push(onChange); }; - /** - * Dispatch event to store (wrapped Redux method) - */ Store.prototype.dispatch = function (action) { - this._store.dispatch(action); + var state = this._store; + var hasChanges = false; + var changes = this._outstandingChanges || this.changeSet(false); + Object.keys(reducers).forEach(function (key) { + var stateUpdate = reducers[key](state[key], action); + if (stateUpdate.update) { + hasChanges = true; + changes[key] = true; + state[key] = stateUpdate.state; + } + }); + if (hasChanges) { + if (this._txn) { + this._outstandingChanges = changes; + } + else { + this._listeners.forEach(function (l) { return l(changes); }); + } + } }; Store.prototype.withTxn = function (func) { - this._store.dispatch(setTxn(true)); + this._txn++; try { func(); } finally { - this._store.dispatch(setTxn(false)); + this._txn = Math.max(0, this._txn - 1); + if (!this._txn) { + var changeSet_1 = this._outstandingChanges; + if (changeSet_1) { + this._outstandingChanges = undefined; + this._listeners.forEach(function (l) { return l(changeSet_1); }); + } + } } }; Object.defineProperty(Store.prototype, "state", { /** - * Get store object (wrapping Redux method) + * Get store object */ get: function () { - return this._store.getState(); + return this._store; }, enumerable: false, configurable: true @@ -1630,10 +1270,10 @@ var Store = /** @class */ (function () { * Get active groups from store */ get: function () { - var _a = this, groups = _a.groups, choices = _a.choices; - return groups.filter(function (group) { + var _this = this; + return this.state.groups.filter(function (group) { var isActive = group.active && !group.disabled; - var hasActiveOptions = choices.some(function (choice) { return choice.active && !choice.disabled; }); + var hasActiveOptions = _this.state.choices.some(function (choice) { return choice.active && !choice.disabled; }); return isActive && hasActiveOptions; }, []); }, @@ -1641,7 +1281,7 @@ var Store = /** @class */ (function () { configurable: true }); Store.prototype.inTxn = function () { - return this.state.txn > 0; + return this._txn > 0; }; /** * Get single choice by it's ID @@ -3246,9 +2886,6 @@ var Choices = /** @class */ (function () { } this.initialised = false; this._store = new Store(); - this._initialState = defaultState; - this._currentState = defaultState; - this._prevState = defaultState; this._currentValue = ''; this.config.searchEnabled = (!this._isTextElement && this.config.searchEnabled) || @@ -3331,8 +2968,7 @@ var Choices = /** @class */ (function () { this._createTemplates(); this._createElements(); this._createStructure(); - this._store.subscribe(this._render); - this._render(); + this._initStore(); this._addEventListeners(); var shouldDisable = (this._isTextElement && !this.config.addItems) || this.passedElement.element.hasAttribute('disabled') || @@ -3356,6 +2992,7 @@ var Choices = /** @class */ (function () { this.passedElement.reveal(); this.containerOuter.unwrap(this.passedElement.element); this.clearStore(); + this._store._listeners = []; this._stopSearch(); this._templates = templates; this.initialised = false; @@ -3761,7 +3398,7 @@ var Choices = /** @class */ (function () { return this; }; Choices.prototype.clearStore = function () { - this._store.dispatch(clearAll()); + this._store.resetStore(); this._lastAddedChoiceId = 0; this._lastAddedGroupId = 0; // @todo integrate with Store @@ -3790,15 +3427,12 @@ var Choices = /** @class */ (function () { } } }; - Choices.prototype._render = function () { + Choices.prototype._render = function (changes) { if (this._store.inTxn()) { return; } - this._currentState = this._store.state; - var shouldRenderItems = this._currentState.items !== this._prevState.items; - var stateChanged = this._currentState.choices !== this._prevState.choices || - this._currentState.groups !== this._prevState.groups || - shouldRenderItems; + var shouldRenderItems = changes === null || changes === void 0 ? void 0 : changes.items; + var stateChanged = (changes === null || changes === void 0 ? void 0 : changes.choices) || (changes === null || changes === void 0 ? void 0 : changes.groups) || shouldRenderItems; if (!stateChanged) { return; } @@ -3808,7 +3442,6 @@ var Choices = /** @class */ (function () { if (shouldRenderItems) { this._renderItems(); } - this._prevState = this._currentState; }; Choices.prototype._renderChoices = function () { var _this = this; @@ -5027,7 +4660,6 @@ var Choices = /** @class */ (function () { }); }; Choices.prototype._createStructure = function () { - var _this = this; // Hide original element this.passedElement.conceal(); // Wrap input in container preserving DOM ordering @@ -5055,6 +4687,10 @@ var Choices = /** @class */ (function () { } this._highlightPosition = 0; this._isSearching = false; + }; + Choices.prototype._initStore = function () { + var _this = this; + this._store.subscribe(this._render); this._store.withTxn(function () { _this._addPredefinedChoices(_this._presetChoices, _this._isSelectOneElement && !_this._hasNonChoicePlaceholder, false); }); diff --git a/public/assets/scripts/choices.search-prefix.js b/public/assets/scripts/choices.search-prefix.js index 6d70816d..3d0334d2 100644 --- a/public/assets/scripts/choices.search-prefix.js +++ b/public/assets/scripts/choices.search-prefix.js @@ -105,14 +105,6 @@ highlighted: highlighted, }); }; - var clearAll = function () { return ({ - type: "CLEAR_ALL" /* ActionType.CLEAR_ALL */, - }); }; - var setTxn = function (txn) { return ({ - type: "SET_TRANSACTION" /* ActionType.SET_TRANSACTION */, - txn: txn, - }); }; - /* eslint-disable @typescript-eslint/no-explicit-any */ var getRandomNumber = function (min, max) { return Math.floor(Math.random() * (max - min) + min); @@ -240,9 +232,6 @@ }); return element.dispatchEvent(event); }; - var cloneObject = function (obj) { - return obj !== undefined ? JSON.parse(JSON.stringify(obj)) : undefined; - }; /** * Returns an array of keys present on the first but missing on the second object */ @@ -980,447 +969,85 @@ var ObjectsInConfig = ['fuseOptions', 'classNames']; - /** - * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js - * - * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes - * during build. - * @param {number} code - */ - function formatProdErrorMessage(code) { - return "Minified Redux error #" + code + "; visit https://redux.js.org/Errors?code=" + code + " for the full message or " + 'use the non-minified dev environment for full errors. '; - } - - // Inlined version of the `symbol-observable` polyfill - var $$observable = function () { - return typeof Symbol === 'function' && Symbol.observable || '@@observable'; - }(); - - /** - * These are private action types reserved by Redux. - * For any unknown actions, you must return the current state. - * If the current state is undefined, you must return the initial state. - * Do not reference these action types directly in your code. - */ - var randomString = function randomString() { - return Math.random().toString(36).substring(7).split('').join('.'); - }; - var ActionTypes = { - INIT: "@@redux/INIT" + randomString(), - REPLACE: "@@redux/REPLACE" + randomString(), - PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() { - return "@@redux/PROBE_UNKNOWN_ACTION" + randomString(); - } - }; - - /** - * @param {any} obj The object to inspect. - * @returns {boolean} True if the argument appears to be a plain object. - */ - function isPlainObject(obj) { - if (typeof obj !== 'object' || obj === null) return false; - var proto = obj; - while (Object.getPrototypeOf(proto) !== null) { - proto = Object.getPrototypeOf(proto); - } - return Object.getPrototypeOf(obj) === proto; - } - - /** - * @deprecated - * - * **We recommend using the `configureStore` method - * of the `@reduxjs/toolkit` package**, which replaces `createStore`. - * - * Redux Toolkit is our recommended approach for writing Redux logic today, - * including store setup, reducers, data fetching, and more. - * - * **For more details, please read this Redux docs page:** - * **https://redux.js.org/introduction/why-rtk-is-redux-today** - * - * `configureStore` from Redux Toolkit is an improved version of `createStore` that - * simplifies setup and helps avoid common bugs. - * - * You should not be using the `redux` core package by itself today, except for learning purposes. - * The `createStore` method from the core `redux` package will not be removed, but we encourage - * all users to migrate to using Redux Toolkit for all Redux code. - * - * If you want to use `createStore` without this visual deprecation warning, use - * the `legacy_createStore` import instead: - * - * `import { legacy_createStore as createStore} from 'redux'` - * - */ - - function createStore(reducer, preloadedState, enhancer) { - var _ref2; - if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') { - throw new Error(formatProdErrorMessage(0) ); - } - if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { - enhancer = preloadedState; - preloadedState = undefined; - } - if (typeof enhancer !== 'undefined') { - if (typeof enhancer !== 'function') { - throw new Error(formatProdErrorMessage(1) ); - } - return enhancer(createStore)(reducer, preloadedState); - } - if (typeof reducer !== 'function') { - throw new Error(formatProdErrorMessage(2) ); - } - var currentReducer = reducer; - var currentState = preloadedState; - var currentListeners = []; - var nextListeners = currentListeners; - var isDispatching = false; - /** - * This makes a shallow copy of currentListeners so we can use - * nextListeners as a temporary list while dispatching. - * - * This prevents any bugs around consumers calling - * subscribe/unsubscribe in the middle of a dispatch. - */ - - function ensureCanMutateNextListeners() { - if (nextListeners === currentListeners) { - nextListeners = currentListeners.slice(); - } - } - /** - * Reads the state tree managed by the store. - * - * @returns {any} The current state tree of your application. - */ - - function getState() { - if (isDispatching) { - throw new Error(formatProdErrorMessage(3) ); - } - return currentState; - } - /** - * Adds a change listener. It will be called any time an action is dispatched, - * and some part of the state tree may potentially have changed. You may then - * call `getState()` to read the current state tree inside the callback. - * - * You may call `dispatch()` from a change listener, with the following - * caveats: - * - * 1. The subscriptions are snapshotted just before every `dispatch()` call. - * If you subscribe or unsubscribe while the listeners are being invoked, this - * will not have any effect on the `dispatch()` that is currently in progress. - * However, the next `dispatch()` call, whether nested or not, will use a more - * recent snapshot of the subscription list. - * - * 2. The listener should not expect to see all state changes, as the state - * might have been updated multiple times during a nested `dispatch()` before - * the listener is called. It is, however, guaranteed that all subscribers - * registered before the `dispatch()` started will be called with the latest - * state by the time it exits. - * - * @param {Function} listener A callback to be invoked on every dispatch. - * @returns {Function} A function to remove this change listener. - */ - - function subscribe(listener) { - if (typeof listener !== 'function') { - throw new Error(formatProdErrorMessage(4) ); - } - if (isDispatching) { - throw new Error(formatProdErrorMessage(5) ); - } - var isSubscribed = true; - ensureCanMutateNextListeners(); - nextListeners.push(listener); - return function unsubscribe() { - if (!isSubscribed) { - return; - } - if (isDispatching) { - throw new Error(formatProdErrorMessage(6) ); - } - isSubscribed = false; - ensureCanMutateNextListeners(); - var index = nextListeners.indexOf(listener); - nextListeners.splice(index, 1); - currentListeners = null; - }; - } - /** - * Dispatches an action. It is the only way to trigger a state change. - * - * The `reducer` function, used to create the store, will be called with the - * current state tree and the given `action`. Its return value will - * be considered the **next** state of the tree, and the change listeners - * will be notified. - * - * The base implementation only supports plain object actions. If you want to - * dispatch a Promise, an Observable, a thunk, or something else, you need to - * wrap your store creating function into the corresponding middleware. For - * example, see the documentation for the `redux-thunk` package. Even the - * middleware will eventually dispatch plain object actions using this method. - * - * @param {Object} action A plain object representing “what changed”. It is - * a good idea to keep actions serializable so you can record and replay user - * sessions, or use the time travelling `redux-devtools`. An action must have - * a `type` property which may not be `undefined`. It is a good idea to use - * string constants for action types. - * - * @returns {Object} For convenience, the same action object you dispatched. - * - * Note that, if you use a custom middleware, it may wrap `dispatch()` to - * return something else (for example, a Promise you can await). - */ - - function dispatch(action) { - if (!isPlainObject(action)) { - throw new Error(formatProdErrorMessage(7) ); - } - if (typeof action.type === 'undefined') { - throw new Error(formatProdErrorMessage(8) ); - } - if (isDispatching) { - throw new Error(formatProdErrorMessage(9) ); - } - try { - isDispatching = true; - currentState = currentReducer(currentState, action); - } finally { - isDispatching = false; - } - var listeners = currentListeners = nextListeners; - for (var i = 0; i < listeners.length; i++) { - var listener = listeners[i]; - listener(); - } - return action; - } - /** - * Replaces the reducer currently used by the store to calculate the state. - * - * You might need this if your app implements code splitting and you want to - * load some of the reducers dynamically. You might also need this if you - * implement a hot reloading mechanism for Redux. - * - * @param {Function} nextReducer The reducer for the store to use instead. - * @returns {void} - */ - - function replaceReducer(nextReducer) { - if (typeof nextReducer !== 'function') { - throw new Error(formatProdErrorMessage(10) ); - } - currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT. - // Any reducers that existed in both the new and old rootReducer - // will receive the previous state. This effectively populates - // the new state tree with any relevant data from the old one. - - dispatch({ - type: ActionTypes.REPLACE - }); - } - /** - * Interoperability point for observable/reactive libraries. - * @returns {observable} A minimal observable of state changes. - * For more information, see the observable proposal: - * https://github.com/tc39/proposal-observable - */ - - function observable() { - var _ref; - var outerSubscribe = subscribe; - return _ref = { - /** - * The minimal observable subscription method. - * @param {Object} observer Any object that can be used as an observer. - * The observer object should have a `next` method. - * @returns {subscription} An object with an `unsubscribe` method that can - * be used to unsubscribe the observable from the store, and prevent further - * emission of values from the observable. - */ - subscribe: function subscribe(observer) { - if (typeof observer !== 'object' || observer === null) { - throw new Error(formatProdErrorMessage(11) ); - } - function observeState() { - if (observer.next) { - observer.next(getState()); - } - } - observeState(); - var unsubscribe = outerSubscribe(observeState); - return { - unsubscribe: unsubscribe - }; - } - }, _ref[$$observable] = function () { - return this; - }, _ref; - } // When a store is created, an "INIT" action is dispatched so that every - // reducer returns their initial state. This effectively populates - // the initial state tree. - - dispatch({ - type: ActionTypes.INIT - }); - return _ref2 = { - dispatch: dispatch, - subscribe: subscribe, - getState: getState, - replaceReducer: replaceReducer - }, _ref2[$$observable] = observable, _ref2; - } - function assertReducerShape(reducers) { - Object.keys(reducers).forEach(function (key) { - var reducer = reducers[key]; - var initialState = reducer(undefined, { - type: ActionTypes.INIT - }); - if (typeof initialState === 'undefined') { - throw new Error(formatProdErrorMessage(12) ); - } - if (typeof reducer(undefined, { - type: ActionTypes.PROBE_UNKNOWN_ACTION() - }) === 'undefined') { - throw new Error(formatProdErrorMessage(13) ); - } - }); - } - /** - * Turns an object whose values are different reducer functions, into a single - * reducer function. It will call every child reducer, and gather their results - * into a single state object, whose keys correspond to the keys of the passed - * reducer functions. - * - * @param {Object} reducers An object whose values correspond to different - * reducer functions that need to be combined into one. One handy way to obtain - * it is to use ES6 `import * as reducers` syntax. The reducers may never return - * undefined for any action. Instead, they should return their initial state - * if the state passed to them was undefined, and the current state for any - * unrecognized action. - * - * @returns {Function} A reducer function that invokes every reducer inside the - * passed object, and builds a state object with the same shape. - */ - - function combineReducers(reducers) { - var reducerKeys = Object.keys(reducers); - var finalReducers = {}; - for (var i = 0; i < reducerKeys.length; i++) { - var key = reducerKeys[i]; - if (typeof reducers[key] === 'function') { - finalReducers[key] = reducers[key]; - } - } - var finalReducerKeys = Object.keys(finalReducers); // This is used to make sure we don't warn about the same - var shapeAssertionError; - try { - assertReducerShape(finalReducers); - } catch (e) { - shapeAssertionError = e; - } - return function combination(state, action) { - if (state === void 0) { - state = {}; - } - if (shapeAssertionError) { - throw shapeAssertionError; - } - var hasChanged = false; - var nextState = {}; - for (var _i = 0; _i < finalReducerKeys.length; _i++) { - var _key = finalReducerKeys[_i]; - var reducer = finalReducers[_key]; - var previousStateForKey = state[_key]; - var nextStateForKey = reducer(previousStateForKey, action); - if (typeof nextStateForKey === 'undefined') { - action && action.type; - throw new Error(formatProdErrorMessage(14) ); - } - nextState[_key] = nextStateForKey; - hasChanged = hasChanged || nextStateForKey !== previousStateForKey; - } - hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length; - return hasChanged ? nextState : state; - }; - } - - function items(state, action) { - if (state === void 0) { state = []; } - if (action === void 0) { action = {}; } + function items(s, action) { + var state = s; + var update = false; switch (action.type) { case "ADD_ITEM" /* ActionType.ADD_ITEM */: { var item = action.item; - if (!item.id) { - return state; + if (item.id) { + item.selected = true; + var el = item.element; + if (el) { + el.selected = true; + el.setAttribute('selected', ''); + } + update = true; + state.push(item); + state.forEach(function (obj) { + // eslint-disable-next-line no-param-reassign + obj.highlighted = false; + }); } - item.selected = true; - var el = item.element; - if (el) { - el.selected = true; - el.setAttribute('selected', ''); - } - return __spreadArray(__spreadArray([], state, true), [item], false).map(function (obj) { - var choice = obj; - choice.highlighted = false; - return choice; - }); + break; } case "REMOVE_ITEM" /* ActionType.REMOVE_ITEM */: { var item_1 = action.item; - if (!item_1.id) { - return state; + if (item_1.id) { + item_1.selected = false; + var el = item_1.element; + if (el) { + el.selected = false; + el.removeAttribute('selected'); + } + update = true; + state = state.filter(function (choice) { return choice.id !== item_1.id; }); } - item_1.selected = false; - var el = item_1.element; - if (el) { - el.selected = false; - el.removeAttribute('selected'); - } - return state.filter(function (choice) { return choice.id !== item_1.id; }); + break; } case "REMOVE_CHOICE" /* ActionType.REMOVE_CHOICE */: { var choice_1 = action.choice; - return state.filter(function (item) { return item.id !== choice_1.id; }); + update = true; + state = state.filter(function (item) { return item.id !== choice_1.id; }); + break; } case "HIGHLIGHT_ITEM" /* ActionType.HIGHLIGHT_ITEM */: { var highlightItemAction_1 = action; - return state.map(function (obj) { + update = true; + state.forEach(function (obj) { var item = obj; if (item.id === highlightItemAction_1.item.id) { item.highlighted = highlightItemAction_1.highlighted; } - return item; }); - } - default: { - return state; + break; } } + return { state: state, update: update }; } - function groups(state, action) { - if (state === void 0) { state = []; } - if (action === void 0) { action = {}; } + function groups(s, action) { + var state = s; + var update = false; switch (action.type) { case "ADD_GROUP" /* ActionType.ADD_GROUP */: { var addGroupAction = action; - return __spreadArray(__spreadArray([], state, true), [addGroupAction.group], false); + update = true; + state.push(addGroupAction.group); + break; } case "CLEAR_CHOICES" /* ActionType.CLEAR_CHOICES */: { - return []; - } - default: { - return state; + update = true; + state = []; + break; } } + return { state: state, update: update }; } - function choices(state, action) { - if (state === void 0) { state = []; } - if (action === void 0) { action = {}; } + function choices(s, action) { + var state = s; + var update = false; switch (action.type) { case "ADD_CHOICE" /* ActionType.ADD_CHOICE */: { var choice = action.choice; @@ -1429,36 +1056,41 @@ A selected choice has been added to the passed input's value (added as an item) An active choice appears within the choice dropdown */ - return __spreadArray(__spreadArray([], state, true), [choice], false); + state.push(choice); + update = true; + break; } case "REMOVE_CHOICE" /* ActionType.REMOVE_CHOICE */: { var choice_1 = action.choice; - return state.filter(function (obj) { return obj.id !== choice_1.id; }); + update = true; + state = state.filter(function (obj) { return obj.id !== choice_1.id; }); + break; } case "ADD_ITEM" /* ActionType.ADD_ITEM */: { var item = action.item; // trigger a rebuild of the choices list as the item can not be added multiple times if (item.id && item.selected) { - return __spreadArray([], state, true); + update = true; } - return state; + break; } case "REMOVE_ITEM" /* ActionType.REMOVE_ITEM */: { var item = action.item; // trigger a rebuild of the choices list as the item can be added if (item.id && !item.selected) { - return __spreadArray([], state, true); + update = true; } - return state; + break; } case "FILTER_CHOICES" /* ActionType.FILTER_CHOICES */: { var results = action.results; + update = true; // avoid O(n^2) algorithm complexity when searching/filtering choices var scoreLookup_1 = []; results.forEach(function (result) { scoreLookup_1[result.item.id] = result; }); - return state.map(function (obj) { + state.forEach(function (obj) { var choice = obj; var result = scoreLookup_1[choice.id]; if (result !== undefined) { @@ -1471,102 +1103,110 @@ choice.rank = 0; choice.active = false; } - return choice; }); + break; } case "ACTIVATE_CHOICES" /* ActionType.ACTIVATE_CHOICES */: { var active_1 = action.active; - return state.map(function (obj) { + update = true; + state.forEach(function (obj) { var choice = obj; choice.active = active_1; return choice; }); + break; } case "CLEAR_CHOICES" /* ActionType.CLEAR_CHOICES */: { - return []; - } - default: { - return state; + update = true; + state = []; + break; } } + return { state: state, update: update }; } - var general = function (state, action) { - if (state === void 0) { state = 0; } - if (action === void 0) { action = {}; } - switch (action.type) { - case "SET_TRANSACTION" /* ActionType.SET_TRANSACTION */: { - if (action.txn) { - return state + 1; - } - return Math.max(0, state - 1); - } - default: { - return state; - } - } - }; - - var defaultState = { - groups: [], - items: [], - choices: [], - txn: 0, - }; - var appReducer = combineReducers({ - items: items, + var reducers = { groups: groups, + items: items, choices: choices, - txn: general, - }); - var rootReducer = function (passedState, action) { - var state = passedState; - // If we are clearing all items, groups and options we reassign - // state and then pass that state to our proper reducer. This isn't - // mutating our actual state - // See: http://stackoverflow.com/a/35641992 - if (action.type === "CLEAR_ALL" /* ActionType.CLEAR_ALL */) { - // preserve the txn state as to allow withTxn to work - var paused = state.txn; - state = cloneObject(defaultState); - state.txn = paused; - } - return appReducer(state, action); }; - - /* eslint-disable @typescript-eslint/no-explicit-any */ var Store = /** @class */ (function () { function Store() { - this._store = createStore(rootReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && - window.__REDUX_DEVTOOLS_EXTENSION__()); + this._store = this.defaultState; + this._listeners = []; + this._txn = 0; } - /** - * Subscribe store to function call (wrapped Redux method) - */ - Store.prototype.subscribe = function (onChange) { - this._store.subscribe(onChange); + Object.defineProperty(Store.prototype, "defaultState", { + // eslint-disable-next-line class-methods-use-this + get: function () { + return { + groups: [], + items: [], + choices: [], + }; + }, + enumerable: false, + configurable: true + }); + // eslint-disable-next-line class-methods-use-this + Store.prototype.changeSet = function (init) { + return { + groups: init, + items: init, + choices: init, + }; + }; + Store.prototype.resetStore = function () { + this._store = this.defaultState; + var changes = this.changeSet(true); + this._listeners.forEach(function (l) { return l(changes); }); + }; + Store.prototype.subscribe = function (onChange) { + this._listeners.push(onChange); }; - /** - * Dispatch event to store (wrapped Redux method) - */ Store.prototype.dispatch = function (action) { - this._store.dispatch(action); + var state = this._store; + var hasChanges = false; + var changes = this._outstandingChanges || this.changeSet(false); + Object.keys(reducers).forEach(function (key) { + var stateUpdate = reducers[key](state[key], action); + if (stateUpdate.update) { + hasChanges = true; + changes[key] = true; + state[key] = stateUpdate.state; + } + }); + if (hasChanges) { + if (this._txn) { + this._outstandingChanges = changes; + } + else { + this._listeners.forEach(function (l) { return l(changes); }); + } + } }; Store.prototype.withTxn = function (func) { - this._store.dispatch(setTxn(true)); + this._txn++; try { func(); } finally { - this._store.dispatch(setTxn(false)); + this._txn = Math.max(0, this._txn - 1); + if (!this._txn) { + var changeSet_1 = this._outstandingChanges; + if (changeSet_1) { + this._outstandingChanges = undefined; + this._listeners.forEach(function (l) { return l(changeSet_1); }); + } + } } }; Object.defineProperty(Store.prototype, "state", { /** - * Get store object (wrapping Redux method) + * Get store object */ get: function () { - return this._store.getState(); + return this._store; }, enumerable: false, configurable: true @@ -1636,10 +1276,10 @@ * Get active groups from store */ get: function () { - var _a = this, groups = _a.groups, choices = _a.choices; - return groups.filter(function (group) { + var _this = this; + return this.state.groups.filter(function (group) { var isActive = group.active && !group.disabled; - var hasActiveOptions = choices.some(function (choice) { return choice.active && !choice.disabled; }); + var hasActiveOptions = _this.state.choices.some(function (choice) { return choice.active && !choice.disabled; }); return isActive && hasActiveOptions; }, []); }, @@ -1647,7 +1287,7 @@ configurable: true }); Store.prototype.inTxn = function () { - return this.state.txn > 0; + return this._txn > 0; }; /** * Get single choice by it's ID @@ -2108,9 +1748,6 @@ } this.initialised = false; this._store = new Store(); - this._initialState = defaultState; - this._currentState = defaultState; - this._prevState = defaultState; this._currentValue = ''; this.config.searchEnabled = (!this._isTextElement && this.config.searchEnabled) || @@ -2193,8 +1830,7 @@ this._createTemplates(); this._createElements(); this._createStructure(); - this._store.subscribe(this._render); - this._render(); + this._initStore(); this._addEventListeners(); var shouldDisable = (this._isTextElement && !this.config.addItems) || this.passedElement.element.hasAttribute('disabled') || @@ -2218,6 +1854,7 @@ this.passedElement.reveal(); this.containerOuter.unwrap(this.passedElement.element); this.clearStore(); + this._store._listeners = []; this._stopSearch(); this._templates = templates; this.initialised = false; @@ -2623,7 +2260,7 @@ return this; }; Choices.prototype.clearStore = function () { - this._store.dispatch(clearAll()); + this._store.resetStore(); this._lastAddedChoiceId = 0; this._lastAddedGroupId = 0; // @todo integrate with Store @@ -2652,15 +2289,12 @@ } } }; - Choices.prototype._render = function () { + Choices.prototype._render = function (changes) { if (this._store.inTxn()) { return; } - this._currentState = this._store.state; - var shouldRenderItems = this._currentState.items !== this._prevState.items; - var stateChanged = this._currentState.choices !== this._prevState.choices || - this._currentState.groups !== this._prevState.groups || - shouldRenderItems; + var shouldRenderItems = changes === null || changes === void 0 ? void 0 : changes.items; + var stateChanged = (changes === null || changes === void 0 ? void 0 : changes.choices) || (changes === null || changes === void 0 ? void 0 : changes.groups) || shouldRenderItems; if (!stateChanged) { return; } @@ -2670,7 +2304,6 @@ if (shouldRenderItems) { this._renderItems(); } - this._prevState = this._currentState; }; Choices.prototype._renderChoices = function () { var _this = this; @@ -3889,7 +3522,6 @@ }); }; Choices.prototype._createStructure = function () { - var _this = this; // Hide original element this.passedElement.conceal(); // Wrap input in container preserving DOM ordering @@ -3917,6 +3549,10 @@ } this._highlightPosition = 0; this._isSearching = false; + }; + Choices.prototype._initStore = function () { + var _this = this; + this._store.subscribe(this._render); this._store.withTxn(function () { _this._addPredefinedChoices(_this._presetChoices, _this._isSelectOneElement && !_this._hasNonChoicePlaceholder, false); }); diff --git a/public/assets/scripts/choices.search-prefix.min.js b/public/assets/scripts/choices.search-prefix.min.js index 7f219bc2..2f73fae9 100644 --- a/public/assets/scripts/choices.search-prefix.min.js +++ b/public/assets/scripts/choices.search-prefix.min.js @@ -1,2 +1,2 @@ /*! choices.js v11.0.0-rc5 | © 2024 Josh Johnson | https://github.com/jshjohnson/Choices#readme */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).Choices=t()}(this,(function(){"use strict";var e=function(t,i){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},e(t,i)};function t(t,i){if("function"!=typeof i&&null!==i)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");function n(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(n.prototype=i.prototype,new n)}var i=function(){return i=Object.assign||function(e){for(var t,i=1,n=arguments.length;i/g,">").replace(/0?this.element.scrollTop+r-s:e.offsetTop;requestAnimationFrame((function(){i._animateScroll(a,t)}))}},e.prototype._scrollDown=function(e,t,i){var n=(i-e)/t,s=n>1?n:1;this.element.scrollTop=e+s},e.prototype._scrollUp=function(e,t,i){var n=(e-i)/t,s=n>1?n:1;this.element.scrollTop=e-s},e.prototype._animateScroll=function(e,t){var i=this,n=this.element.scrollTop,s=!1;t>0?(this._scrollDown(n,4,e),ne&&(s=!0)),s&&requestAnimationFrame((function(){i._animateScroll(e,t)}))},e}(),C=function(){function e(e){var t=e.element,i=e.classNames;this.element=t,this.classNames=i,this.isDisabled=!1}return Object.defineProperty(e.prototype,"isActive",{get:function(){return"active"===this.element.dataset.choice},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dir",{get:function(){return this.element.dir},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.element.value},set:function(e){this.element.setAttribute("value",e),this.element.value=e},enumerable:!1,configurable:!0}),e.prototype.conceal=function(){var e;(e=this.element.classList).add.apply(e,d(this.classNames.input)),this.element.hidden=!0,this.element.tabIndex=-1;var t=this.element.getAttribute("style");t&&this.element.setAttribute("data-choice-orig-style",t),this.element.setAttribute("data-choice","active")},e.prototype.reveal=function(){var e;(e=this.element.classList).remove.apply(e,d(this.classNames.input)),this.element.hidden=!1,this.element.removeAttribute("tabindex");var t=this.element.getAttribute("data-choice-orig-style");t?(this.element.removeAttribute("data-choice-orig-style"),this.element.setAttribute("style",t)):this.element.removeAttribute("style"),this.element.removeAttribute("data-choice"),this.element.value=this.element.value},e.prototype.enable=function(){this.element.removeAttribute("disabled"),this.element.disabled=!1,this.isDisabled=!1},e.prototype.disable=function(){this.element.setAttribute("disabled",""),this.element.disabled=!0,this.isDisabled=!0},e.prototype.triggerEvent=function(e,t){!function(e,t,i){void 0===i&&(i=null);var n=new CustomEvent(t,{detail:i,bubbles:!0,cancelable:!0});e.dispatchEvent(n)}(this.element,e,t||{})},e}(),w=function(e){function i(){return null!==e&&e.apply(this,arguments)||this}return t(i,e),i}(C),I=function(e,t){return void 0===t&&(t=!0),void 0===e?t:!!e},S=function(e){if("string"==typeof e&&(e=e.split(" ").filter((function(e){return 0!==e.length}))),Array.isArray(e)&&0!==e.length)return e},O=function(e,t){if("string"==typeof e)return O({value:e,label:e},!1);var i=e;if("choices"in i){if(!t)throw new TypeError("optGroup is not allowed");var n=i,s=n.choices.map((function(e){return O(e,!1)}));return{id:0,label:h(n.label)||n.value,active:0!==s.length,disabled:!!n.disabled,choices:s}}var o=i;return{id:0,groupId:0,score:0,rank:0,value:o.value,label:o.label||o.value,active:I(o.active),selected:I(o.selected,!1),disabled:I(o.disabled,!1),placeholder:I(o.placeholder,!1),highlighted:!1,labelClass:S(o.labelClass),labelDescription:o.labelDescription,customProperties:o.customProperties}},T=function(e){function i(t){var i=t.element,n=t.classNames,s=t.template,o=t.extractPlaceholder,r=e.call(this,{element:i,classNames:n})||this;return r.template=s,r.extractPlaceholder=o,r}return t(i,e),Object.defineProperty(i.prototype,"placeholderOption",{get:function(){return this.element.querySelector('option[value=""]')||this.element.querySelector("option[placeholder]")},enumerable:!1,configurable:!0}),i.prototype.addOptions=function(e){var t=this;e.forEach((function(e){var i=e;if(!i.element){var n=t.template(i);t.element.appendChild(n),i.element=n}}))},i.prototype.optionsAsChoices=function(){var e=this,t=[];return this.element.querySelectorAll(":scope > option, :scope > optgroup").forEach((function(i){!function(e){return"OPTION"===e.tagName}(i)?function(e){return"OPTGROUP"===e.tagName}(i)&&t.push(e._optgroupToChoice(i)):t.push(e._optionToChoice(i))})),t},i.prototype._optionToChoice=function(e){return{id:0,groupId:0,score:0,rank:0,value:e.value,label:e.innerHTML,element:e,active:!0,selected:this.extractPlaceholder?e.selected:e.hasAttribute("selected"),disabled:e.disabled,highlighted:!1,placeholder:this.extractPlaceholder&&(""===e.value||e.hasAttribute("placeholder")),labelClass:void 0!==e.dataset.labelClass?S(e.dataset.labelClass):void 0,labelDescription:void 0!==e.dataset.labelDescription?e.dataset.labelDescription:void 0,customProperties:f(e.dataset.customProperties)}},i.prototype._optgroupToChoice=function(e){var t=this,i=e.querySelectorAll("option"),n=Array.from(i).map((function(e){return t._optionToChoice(e)}));return{id:0,label:e.label||"",element:e,active:0!==n.length,disabled:e.disabled,choices:n}},i}(C),A={items:[],choices:[],silent:!1,renderChoiceLimit:-1,maxItemCount:-1,singleModeForMultiSelect:!1,addChoices:!1,addItems:!0,addItemFilter:function(e){return!!e&&""!==e},removeItems:!0,removeItemButton:!1,removeItemButtonAlignLeft:!1,editItems:!1,allowHTML:!1,allowHtmlUserInput:!1,duplicateItemsAllowed:!0,delimiter:",",paste:!0,searchEnabled:!0,searchChoices:!0,searchFloor:1,searchResultLimit:4,searchFields:["label","value"],position:"auto",resetScrollPosition:!0,shouldSort:!0,shouldSortItems:!1,sorter:function(e,t){var i=e.value,n=e.label,s=void 0===n?i:n,o=t.value,r=t.label,a=void 0===r?o:r;return h(s).localeCompare(h(a),[],{sensitivity:"base",ignorePunctuation:!0,numeric:!0})},shadowRoot:null,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 "'.concat(e,'"')},removeItemIconText:function(){return"Remove item"},removeItemLabelText:function(e){return"Remove item: ".concat(e)},maxItemText:function(e){return"Only ".concat(e," values can be added")},valueComparer:function(e,t){return e===t},fuseOptions:{includeScore:!0},labelId:"",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"],description:["choices__description"],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"],selectedState:["is-selected"],flippedState:["is-flipped"],loadingState:["is-loading"],addChoice:["choices__item","choices__item--selectable","add-choice"],noResults:["has-no-results"],noChoices:["has-no-choices"]},appendGroupInSearch:!1},L=["fuseOptions","classNames"];function x(e){return"Minified Redux error #"+e+"; visit https://redux.js.org/Errors?code="+e+" for the full message or use the non-minified dev environment for full errors. "}var N="function"==typeof Symbol&&Symbol.observable||"@@observable",D=function(){return Math.random().toString(36).substring(7).split("").join(".")},P={INIT:"@@redux/INIT"+D(),REPLACE:"@@redux/REPLACE"+D(),PROBE_UNKNOWN_ACTION:function(){return"@@redux/PROBE_UNKNOWN_ACTION"+D()}};function F(e,t,i){var n;if("function"==typeof t&&"function"==typeof i||"function"==typeof i&&"function"==typeof arguments[3])throw new Error(x(0));if("function"==typeof t&&void 0===i&&(i=t,t=void 0),void 0!==i){if("function"!=typeof i)throw new Error(x(1));return i(F)(e,t)}if("function"!=typeof e)throw new Error(x(2));var s=e,o=t,r=[],a=r,c=!1;function l(){a===r&&(a=r.slice())}function h(){if(c)throw new Error(x(3));return o}function u(e){if("function"!=typeof e)throw new Error(x(4));if(c)throw new Error(x(5));var t=!0;return l(),a.push(e),function(){if(t){if(c)throw new Error(x(6));t=!1,l();var i=a.indexOf(e);a.splice(i,1),r=null}}}function d(e){if(!function(e){if("object"!=typeof e||null===e)return!1;for(var t=e;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}(e))throw new Error(x(7));if(void 0===e.type)throw new Error(x(8));if(c)throw new Error(x(9));try{c=!0,o=s(o,e)}finally{c=!1}for(var t=r=a,i=0;i0},e.prototype.getChoiceById=function(e){return this.activeChoices.find((function(t){return t.id===e}))},e.prototype.getGroupById=function(e){return this.groups.find((function(t){return t.id===e}))},e}(),R=function(e,t){return e?function(e){if("string"==typeof e)return e;if("object"==typeof e){if("escaped"in e)return e.escaped;if("trusted"in e)return e.trusted}return""}(t):c(t)},V=function(e,t){if(t){var i=e.dataset;"string"==typeof t?i.customProperties=t:"object"!=typeof t||function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}(t)||(i.customProperties=JSON.stringify(t))}},K={containerOuter:function(e,t,i,n,s,o,r){var a=e.classNames.containerOuter,c=Object.assign(document.createElement("div"),{className:d(a).join(" ")});return c.dataset.type=o,t&&(c.dir=t),n&&(c.tabIndex=0),i&&(c.setAttribute("role",s?"combobox":"listbox"),s&&c.setAttribute("aria-autocomplete","list")),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),r&&c.setAttribute("aria-labelledby",r),c},containerInner:function(e){var t=e.classNames.containerInner;return Object.assign(document.createElement("div"),{className:d(t).join(" ")})},itemList:function(e,t){var i=e.classNames,n=i.list,s=i.listSingle,o=i.listItems;return Object.assign(document.createElement("div"),{className:"".concat(d(n).join(" ")," ").concat(t?d(s).join(" "):d(o).join(" "))})},placeholder:function(e,t){var i=e.allowHTML,n=e.classNames.placeholder;return Object.assign(document.createElement("div"),{className:d(n).join(" "),innerHTML:R(i,t)})},item:function(e,t,i){var n,s,o,r=e.allowHTML,a=e.removeItemButtonAlignLeft,l=e.classNames,h=l.item,u=l.button,p=l.highlightedState,f=l.itemSelectable,m=l.placeholder,v=t.id,g=t.value,_=t.label,y=t.labelClass,b=t.labelDescription,E=t.customProperties,C=t.active,w=t.disabled,I=t.highlighted,S=t.placeholder,O=Object.assign(document.createElement("div"),{className:d(h).join(" ")});if(y){var T=Object.assign(document.createElement("span"),{innerHTML:R(r,_),className:d(y).join(" ")});O.appendChild(T)}else O.innerHTML=R(r,_);if(Object.assign(O.dataset,{item:"",id:v,value:g}),y&&(O.dataset.labelClass=d(y).join(" ")),b&&(O.dataset.labelDescription=b),V(O,E),C&&O.setAttribute("aria-selected","true"),w&&O.setAttribute("aria-disabled","true"),S&&((n=O.classList).add.apply(n,d(m)),O.dataset.placeholder=""),(s=O.classList).add.apply(s,d(I?p:f)),i){w&&(o=O.classList).remove.apply(o,d(f)),O.dataset.deletable="";var A="function"==typeof this.config.removeItemIconText?this.config.removeItemIconText(c(g),g):this.config.removeItemIconText,L="function"==typeof this.config.removeItemLabelText?this.config.removeItemLabelText(c(g),g):this.config.removeItemLabelText,x=Object.assign(document.createElement("button"),{type:"button",className:d(u).join(" "),innerHTML:A});L&&x.setAttribute("aria-label",L),x.dataset.button="",a?O.insertAdjacentElement("afterbegin",x):O.appendChild(x)}return O},choiceList:function(e,t){var i=e.classNames.list,n=Object.assign(document.createElement("div"),{className:d(i).join(" ")});return t||n.setAttribute("aria-multiselectable","true"),n.setAttribute("role","listbox"),n},choiceGroup:function(e,t){var i=e.allowHTML,n=e.classNames,s=n.group,o=n.groupHeading,r=n.itemDisabled,a=t.id,c=t.label,l=t.disabled,h=Object.assign(document.createElement("div"),{className:"".concat(d(s).join(" ")," ").concat(l?d(r).join(" "):"")});return h.setAttribute("role","group"),Object.assign(h.dataset,{group:"",id:a,value:c}),l&&h.setAttribute("aria-disabled","true"),h.appendChild(Object.assign(document.createElement("div"),{className:d(o).join(" "),innerHTML:R(i,c)})),h},choice:function(e,t,i){var n,s,o,r,a,c=e.allowHTML,l=e.classNames,h=l.item,u=l.itemChoice,p=l.itemSelectable,f=l.selectedState,m=l.itemDisabled,v=l.description,g=l.placeholder,_=t.id,y=t.value,b=t.label,E=t.groupId,C=t.elementId,w=t.labelClass,I=t.labelDescription,S=t.disabled,O=t.selected,T=t.placeholder,A=Object.assign(document.createElement("div"),{id:C,className:"".concat(d(h).join(" ")," ").concat(d(u).join(" "))}),L=A;if(w){var x=Object.assign(document.createElement("span"),{innerHTML:R(c,b),className:d(w).join(" ")});L=x,A.appendChild(x)}else A.innerHTML=R(c,b);if(I){var N="".concat(C,"-description");L.setAttribute("aria-describedby",N);var D=Object.assign(document.createElement("span"),{innerHTML:R(c,I),id:N});(n=D.classList).add.apply(n,d(v)),A.appendChild(D)}return O&&(s=A.classList).add.apply(s,d(f)),T&&(o=A.classList).add.apply(o,d(g)),A.setAttribute("role",E&&E>0?"treeitem":"option"),Object.assign(A.dataset,{choice:"",id:_,value:y,selectText:i}),w&&(A.dataset.labelClass=d(w).join(" ")),I&&(A.dataset.labelDescription=I),S?((r=A.classList).add.apply(r,d(m)),A.dataset.choiceDisabled="",A.setAttribute("aria-disabled","true")):((a=A.classList).add.apply(a,d(p)),A.dataset.choiceSelectable=""),A},input:function(e,t){var i=e.classNames,n=i.input,s=i.inputCloned,o=Object.assign(document.createElement("input"),{type:"search",className:"".concat(d(n).join(" ")," ").concat(d(s).join(" ")),autocomplete:"off",autocapitalize:"off",spellcheck:!1});return o.setAttribute("role","textbox"),o.setAttribute("aria-autocomplete","list"),t&&o.setAttribute("aria-label",t),o},dropdown:function(e){var t,i,n=e.classNames,s=n.list,o=n.listDropdown,r=document.createElement("div");return(t=r.classList).add.apply(t,d(s)),(i=r.classList).add.apply(i,d(o)),r.setAttribute("aria-expanded","false"),r},notice:function(e,t,i){var s=e.allowHTML,o=e.classNames,r=o.item,a=o.itemChoice,c=o.addChoice,l=o.noResults,h=o.noChoices;void 0===i&&(i="");var u=n(n([],d(r),!0),d(a),!0);switch(i){case"add-choice":u.push.apply(u,d(c));break;case"no-results":u.push.apply(u,d(l));break;case"no-choices":u.push.apply(u,d(h))}var p=Object.assign(document.createElement("div"),{innerHTML:R(s,t),className:u.join(" ")});return"add-choice"===i&&(p.dataset.choiceSelectable="",p.dataset.choice=""),p},option:function(e){var t=e.label,i=e.value,n=e.labelClass,s=e.labelDescription,o=e.customProperties,r=e.active,a=e.disabled,c=h(t),l=new Option(c,i,!1,r);return n&&(l.dataset.labelClass=d(n).join(" ")),s&&(l.dataset.labelDescription=s),V(l,o),l.disabled=a,l}},B=function(){function e(e){this._haystack=[],this._fields=e.searchFields}return e.prototype.index=function(e){this._haystack=e},e.prototype.reset=function(){this._haystack=[]},e.prototype.isEmptyIndex=function(){return 0===this._haystack.length},e.prototype.search=function(e){var t=this._fields;if(!t||0===t.length||""===e)return[];var i=e.toLowerCase();return this._haystack.filter((function(e){return t.some((function(t){return t in e&&e[t].toLowerCase().startsWith(i)}))})).map((function(e,t){return{item:e,score:t,rank:t}}))},e}();var U="-ms-scroll-limit"in document.documentElement.style&&"-ms-ime-align"in document.documentElement.style,q={},G=function(e){if(e){var t=e.dataset.id;return t?parseInt(t,10):void 0}},W=function(){function e(t,n){void 0===t&&(t="[data-choice]"),void 0===n&&(n={});var s=this;this.initialisedOK=void 0,this._hasNonChoicePlaceholder=!1,this._lastAddedChoiceId=0,this._lastAddedGroupId=0,this.config=i(i(i({},e.defaults.allOptions),e.defaults.options),n),L.forEach((function(t){s.config[t]=i(i(i({},e.defaults.allOptions[t]),e.defaults.options[t]),n[t])})),this.config.silent||this._validateConfig();var o=this.config.shadowRoot||document.documentElement,r="string"==typeof t?o.querySelector(t):t;if(!r||"object"!=typeof r||"INPUT"!==r.tagName&&!function(e){return"SELECT"===e.tagName}(r)){if(!r&&"string"==typeof t)throw TypeError("Selector ".concat(t," failed to find an element"));throw TypeError("Expected one of the following types text|select-one|select-multiple")}if(this._elementType=r.type,this._isTextElement=this._elementType===v,(this._isTextElement||1!==this.config.maxItemCount)&&(this.config.singleModeForMultiSelect=!1),this.config.singleModeForMultiSelect&&(this._elementType=_),this._isSelectOneElement=this._elementType===g,this._isSelectMultipleElement=this._elementType===_,this._isSelectElement=this._isSelectOneElement||this._isSelectMultipleElement,this._canAddUserChoices=this._isTextElement&&this.config.addItems||this._isSelectElement&&this.config.addChoices,["auto","always"].includes("".concat(this.config.renderSelectedChoices))||(this.config.renderSelectedChoices="auto"),this.config.placeholder&&(this.config.placeholderValue?this._hasNonChoicePlaceholder=!0:r.dataset.placeholder&&(this._hasNonChoicePlaceholder=!0,this.config.placeholderValue=r.dataset.placeholder)),n.addItemFilter&&"function"!=typeof n.addItemFilter){var c=n.addItemFilter instanceof RegExp?n.addItemFilter:new RegExp(n.addItemFilter);this.config.addItemFilter=c.test.bind(c)}if(this._isTextElement)this.passedElement=new w({element:r,classNames:this.config.classNames});else{var l=r;this.passedElement=new T({element:l,classNames:this.config.classNames,template:function(e){return s._templates.option(e)},extractPlaceholder:this.config.placeholder&&!this._hasNonChoicePlaceholder})}if(this.initialised=!1,this._store=new k,this._initialState=j,this._currentState=j,this._prevState=j,this._currentValue="",this.config.searchEnabled=!this._isTextElement&&this.config.searchEnabled||this._elementType===_,this._canSearch=this.config.searchEnabled,this._isScrollingOnIe=!1,this._highlightPosition=0,this._wasTap=!0,this._placeholderValue=this._generatePlaceholderValue(),this._baseId=function(e,t){var i=e.id||e.name&&"".concat(e.name,"-").concat(a(2))||a(4);return i=i.replace(/(:|\.|\[|\]|,)/g,""),"".concat(t,"-").concat(i)}(this.passedElement.element,"choices-"),this._direction=this.passedElement.dir,!this._direction){var h=window.getComputedStyle(this.passedElement.element).direction;h!==window.getComputedStyle(document.documentElement).direction&&(this._direction=h)}if(this._idNames={itemChoice:"item-choice"},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._onInput=this._onInput.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._onSelectKey=this._onSelectKey.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.passedElement.isActive)return this.config.silent||console.warn("Trying to initialise Choices on element already initialised",{element:t}),this.initialised=!0,void(this.initialisedOK=!1);this.init(),this._initialItems=this._store.items.map((function(e){return e.value}))}return Object.defineProperty(e,"defaults",{get:function(){return Object.preventExtensions({get options(){return q},get allOptions(){return A},get templates(){return K}})},enumerable:!1,configurable:!0}),e.prototype.init=function(){if(!this.initialised&&void 0===this.initialisedOK){var e;this._searcher=(e=this.config,new B(e)),this._loadChoices(),this._createTemplates(),this._createElements(),this._createStructure(),this._store.subscribe(this._render),this._render(),this._addEventListeners(),(this._isTextElement&&!this.config.addItems||this.passedElement.element.hasAttribute("disabled")||!!this.passedElement.element.closest("fieldset:disabled"))&&this.disable(),this.initialised=!0,this.initialisedOK=!0;var t=this.config.callbackOnInit;t&&"function"==typeof t&&t.call(this)}},e.prototype.destroy=function(){this.initialised&&(this._removeEventListeners(),this.passedElement.reveal(),this.containerOuter.unwrap(this.passedElement.element),this.clearStore(),this._stopSearch(),this._templates=K,this.initialised=!1,this.initialisedOK=void 0)},e.prototype.enable=function(){return this.passedElement.isDisabled&&this.passedElement.enable(),this.containerOuter.isDisabled&&(this._addEventListeners(),this.input.enable(),this.containerOuter.enable()),this},e.prototype.disable=function(){return this.passedElement.isDisabled||this.passedElement.disable(),this.containerOuter.isDisabled||(this._removeEventListeners(),this.input.disable(),this.containerOuter.disable()),this},e.prototype.highlightItem=function(e,t){if(void 0===t&&(t=!0),!e||!e.id)return this;var i=this._store.choices.find((function(t){return t.id===e.id}));return!i||i.highlighted||(this._store.dispatch(o(i,!0)),t&&this.passedElement.triggerEvent("highlightItem",this._getChoiceForOutput(i))),this},e.prototype.unhighlightItem=function(e,t){if(void 0===t&&(t=!0),!e||!e.id)return this;var i=this._store.choices.find((function(t){return t.id===e.id}));return i&&i.highlighted?(this._store.dispatch(o(i,!1)),t&&this.passedElement.triggerEvent("highlightItem",this._getChoiceForOutput(i)),this):this},e.prototype.highlightAll=function(){var e=this;return this._store.withTxn((function(){e._store.items.forEach((function(t){return e.highlightItem(t)}))})),this},e.prototype.unhighlightAll=function(){var e=this;return this._store.withTxn((function(){e._store.items.forEach((function(t){return e.unhighlightItem(t)}))})),this},e.prototype.removeActiveItemsByValue=function(e){var t=this;return this._store.withTxn((function(){t._store.items.filter((function(t){return t.value===e})).forEach((function(e){return t._removeItem(e)}))})),this},e.prototype.removeActiveItems=function(e){var t=this;return this._store.withTxn((function(){t._store.items.filter((function(t){return t.id!==e})).forEach((function(e){return t._removeItem(e)}))})),this},e.prototype.removeHighlightedItems=function(e){var t=this;return void 0===e&&(e=!1),this._store.withTxn((function(){t._store.highlightedActiveItems.forEach((function(i){t._removeItem(i),e&&t._triggerChange(i.value)}))})),this},e.prototype.showDropdown=function(e){var t=this;return this.dropdown.isActive||requestAnimationFrame((function(){t.dropdown.show(),t.containerOuter.open(t.dropdown.distanceFromTopWindow),!e&&t._canSearch&&t.input.focus(),t.passedElement.triggerEvent("showDropdown")})),this},e.prototype.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("hideDropdown")})),this):this},e.prototype.getValue=function(e){var t=this;void 0===e&&(e=!1);var i=this._store.items.reduce((function(i,n){var s=e?n.value:t._getChoiceForOutput(n);return i.push(s),i}),[]);return this._isSelectOneElement||this.config.singleModeForMultiSelect?i[0]:i},e.prototype.setValue=function(e){var t=this;return this.initialisedOK?(this._store.withTxn((function(){e.forEach((function(e){e&&t._addChoice(O(e,!1))}))})),this._searcher.reset(),this):(this._warnChoicesInitFailed("setValue"),this)},e.prototype.setChoiceByValue=function(e){var t=this;return this.initialisedOK?(this._isTextElement||(this._store.withTxn((function(){(Array.isArray(e)?e:[e]).forEach((function(e){return t._findAndSelectChoiceByValue(e)}))})),this._searcher.reset()),this):(this._warnChoicesInitFailed("setChoiceByValue"),this)},e.prototype.setChoices=function(e,t,n,s){var o=this;if(void 0===e&&(e=[]),void 0===t&&(t="value"),void 0===n&&(n="label"),void 0===s&&(s=!1),!this.initialisedOK)return this._warnChoicesInitFailed("setChoices"),this;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(s&&this.clearChoices(),"function"==typeof e){var r=e(this);if("function"==typeof Promise&&r instanceof Promise)return new Promise((function(e){return requestAnimationFrame(e)})).then((function(){return o._handleLoadingState(!0)})).then((function(){return r})).then((function(e){return o.setChoices(e,t,n,s)})).catch((function(e){o.config.silent||console.error(e)})).then((function(){return o._handleLoadingState(!1)})).then((function(){return o}));if(!Array.isArray(r))throw new TypeError(".setChoices first argument function must return either array of choices or Promise, got: ".concat(typeof r));return this.setChoices(r,t,n,!1)}if(!Array.isArray(e))throw new TypeError(".setChoices must be called either with array of choices with a function resulting into Promise of array of choices");return this.containerOuter.removeLoadingState(),this._store.withTxn((function(){var s="value"===t,r="label"===n;e.forEach((function(e){if("choices"in e){var a=e;r||(a=i(i({},a),{label:a[n]})),o._addGroup(O(a,!0))}else{var c=e;r&&s||(c=i(i({},c),{value:c[t],label:c[n]})),o._addChoice(O(c,!1))}}))})),this._searcher.reset(),this},e.prototype.refresh=function(e,t,i){var n=this;return void 0===e&&(e=!1),void 0===t&&(t=!1),void 0===i&&(i=!1),this._isSelectElement?(this._store.withTxn((function(){var s=n.passedElement.optionsAsChoices(),o=n._store.items,r={};i||o.forEach((function(e){e.id&&e.active&&e.selected&&!e.disabled&&(r[e.value]=!0)})),s.forEach((function(e){if(!("choices"in e)){var t=e;i?t.selected=!1:r[t.value]&&(t.selected=!0)}})),n.clearStore(),n._addPredefinedChoices(s,t,e),n._isSearching&&n._searchChoices(n.input.value)})),this):(this.config.silent||console.warn("refresh method can only be used on choices backed by a element"),this)},e.prototype.removeChoice=function(e){var t=this._store.choices.find((function(t){return t.value===e}));return t?(this._store.dispatch(function(e){return{type:"REMOVE_CHOICE",choice:e}}(t)),this._searcher.reset(),t.selected&&this.passedElement.triggerEvent("removeItem",this._getChoiceForOutput(t)),this):this},e.prototype.clearChoices=function(){return this.passedElement.element.innerHTML="",this._store.dispatch({type:"CLEAR_CHOICES"}),this._searcher.reset(),this},e.prototype.clearStore=function(){return this._store.resetStore(),this._lastAddedChoiceId=0,this._lastAddedGroupId=0,this._searcher.reset(),this},e.prototype.clearInput=function(){var e=!this._isSelectOneElement;return this.input.clear(e),this._isSearching&&this._stopSearch(),this},e.prototype._validateConfig=function(){var e,t,i,n,s=(e=this.config,t=T,i=Object.keys(e).sort(),n=Object.keys(t).sort(),i.filter((function(e){return n.indexOf(e)<0})));s.length&&console.warn("Unknown config option(s) passed",s.join(", ")),this.config.allowHTML&&this.config.allowHtmlUserInput&&(this.config.addItems&&console.warn("Warning: allowHTML/allowHtmlUserInput/addItems all being true is strongly not recommended and may lead to XSS attacks"),this.config.addChoices&&console.warn("Warning: allowHTML/allowHtmlUserInput/addChoices all being true is strongly not recommended and may lead to XSS attacks"))},e.prototype._render=function(e){if(!this._store.inTxn()){var t=null==e?void 0:e.items;((null==e?void 0:e.choices)||(null==e?void 0:e.groups)||t)&&(this._isSelectElement&&this._renderChoices(),t&&this._renderItems())}},e.prototype._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){if(!this._hasNonChoicePlaceholder){var o=n.filter((function(e){return e.placeholder&&-1===e.groupId}));o.length>=1&&(s=this._createChoicesFragment(o,s))}s=this._createGroupsFragment(i,n,s)}else n.length>=1&&(s=this._createChoicesFragment(n,s));var r=this.input.value,a=this._canAddItem(this._store.items,r);if(s.childNodes&&s.childNodes.length>0){var c=!a.response;if(a.response&&(this.choiceList.append(s),this._highlightChoice(),this._canAddUserChoices&&r&&a.notice&&(c=!n.find((function(t){return e.config.valueComparer(t.value,r)})))),c){var l=this._templates.notice(this.config,a.notice,this._canAddUserChoices?"add-choice":"");this.choiceList.prepend(l)}}else{var h=void 0;if(a.response&&this._canAddUserChoices&&r)h=this._templates.notice(this.config,a.notice,"add-choice");else if(this._isSearching){l="function"==typeof this.config.noResultsText?this.config.noResultsText():this.config.noResultsText;h=this._templates.notice(this.config,l,"no-results")}else{l="function"==typeof this.config.noChoicesText?this.config.noChoicesText():this.config.noChoicesText;h=this._templates.notice(this.config,l,"no-choices")}this.choiceList.append(h)}},e.prototype._renderItems=function(){var e=this._store.items||[];this.itemList.clear();var t=this._createItemsFragment(e);t.childNodes&&this.itemList.append(t)},e.prototype._createGroupsFragment=function(e,t,i){var n=this;void 0===i&&(i=document.createDocumentFragment());this.config.shouldSort&&e.sort(this.config.sorter);var s=t.filter((function(e){return 0===e.groupId}));return s.length>0&&this._createChoicesFragment(s,i,!1),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 o=n._templates.choiceGroup(n.config,e);i.appendChild(o),n._createChoicesFragment(s,i,!0)}})),i},e.prototype._createChoicesFragment=function(e,t,i){var s=this;void 0===t&&(t=document.createDocumentFragment()),void 0===i&&(i=!1);var o=this.config,r=o.renderSelectedChoices,a=o.searchResultLimit,c=o.renderChoiceLimit,l=[],u=this.config.appendGroupInSearch&&this._isSearching;u&&this._store.groups.forEach((function(e){l[e.id]=e.label}));var d=function(e){if("auto"!==r||(s._isSelectOneElement||!e.selected)){var i=s._templates.choice(s.config,e,s.config.itemSelectText);if(u&&e.groupId>0){var n=l[e.groupId];n&&(i.innerHTML+=" (".concat(n,")"))}t.appendChild(i)}},p=e;if("auto"!==r||this._isSelectOneElement||(p=e.filter((function(e){return!e.selected}))),this._isSelectElement){var m=e.filter((function(e){return!e.element}));0!==m.length&&this.passedElement.addOptions(m)}var f=[],v=[];this._hasNonChoicePlaceholder?v=p:p.forEach((function(e){e.placeholder?f.push(e):v.push(e)})),this._isSearching?v.sort(h):this.config.shouldSort&&v.sort(this.config.sorter);var g=p.length,_=this._isSelectOneElement&&0!==f.length?n(n([],f,!0),v,!0):v;this._isSearching?g=a:c&&c>0&&!i&&(g=c);for(var y=0;y0?this._store.getGroupById(e.groupId):null;return{id:e.id,highlighted:e.highlighted,labelClass:e.labelClass,labelDescription:e.labelDescription,customProperties:e.customProperties,disabled:e.disabled,active:e.active,label:e.label,placeholder:e.placeholder,value:e.value,groupValue:i&&i.label?i.label:void 0,element:e.element,keyCode:t}}},e.prototype._triggerChange=function(e){null!=e&&this.passedElement.triggerEvent("change",{value:e})},e.prototype._handleButtonAction=function(e,t){if(0!==e.length&&this.config.removeItems&&this.config.removeItemButton){var i=t&&H(t.parentNode),n=i&&e.find((function(e){return e.id===i}));if(n&&(this._removeItem(n),this._triggerChange(n.value),this._isSelectOneElement&&!this._hasNonChoicePlaceholder)){var s=this._store.choices.reverse().find((function(e){return!e.disabled&&e.placeholder}));s&&(this._addItem(s),s.value&&this._triggerChange(s.value))}}},e.prototype._handleItemAction=function(e,t,i){var n=this;if(void 0===i&&(i=!1),0!==e.length&&this.config.removeItems&&!this._isSelectOneElement){var s=H(t);s&&(e.forEach((function(e){e.id!==s||e.highlighted?!i&&e.highlighted&&n.unhighlightItem(e):n.highlightItem(e)})),this.input.focus())}},e.prototype._handleChoiceAction=function(e,t,i){var n=this,s=H(t),o=s&&this._store.getChoiceById(s);if(!o)return!1;var r=this.dropdown.isActive,a=!1;return this._store.withTxn((function(){if(!o.selected&&!o.disabled&&n._canAddItem(e,o.value).response){if(n.config.singleModeForMultiSelect&&0!==e.length){var t=e[e.length-1];n._removeItem(t)}n.passedElement.triggerEvent("choice",n._getChoiceForOutput(o,i)),n._addItem(o),n.clearInput(),a=!0}})),!!a&&(this._triggerChange(o.value),r&&(this.config.singleModeForMultiSelect||this._isSelectOneElement)&&(this.hideDropdown(!0),this.containerOuter.focus()),!0)},e.prototype._handleBackspace=function(e){if(this.config.removeItems&&0!==e.length){var t=e[e.length-1],i=e.some((function(e){return e.highlighted}));this.config.editItems&&!i&&t?(this.input.value=t.value,this.input.setWidth(),this._removeItem(t),this._triggerChange(t.value)):(i||this.highlightItem(t,!1),this.removeHighlightedItems(!0))}},e.prototype._loadChoices=function(){var e;if(this._isTextElement){this._presetChoices=this.config.items.map((function(e){return w(e,!1)}));var t=this.passedElement.value;if(t){var i=t.split(this.config.delimiter).map((function(e){return w(e,!1)}));this._presetChoices=this._presetChoices.concat(i)}this._presetChoices.forEach((function(e){e.selected=!0}))}else if(this._isSelectElement){this._presetChoices=this.config.choices.map((function(e){return w(e,!0)}));var n=this.passedElement.optionsAsChoices();n&&(e=this._presetChoices).push.apply(e,n)}},e.prototype._handleLoadingState=function(e){void 0===e&&(e=!0);var t=this.itemList.element.querySelector(d(this.config.classNames.placeholder));e?(this.disable(),this.containerOuter.addLoadingState(),this._isSelectOneElement?t?t.innerHTML=this.config.loadingText:(t=this._templates.placeholder(this.config,this.config.loadingText))&&this.itemList.append(t):this.input.placeholder=this.config.loadingText):(this.enable(),this.containerOuter.removeLoadingState(),this._isSelectOneElement?t&&(t.innerHTML=this._placeholderValue||""):this.input.placeholder=this._placeholderValue||"")},e.prototype._handleSearch=function(e){if(this.input.isFocussed){var t=this._store.choices,i=this.config,n=i.searchFloor,s=i.searchChoices,o=t.some((function(e){return!e.active}));if(null!=e&&e.length>=n){var r=s?this._searchChoices(e):0;null!==r&&this.passedElement.triggerEvent("search",{value:e,resultCount:r})}else o&&this._stopSearch()}},e.prototype._canAddItem=function(e,t){var i=this,n=!0,s="";(this.config.maxItemCount>0&&this.config.maxItemCount<=e.length&&(this.config.singleModeForMultiSelect||(n=!1,s="function"==typeof this.config.maxItemText?this.config.maxItemText(this.config.maxItemCount):this.config.maxItemText)),n&&this._canAddUserChoices&&""!==t&&"function"==typeof this.config.addItemFilter&&!this.config.addItemFilter(t)&&(n=!1,s="function"==typeof this.config.customAddItemText?this.config.customAddItemText(a(t),t):this.config.customAddItemText),!n||""===t||!this._isSelectElement&&this.config.duplicateItemsAllowed)||this._store.items.find((function(e){return i.config.valueComparer(e.value,t)}))&&(n=!1,s="function"==typeof this.config.uniqueItemText?this.config.uniqueItemText(a(t),t):this.config.uniqueItemText);return n&&(s="function"==typeof this.config.addItemText?this.config.addItemText(a(t),t):this.config.addItemText),{response:n,notice:{trusted:s}}},e.prototype._searchChoices=function(e){var t=e.trim().replace(/\s{2,}/," ");if(0===t.length||t===this._currentValue)return null;var i=this._searcher;i.isEmptyIndex()&&i.index(this._store.searchableChoices);var n=i.search(t);return this._currentValue=t,this._highlightPosition=0,this._isSearching=!0,this._store.dispatch(function(e){return{type:"FILTER_CHOICES",results:e}}(n)),n.length},e.prototype._stopSearch=function(){var e=this._isSearching;this._currentValue="",this._isSearching=!1,e&&this._store.dispatch({type:"ACTIVATE_CHOICES",active:!0})},e.prototype._addEventListeners=function(){var e=this.config.shadowRoot||document.documentElement;e.addEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.addEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.addEventListener("mousedown",this._onMouseDown,!0),e.addEventListener("click",this._onClick,{passive:!0}),e.addEventListener("touchmove",this._onTouchMove,{passive:!0}),this.dropdown.element.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("input",this._onInput,{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()},e.prototype._removeEventListeners=function(){var e=this.config.shadowRoot||document.documentElement;e.removeEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.removeEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.removeEventListener("mousedown",this._onMouseDown,!0),e.removeEventListener("click",this._onClick),e.removeEventListener("touchmove",this._onTouchMove),this.dropdown.element.removeEventListener("mouseover",this._onMouseOver),this._isSelectOneElement&&(this.containerOuter.element.removeEventListener("focus",this._onFocus),this.containerOuter.element.removeEventListener("blur",this._onBlur)),this.input.element.removeEventListener("keyup",this._onKeyUp),this.input.element.removeEventListener("input",this._onInput),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()},e.prototype._onKeyDown=function(e){var t=e.keyCode,i=this._store.items,n=this.input.isFocussed,s=this.dropdown.isActive,o=this.itemList.hasChildren(),r=1===e.key.length||2===e.key.length&&e.key.charCodeAt(0)>=55296||"Unidentified"===e.key;switch(this._isTextElement||s||(this.showDropdown(),!this.input.isFocussed&&r&&(this.input.value+=e.key)),t){case 65:return this._onSelectKey(e,o);case 13:return this._onEnterKey(e,i,s);case 27:return this._onEscapeKey(e,s);case 38:case 33:case 40:case 34:return this._onDirectionKey(e,s);case 8:case 46:return this._onDeleteKey(e,i,n)}},e.prototype._onKeyUp=function(){this._canSearch=this.config.searchEnabled},e.prototype._onInput=function(){var e=this.input.value;if(e){if(this._isTextElement){var t=this._canAddItem(this._store.items,e);t.notice&&(this._displayAddItemNotice(t),this.showDropdown(!0))}if(this._canSearch){this._handleSearch(e);var i=this._canAddItem(this._store.items,e);i.response||this._displayAddItemNotice(i),this._canAddUserChoices&&(this._highlightPosition=0,this._highlightChoice())}}else this._isTextElement?this.hideDropdown(!0):this._stopSearch()},e.prototype._displayAddItemNotice=function(e){var t=this._templates.notice(this.config,e.notice,"add-choice"),i="".concat(d(this.config.classNames.addChoice),"[data-choice-selectable]"),n=this.choiceList.element.querySelector(i);n?n.outerHTML=t.outerHTML:this.choiceList.prepend(t)},e.prototype._onSelectKey=function(e,t){var i=e.ctrlKey,n=e.metaKey;(i||n)&&t&&(this._canSearch=!1,this.config.removeItems&&!this.input.value&&this.input.element===document.activeElement&&this.highlightAll())},e.prototype._onEnterKey=function(e,t,i){var n=this,s=this.input.value,o=e.target;if(o&&o.hasAttribute("data-button"))return e.preventDefault(),void this._handleButtonAction(t,o);if(!i&&this._isSelectOneElement)return e.preventDefault(),void this.showDropdown();if(i){var r=this.dropdown.element.querySelector(d(this.config.classNames.highlightedState));if(r&&this._handleChoiceAction(t,r,13))return e.preventDefault(),void this.unhighlightAll();s||this.hideDropdown(!0)}o&&s&&this._canAddUserChoices&&(this._canAddItem(t,s).response&&(this._store.withTxn((function(){if((n._isSelectOneElement||n.config.singleModeForMultiSelect)&&0!==t.length){var e=t[t.length-1];n._removeItem(e)}var i=!0;if(!n._isSelectElement&&n.config.duplicateItemsAllowed||(i=!n._findAndSelectChoiceByValue(s)),i){var o=a(s),r=n.config.allowHtmlUserInput||o===s?s:{escaped:o,raw:s};n._addChoice(w({value:r,label:r,selected:!0},!1))}n.clearInput(),n.unhighlightAll(),n._triggerChange(s)})),(this._isTextElement||this._isSelectOneElement)&&this.hideDropdown(!0)))},e.prototype._onEscapeKey=function(e,t){t&&(e.stopPropagation(),this.hideDropdown(!0),this.containerOuter.focus())},e.prototype._onDirectionKey=function(e,t){var i,n,s,o=e.keyCode,r=e.metaKey;if(t||this._isSelectOneElement){this.showDropdown(),this._canSearch=!1;var a=40===o||34===o?1:-1,c="[data-choice-selectable]",l=void 0;if(r||34===o||33===o)l=a>0?this.dropdown.element.querySelector("".concat(c,":last-of-type")):this.dropdown.element.querySelector(c);else{var h=this.dropdown.element.querySelector(d(this.config.classNames.highlightedState));l=h?function(e,t,i){void 0===i&&(i=1);for(var n="".concat(i>0?"next":"previous","ElementSibling"),s=e[n];s;){if(s.matches(t))return s;s=s[n]}return s}(h,c,a):this.dropdown.element.querySelector(c)}l&&(i=l,n=this.choiceList.element,void 0===(s=a)&&(s=1),i&&(s>0?n.scrollTop+n.offsetHeight>=i.offsetTop+i.offsetHeight:i.offsetTop>=n.scrollTop)||this.choiceList.scrollToChildElement(l,a),this._highlightChoice(l)),e.preventDefault()}},e.prototype._onDeleteKey=function(e,t,i){var n=e.target;this._isSelectOneElement||n.value||!i||(this._handleBackspace(t),e.preventDefault())},e.prototype._onTouchMove=function(){this._wasTap&&(this._wasTap=!1)},e.prototype._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},e.prototype._onMouseDown=function(e){var t=e.target;if(t instanceof HTMLElement){if(M&&this.choiceList.element.contains(t)){var i=this.choiceList.element.firstElementChild;this._isScrollingOnIe="ltr"===this._direction?e.offsetX>=i.offsetWidth:e.offsetX0&&this.unhighlightAll(),this.containerOuter.removeFocusState(),this.hideDropdown(!0))},e.prototype._onFocus=function(e){var t,i=this,n=e.target;n&&this.containerOuter.element.contains(n)&&((t={})[f]=function(){n===i.input.element&&i.containerOuter.addFocusState()},t[v]=function(){i.containerOuter.addFocusState(),n===i.input.element&&i.showDropdown(!0)},t[g]=function(){n===i.input.element&&(i.showDropdown(!0),i.containerOuter.addFocusState())},t)[this._elementType]()},e.prototype._onBlur=function(e){var t,i=this,n=e.target;if(n&&this.containerOuter.element.contains(n)&&!this._isScrollingOnIe){var s=this._store.activeChoices.some((function(e){return e.highlighted}));((t={})[f]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),s&&i.unhighlightAll(),i.hideDropdown(!0))},t[v]=function(){i.containerOuter.removeFocusState(),(n===i.input.element||n===i.containerOuter.element&&!i._canSearch)&&i.hideDropdown(!0)},t[g]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),i.hideDropdown(!0),s&&i.unhighlightAll())},t)[this._elementType]()}else this._isScrollingOnIe=!1,this.input.element.focus()},e.prototype._onFormReset=function(){var e=this;this._store.withTxn((function(){e.clearInput(),e.hideDropdown(),e.refresh(!1,!1,!0),0!==e._initialItems.length&&e.setChoiceByValue(e._initialItems)}))},e.prototype._highlightChoice=function(e){var t,i=this;void 0===e&&(e=null);var n=Array.from(this.dropdown.element.querySelectorAll("[data-choice-selectable]"));if(n.length){var s=e;Array.from(this.dropdown.element.querySelectorAll(d(this.config.classNames.highlightedState))).forEach((function(e){var t;(t=e.classList).remove.apply(t,u(i.config.classNames.highlightedState)),e.setAttribute("aria-selected","false")})),s?this._highlightPosition=n.indexOf(s):(s=n.length>this._highlightPosition?n[this._highlightPosition]:n[n.length-1])||(s=n[0]),(t=s.classList).add.apply(t,u(this.config.classNames.highlightedState)),s.setAttribute("aria-selected","true"),this.passedElement.triggerEvent("highlightChoice",{el:s}),this.dropdown.isActive&&(this.input.setActiveDescendant(s.id),this.containerOuter.setActiveDescendant(s.id))}},e.prototype._addItem=function(e,t){void 0===t&&(t=!0);var i=e.id;if(0===i)throw new TypeError("item.id must be set before _addItem is called for a choice/item");this._store.dispatch(function(e){return{type:"ADD_ITEM",item:e}}(e)),this._isSelectOneElement&&this.removeActiveItems(i),t&&this.passedElement.triggerEvent("addItem",this._getChoiceForOutput(e))},e.prototype._removeItem=function(e){e.id&&(this._store.dispatch(function(e){return{type:"REMOVE_ITEM",item:e}}(e)),this.passedElement.triggerEvent("removeItem",this._getChoiceForOutput(e)))},e.prototype._addChoice=function(e,t){if(void 0===t&&(t=!0),0!==e.id)throw new TypeError("Can not re-add a choice which has already been added");var i=e;this._lastAddedChoiceId++,i.id=this._lastAddedChoiceId,i.elementId="".concat(this._baseId,"-").concat(this._idNames.itemChoice,"-").concat(i.id),this.config.prependValue&&(i.value=this.config.prependValue+i.value),this.config.appendValue&&(i.value+=this.config.appendValue.toString()),(this.config.prependValue||this.config.appendValue)&&i.element&&(i.element.value=i.value),this._store.dispatch(function(e){return{type:"ADD_CHOICE",choice:e}}(e)),e.selected&&this._addItem(e,t)},e.prototype._addGroup=function(e,t){var i=this;if(void 0===t&&(t=!0),0!==e.id)throw new TypeError("Can not re-add a group which has already been added");if(this._store.dispatch(function(e){return{type:"ADD_GROUP",group:e}}(e)),e.choices){var n=e;this._lastAddedGroupId++,n.id=this._lastAddedGroupId;var s=e.id,o=e.choices;n.choices=[],o.forEach((function(n){var o=n;o.groupId=s,e.disabled&&(o.disabled=!0),i._addChoice(o,t)}))}},e.prototype._createTemplates=function(){var e=this,t=this.config.callbackOnCreateTemplates,i={};t&&"function"==typeof t&&(i=t.call(this,c,D));var n={};Object.keys(F).forEach((function(t){n[t]=t in i?i[t].bind(e):F[t].bind(e)})),this._templates=n},e.prototype._createElements=function(){this.containerOuter=new _({element:this._templates.containerOuter(this.config,this._direction,this._isSelectElement,this._isSelectOneElement,this.config.searchEnabled,this._elementType,this.config.labelId),classNames:this.config.classNames,type:this._elementType,position:this.config.position}),this.containerInner=new _({element:this._templates.containerInner(this.config),classNames:this.config.classNames,type:this._elementType,position:this.config.position}),this.input=new y({element:this._templates.input(this.config,this._placeholderValue),classNames:this.config.classNames,type:this._elementType,preventPaste:!this.config.paste}),this.choiceList=new b({element:this._templates.choiceList(this.config,this._isSelectOneElement)}),this.itemList=new b({element:this._templates.itemList(this.config,this._isSelectOneElement)}),this.dropdown=new m({element:this._templates.dropdown(this.config),classNames:this.config.classNames,type:this._elementType})},e.prototype._createStructure=function(){this.passedElement.conceal(),this.containerInner.wrap(this.passedElement.element),this.containerOuter.wrap(this.containerInner.element),this._isSelectOneElement?this.input.placeholder=this.config.searchPlaceholderValue||"":(this._placeholderValue&&(this.input.placeholder=this._placeholderValue),this.input.setWidth()),this.containerOuter.element.appendChild(this.containerInner.element),this.containerOuter.element.appendChild(this.dropdown.element),this.containerInner.element.appendChild(this.itemList.element),this.dropdown.element.appendChild(this.choiceList.element),this._isSelectOneElement?this.config.searchEnabled&&this.dropdown.element.insertBefore(this.input.element,this.dropdown.element.firstChild):this.containerInner.element.appendChild(this.input.element),this._highlightPosition=0,this._isSearching=!1},e.prototype._initStore=function(){var e=this;this._store.subscribe(this._render),this._store.withTxn((function(){e._addPredefinedChoices(e._presetChoices,e._isSelectOneElement&&!e._hasNonChoicePlaceholder,!1)}))},e.prototype._addPredefinedChoices=function(e,t,i){var n=this;if(void 0===t&&(t=!1),void 0===i&&(i=!0),this.config.shouldSort&&e.sort(this.config.sorter),t){var s=-1===e.findIndex((function(e){return!!e.selected}));if(s){var o=e.findIndex((function(e){return void 0===e.disabled||!e.disabled}));if(-1!==o)e[o].selected=!0}}e.forEach((function(e){"choices"in e?n._isSelectElement&&n._addGroup(e,i):n._addChoice(e,i)}))},e.prototype._findAndSelectChoiceByValue=function(e){var t=this,i=this._store.choices.find((function(i){return t.config.valueComparer(i.value,e)}));return!(!i||i.selected)&&(this._addItem(i),!0)},e.prototype._generatePlaceholderValue=function(){if(!this.config.placeholder)return null;if(this._hasNonChoicePlaceholder)return this.config.placeholderValue;if(this._isSelectElement){var e=this.passedElement.placeholderOption;return e?e.text:null}return null},e.prototype._warnChoicesInitFailed=function(e){if(!this.config.silent){if(!this.initialised)throw new TypeError("".concat(e," called on a non-initialised instance of Choices"));if(!this.initialisedOK)throw new TypeError("".concat(e," called for an element which has multiple instances of Choices initialised on it"))}},e.version="11.0.0-rc5",e}();return k})); diff --git a/public/assets/scripts/choices.search-prefix.min.mjs b/public/assets/scripts/choices.search-prefix.min.mjs index adde5be5..658e07d5 100644 --- a/public/assets/scripts/choices.search-prefix.min.mjs +++ b/public/assets/scripts/choices.search-prefix.min.mjs @@ -1,2 +1,2 @@ /*! choices.js v11.0.0-rc5 | © 2024 Josh Johnson | https://github.com/jshjohnson/Choices#readme */ -var e=function(t,i){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},e(t,i)};function t(t,i){if("function"!=typeof i&&null!==i)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");function n(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(n.prototype=i.prototype,new n)}var i=function(){return i=Object.assign||function(e){for(var t,i=1,n=arguments.length;i/g,">").replace(/0?this.element.scrollTop+r-s:e.offsetTop;requestAnimationFrame((function(){i._animateScroll(a,t)}))}},e.prototype._scrollDown=function(e,t,i){var n=(i-e)/t,s=n>1?n:1;this.element.scrollTop=e+s},e.prototype._scrollUp=function(e,t,i){var n=(e-i)/t,s=n>1?n:1;this.element.scrollTop=e-s},e.prototype._animateScroll=function(e,t){var i=this,n=this.element.scrollTop,s=!1;t>0?(this._scrollDown(n,4,e),ne&&(s=!0)),s&&requestAnimationFrame((function(){i._animateScroll(e,t)}))},e}(),C=function(){function e(e){var t=e.element,i=e.classNames;this.element=t,this.classNames=i,this.isDisabled=!1}return Object.defineProperty(e.prototype,"isActive",{get:function(){return"active"===this.element.dataset.choice},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dir",{get:function(){return this.element.dir},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.element.value},set:function(e){this.element.setAttribute("value",e),this.element.value=e},enumerable:!1,configurable:!0}),e.prototype.conceal=function(){var e;(e=this.element.classList).add.apply(e,d(this.classNames.input)),this.element.hidden=!0,this.element.tabIndex=-1;var t=this.element.getAttribute("style");t&&this.element.setAttribute("data-choice-orig-style",t),this.element.setAttribute("data-choice","active")},e.prototype.reveal=function(){var e;(e=this.element.classList).remove.apply(e,d(this.classNames.input)),this.element.hidden=!1,this.element.removeAttribute("tabindex");var t=this.element.getAttribute("data-choice-orig-style");t?(this.element.removeAttribute("data-choice-orig-style"),this.element.setAttribute("style",t)):this.element.removeAttribute("style"),this.element.removeAttribute("data-choice"),this.element.value=this.element.value},e.prototype.enable=function(){this.element.removeAttribute("disabled"),this.element.disabled=!1,this.isDisabled=!1},e.prototype.disable=function(){this.element.setAttribute("disabled",""),this.element.disabled=!0,this.isDisabled=!0},e.prototype.triggerEvent=function(e,t){!function(e,t,i){void 0===i&&(i=null);var n=new CustomEvent(t,{detail:i,bubbles:!0,cancelable:!0});e.dispatchEvent(n)}(this.element,e,t||{})},e}(),w=function(e){function i(){return null!==e&&e.apply(this,arguments)||this}return t(i,e),i}(C),I=function(e,t){return void 0===t&&(t=!0),void 0===e?t:!!e},S=function(e){if("string"==typeof e&&(e=e.split(" ").filter((function(e){return 0!==e.length}))),Array.isArray(e)&&0!==e.length)return e},O=function(e,t){if("string"==typeof e)return O({value:e,label:e},!1);var i=e;if("choices"in i){if(!t)throw new TypeError("optGroup is not allowed");var n=i,s=n.choices.map((function(e){return O(e,!1)}));return{id:0,label:h(n.label)||n.value,active:0!==s.length,disabled:!!n.disabled,choices:s}}var o=i;return{id:0,groupId:0,score:0,rank:0,value:o.value,label:o.label||o.value,active:I(o.active),selected:I(o.selected,!1),disabled:I(o.disabled,!1),placeholder:I(o.placeholder,!1),highlighted:!1,labelClass:S(o.labelClass),labelDescription:o.labelDescription,customProperties:o.customProperties}},T=function(e){function i(t){var i=t.element,n=t.classNames,s=t.template,o=t.extractPlaceholder,r=e.call(this,{element:i,classNames:n})||this;return r.template=s,r.extractPlaceholder=o,r}return t(i,e),Object.defineProperty(i.prototype,"placeholderOption",{get:function(){return this.element.querySelector('option[value=""]')||this.element.querySelector("option[placeholder]")},enumerable:!1,configurable:!0}),i.prototype.addOptions=function(e){var t=this;e.forEach((function(e){var i=e;if(!i.element){var n=t.template(i);t.element.appendChild(n),i.element=n}}))},i.prototype.optionsAsChoices=function(){var e=this,t=[];return this.element.querySelectorAll(":scope > option, :scope > optgroup").forEach((function(i){!function(e){return"OPTION"===e.tagName}(i)?function(e){return"OPTGROUP"===e.tagName}(i)&&t.push(e._optgroupToChoice(i)):t.push(e._optionToChoice(i))})),t},i.prototype._optionToChoice=function(e){return{id:0,groupId:0,score:0,rank:0,value:e.value,label:e.innerHTML,element:e,active:!0,selected:this.extractPlaceholder?e.selected:e.hasAttribute("selected"),disabled:e.disabled,highlighted:!1,placeholder:this.extractPlaceholder&&(""===e.value||e.hasAttribute("placeholder")),labelClass:void 0!==e.dataset.labelClass?S(e.dataset.labelClass):void 0,labelDescription:void 0!==e.dataset.labelDescription?e.dataset.labelDescription:void 0,customProperties:m(e.dataset.customProperties)}},i.prototype._optgroupToChoice=function(e){var t=this,i=e.querySelectorAll("option"),n=Array.from(i).map((function(e){return t._optionToChoice(e)}));return{id:0,label:e.label||"",element:e,active:0!==n.length,disabled:e.disabled,choices:n}},i}(C),A={items:[],choices:[],silent:!1,renderChoiceLimit:-1,maxItemCount:-1,singleModeForMultiSelect:!1,addChoices:!1,addItems:!0,addItemFilter:function(e){return!!e&&""!==e},removeItems:!0,removeItemButton:!1,removeItemButtonAlignLeft:!1,editItems:!1,allowHTML:!1,allowHtmlUserInput:!1,duplicateItemsAllowed:!0,delimiter:",",paste:!0,searchEnabled:!0,searchChoices:!0,searchFloor:1,searchResultLimit:4,searchFields:["label","value"],position:"auto",resetScrollPosition:!0,shouldSort:!0,shouldSortItems:!1,sorter:function(e,t){var i=e.value,n=e.label,s=void 0===n?i:n,o=t.value,r=t.label,a=void 0===r?o:r;return h(s).localeCompare(h(a),[],{sensitivity:"base",ignorePunctuation:!0,numeric:!0})},shadowRoot:null,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 "'.concat(e,'"')},removeItemIconText:function(){return"Remove item"},removeItemLabelText:function(e){return"Remove item: ".concat(e)},maxItemText:function(e){return"Only ".concat(e," values can be added")},valueComparer:function(e,t){return e===t},fuseOptions:{includeScore:!0},labelId:"",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"],description:["choices__description"],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"],selectedState:["is-selected"],flippedState:["is-flipped"],loadingState:["is-loading"],addChoice:["choices__item","choices__item--selectable","add-choice"],noResults:["has-no-results"],noChoices:["has-no-choices"]},appendGroupInSearch:!1},L=["fuseOptions","classNames"];function x(e){return"Minified Redux error #"+e+"; visit https://redux.js.org/Errors?code="+e+" for the full message or use the non-minified dev environment for full errors. "}var N="function"==typeof Symbol&&Symbol.observable||"@@observable",D=function(){return Math.random().toString(36).substring(7).split("").join(".")},P={INIT:"@@redux/INIT"+D(),REPLACE:"@@redux/REPLACE"+D(),PROBE_UNKNOWN_ACTION:function(){return"@@redux/PROBE_UNKNOWN_ACTION"+D()}};function F(e,t,i){var n;if("function"==typeof t&&"function"==typeof i||"function"==typeof i&&"function"==typeof arguments[3])throw new Error(x(0));if("function"==typeof t&&void 0===i&&(i=t,t=void 0),void 0!==i){if("function"!=typeof i)throw new Error(x(1));return i(F)(e,t)}if("function"!=typeof e)throw new Error(x(2));var s=e,o=t,r=[],a=r,c=!1;function l(){a===r&&(a=r.slice())}function h(){if(c)throw new Error(x(3));return o}function u(e){if("function"!=typeof e)throw new Error(x(4));if(c)throw new Error(x(5));var t=!0;return l(),a.push(e),function(){if(t){if(c)throw new Error(x(6));t=!1,l();var i=a.indexOf(e);a.splice(i,1),r=null}}}function d(e){if(!function(e){if("object"!=typeof e||null===e)return!1;for(var t=e;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}(e))throw new Error(x(7));if(void 0===e.type)throw new Error(x(8));if(c)throw new Error(x(9));try{c=!0,o=s(o,e)}finally{c=!1}for(var t=r=a,i=0;i0},e.prototype.getChoiceById=function(e){return this.activeChoices.find((function(t){return t.id===e}))},e.prototype.getGroupById=function(e){return this.groups.find((function(t){return t.id===e}))},e}(),R=function(e,t){return e?function(e){if("string"==typeof e)return e;if("object"==typeof e){if("escaped"in e)return e.escaped;if("trusted"in e)return e.trusted}return""}(t):c(t)},V=function(e,t){if(t){var i=e.dataset;"string"==typeof t?i.customProperties=t:"object"!=typeof t||function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}(t)||(i.customProperties=JSON.stringify(t))}},K={containerOuter:function(e,t,i,n,s,o,r){var a=e.classNames.containerOuter,c=Object.assign(document.createElement("div"),{className:d(a).join(" ")});return c.dataset.type=o,t&&(c.dir=t),n&&(c.tabIndex=0),i&&(c.setAttribute("role",s?"combobox":"listbox"),s&&c.setAttribute("aria-autocomplete","list")),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),r&&c.setAttribute("aria-labelledby",r),c},containerInner:function(e){var t=e.classNames.containerInner;return Object.assign(document.createElement("div"),{className:d(t).join(" ")})},itemList:function(e,t){var i=e.classNames,n=i.list,s=i.listSingle,o=i.listItems;return Object.assign(document.createElement("div"),{className:"".concat(d(n).join(" ")," ").concat(t?d(s).join(" "):d(o).join(" "))})},placeholder:function(e,t){var i=e.allowHTML,n=e.classNames.placeholder;return Object.assign(document.createElement("div"),{className:d(n).join(" "),innerHTML:R(i,t)})},item:function(e,t,i){var n,s,o,r=e.allowHTML,a=e.removeItemButtonAlignLeft,l=e.classNames,h=l.item,u=l.button,p=l.highlightedState,m=l.itemSelectable,f=l.placeholder,v=t.id,g=t.value,_=t.label,y=t.labelClass,b=t.labelDescription,E=t.customProperties,C=t.active,w=t.disabled,I=t.highlighted,S=t.placeholder,O=Object.assign(document.createElement("div"),{className:d(h).join(" ")});if(y){var T=Object.assign(document.createElement("span"),{innerHTML:R(r,_),className:d(y).join(" ")});O.appendChild(T)}else O.innerHTML=R(r,_);if(Object.assign(O.dataset,{item:"",id:v,value:g}),y&&(O.dataset.labelClass=d(y).join(" ")),b&&(O.dataset.labelDescription=b),V(O,E),C&&O.setAttribute("aria-selected","true"),w&&O.setAttribute("aria-disabled","true"),S&&((n=O.classList).add.apply(n,d(f)),O.dataset.placeholder=""),(s=O.classList).add.apply(s,d(I?p:m)),i){w&&(o=O.classList).remove.apply(o,d(m)),O.dataset.deletable="";var A="function"==typeof this.config.removeItemIconText?this.config.removeItemIconText(c(g),g):this.config.removeItemIconText,L="function"==typeof this.config.removeItemLabelText?this.config.removeItemLabelText(c(g),g):this.config.removeItemLabelText,x=Object.assign(document.createElement("button"),{type:"button",className:d(u).join(" "),innerHTML:A});L&&x.setAttribute("aria-label",L),x.dataset.button="",a?O.insertAdjacentElement("afterbegin",x):O.appendChild(x)}return O},choiceList:function(e,t){var i=e.classNames.list,n=Object.assign(document.createElement("div"),{className:d(i).join(" ")});return t||n.setAttribute("aria-multiselectable","true"),n.setAttribute("role","listbox"),n},choiceGroup:function(e,t){var i=e.allowHTML,n=e.classNames,s=n.group,o=n.groupHeading,r=n.itemDisabled,a=t.id,c=t.label,l=t.disabled,h=Object.assign(document.createElement("div"),{className:"".concat(d(s).join(" ")," ").concat(l?d(r).join(" "):"")});return h.setAttribute("role","group"),Object.assign(h.dataset,{group:"",id:a,value:c}),l&&h.setAttribute("aria-disabled","true"),h.appendChild(Object.assign(document.createElement("div"),{className:d(o).join(" "),innerHTML:R(i,c)})),h},choice:function(e,t,i){var n,s,o,r,a,c=e.allowHTML,l=e.classNames,h=l.item,u=l.itemChoice,p=l.itemSelectable,m=l.selectedState,f=l.itemDisabled,v=l.description,g=l.placeholder,_=t.id,y=t.value,b=t.label,E=t.groupId,C=t.elementId,w=t.labelClass,I=t.labelDescription,S=t.disabled,O=t.selected,T=t.placeholder,A=Object.assign(document.createElement("div"),{id:C,className:"".concat(d(h).join(" ")," ").concat(d(u).join(" "))}),L=A;if(w){var x=Object.assign(document.createElement("span"),{innerHTML:R(c,b),className:d(w).join(" ")});L=x,A.appendChild(x)}else A.innerHTML=R(c,b);if(I){var N="".concat(C,"-description");L.setAttribute("aria-describedby",N);var D=Object.assign(document.createElement("span"),{innerHTML:R(c,I),id:N});(n=D.classList).add.apply(n,d(v)),A.appendChild(D)}return O&&(s=A.classList).add.apply(s,d(m)),T&&(o=A.classList).add.apply(o,d(g)),A.setAttribute("role",E&&E>0?"treeitem":"option"),Object.assign(A.dataset,{choice:"",id:_,value:y,selectText:i}),w&&(A.dataset.labelClass=d(w).join(" ")),I&&(A.dataset.labelDescription=I),S?((r=A.classList).add.apply(r,d(f)),A.dataset.choiceDisabled="",A.setAttribute("aria-disabled","true")):((a=A.classList).add.apply(a,d(p)),A.dataset.choiceSelectable=""),A},input:function(e,t){var i=e.classNames,n=i.input,s=i.inputCloned,o=Object.assign(document.createElement("input"),{type:"search",className:"".concat(d(n).join(" ")," ").concat(d(s).join(" ")),autocomplete:"off",autocapitalize:"off",spellcheck:!1});return o.setAttribute("role","textbox"),o.setAttribute("aria-autocomplete","list"),t&&o.setAttribute("aria-label",t),o},dropdown:function(e){var t,i,n=e.classNames,s=n.list,o=n.listDropdown,r=document.createElement("div");return(t=r.classList).add.apply(t,d(s)),(i=r.classList).add.apply(i,d(o)),r.setAttribute("aria-expanded","false"),r},notice:function(e,t,i){var s=e.allowHTML,o=e.classNames,r=o.item,a=o.itemChoice,c=o.addChoice,l=o.noResults,h=o.noChoices;void 0===i&&(i="");var u=n(n([],d(r),!0),d(a),!0);switch(i){case"add-choice":u.push.apply(u,d(c));break;case"no-results":u.push.apply(u,d(l));break;case"no-choices":u.push.apply(u,d(h))}var p=Object.assign(document.createElement("div"),{innerHTML:R(s,t),className:u.join(" ")});return"add-choice"===i&&(p.dataset.choiceSelectable="",p.dataset.choice=""),p},option:function(e){var t=e.label,i=e.value,n=e.labelClass,s=e.labelDescription,o=e.customProperties,r=e.active,a=e.disabled,c=h(t),l=new Option(c,i,!1,r);return n&&(l.dataset.labelClass=d(n).join(" ")),s&&(l.dataset.labelDescription=s),V(l,o),l.disabled=a,l}},B=function(){function e(e){this._haystack=[],this._fields=e.searchFields}return e.prototype.index=function(e){this._haystack=e},e.prototype.reset=function(){this._haystack=[]},e.prototype.isEmptyIndex=function(){return 0===this._haystack.length},e.prototype.search=function(e){var t=this._fields;if(!t||0===t.length||""===e)return[];var i=e.toLowerCase();return this._haystack.filter((function(e){return t.some((function(t){return t in e&&e[t].toLowerCase().startsWith(i)}))})).map((function(e,t){return{item:e,score:t,rank:t}}))},e}();var U="-ms-scroll-limit"in document.documentElement.style&&"-ms-ime-align"in document.documentElement.style,q={},G=function(e){if(e){var t=e.dataset.id;return t?parseInt(t,10):void 0}},W=function(){function e(t,n){void 0===t&&(t="[data-choice]"),void 0===n&&(n={});var s=this;this.initialisedOK=void 0,this._hasNonChoicePlaceholder=!1,this._lastAddedChoiceId=0,this._lastAddedGroupId=0,this.config=i(i(i({},e.defaults.allOptions),e.defaults.options),n),L.forEach((function(t){s.config[t]=i(i(i({},e.defaults.allOptions[t]),e.defaults.options[t]),n[t])})),this.config.silent||this._validateConfig();var o=this.config.shadowRoot||document.documentElement,r="string"==typeof t?o.querySelector(t):t;if(!r||"object"!=typeof r||"INPUT"!==r.tagName&&!function(e){return"SELECT"===e.tagName}(r)){if(!r&&"string"==typeof t)throw TypeError("Selector ".concat(t," failed to find an element"));throw TypeError("Expected one of the following types text|select-one|select-multiple")}if(this._elementType=r.type,this._isTextElement=this._elementType===v,(this._isTextElement||1!==this.config.maxItemCount)&&(this.config.singleModeForMultiSelect=!1),this.config.singleModeForMultiSelect&&(this._elementType=_),this._isSelectOneElement=this._elementType===g,this._isSelectMultipleElement=this._elementType===_,this._isSelectElement=this._isSelectOneElement||this._isSelectMultipleElement,this._canAddUserChoices=this._isTextElement&&this.config.addItems||this._isSelectElement&&this.config.addChoices,["auto","always"].includes("".concat(this.config.renderSelectedChoices))||(this.config.renderSelectedChoices="auto"),this.config.placeholder&&(this.config.placeholderValue?this._hasNonChoicePlaceholder=!0:r.dataset.placeholder&&(this._hasNonChoicePlaceholder=!0,this.config.placeholderValue=r.dataset.placeholder)),n.addItemFilter&&"function"!=typeof n.addItemFilter){var c=n.addItemFilter instanceof RegExp?n.addItemFilter:new RegExp(n.addItemFilter);this.config.addItemFilter=c.test.bind(c)}if(this._isTextElement)this.passedElement=new w({element:r,classNames:this.config.classNames});else{var l=r;this.passedElement=new T({element:l,classNames:this.config.classNames,template:function(e){return s._templates.option(e)},extractPlaceholder:this.config.placeholder&&!this._hasNonChoicePlaceholder})}if(this.initialised=!1,this._store=new k,this._initialState=j,this._currentState=j,this._prevState=j,this._currentValue="",this.config.searchEnabled=!this._isTextElement&&this.config.searchEnabled||this._elementType===_,this._canSearch=this.config.searchEnabled,this._isScrollingOnIe=!1,this._highlightPosition=0,this._wasTap=!0,this._placeholderValue=this._generatePlaceholderValue(),this._baseId=function(e,t){var i=e.id||e.name&&"".concat(e.name,"-").concat(a(2))||a(4);return i=i.replace(/(:|\.|\[|\]|,)/g,""),"".concat(t,"-").concat(i)}(this.passedElement.element,"choices-"),this._direction=this.passedElement.dir,!this._direction){var h=window.getComputedStyle(this.passedElement.element).direction;h!==window.getComputedStyle(document.documentElement).direction&&(this._direction=h)}if(this._idNames={itemChoice:"item-choice"},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._onInput=this._onInput.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._onSelectKey=this._onSelectKey.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.passedElement.isActive)return this.config.silent||console.warn("Trying to initialise Choices on element already initialised",{element:t}),this.initialised=!0,void(this.initialisedOK=!1);this.init(),this._initialItems=this._store.items.map((function(e){return e.value}))}return Object.defineProperty(e,"defaults",{get:function(){return Object.preventExtensions({get options(){return q},get allOptions(){return A},get templates(){return K}})},enumerable:!1,configurable:!0}),e.prototype.init=function(){if(!this.initialised&&void 0===this.initialisedOK){var e;this._searcher=(e=this.config,new B(e)),this._loadChoices(),this._createTemplates(),this._createElements(),this._createStructure(),this._store.subscribe(this._render),this._render(),this._addEventListeners(),(this._isTextElement&&!this.config.addItems||this.passedElement.element.hasAttribute("disabled")||!!this.passedElement.element.closest("fieldset:disabled"))&&this.disable(),this.initialised=!0,this.initialisedOK=!0;var t=this.config.callbackOnInit;t&&"function"==typeof t&&t.call(this)}},e.prototype.destroy=function(){this.initialised&&(this._removeEventListeners(),this.passedElement.reveal(),this.containerOuter.unwrap(this.passedElement.element),this.clearStore(),this._stopSearch(),this._templates=K,this.initialised=!1,this.initialisedOK=void 0)},e.prototype.enable=function(){return this.passedElement.isDisabled&&this.passedElement.enable(),this.containerOuter.isDisabled&&(this._addEventListeners(),this.input.enable(),this.containerOuter.enable()),this},e.prototype.disable=function(){return this.passedElement.isDisabled||this.passedElement.disable(),this.containerOuter.isDisabled||(this._removeEventListeners(),this.input.disable(),this.containerOuter.disable()),this},e.prototype.highlightItem=function(e,t){if(void 0===t&&(t=!0),!e||!e.id)return this;var i=this._store.choices.find((function(t){return t.id===e.id}));return!i||i.highlighted||(this._store.dispatch(o(i,!0)),t&&this.passedElement.triggerEvent("highlightItem",this._getChoiceForOutput(i))),this},e.prototype.unhighlightItem=function(e,t){if(void 0===t&&(t=!0),!e||!e.id)return this;var i=this._store.choices.find((function(t){return t.id===e.id}));return i&&i.highlighted?(this._store.dispatch(o(i,!1)),t&&this.passedElement.triggerEvent("highlightItem",this._getChoiceForOutput(i)),this):this},e.prototype.highlightAll=function(){var e=this;return this._store.withTxn((function(){e._store.items.forEach((function(t){return e.highlightItem(t)}))})),this},e.prototype.unhighlightAll=function(){var e=this;return this._store.withTxn((function(){e._store.items.forEach((function(t){return e.unhighlightItem(t)}))})),this},e.prototype.removeActiveItemsByValue=function(e){var t=this;return this._store.withTxn((function(){t._store.items.filter((function(t){return t.value===e})).forEach((function(e){return t._removeItem(e)}))})),this},e.prototype.removeActiveItems=function(e){var t=this;return this._store.withTxn((function(){t._store.items.filter((function(t){return t.id!==e})).forEach((function(e){return t._removeItem(e)}))})),this},e.prototype.removeHighlightedItems=function(e){var t=this;return void 0===e&&(e=!1),this._store.withTxn((function(){t._store.highlightedActiveItems.forEach((function(i){t._removeItem(i),e&&t._triggerChange(i.value)}))})),this},e.prototype.showDropdown=function(e){var t=this;return this.dropdown.isActive||requestAnimationFrame((function(){t.dropdown.show(),t.containerOuter.open(t.dropdown.distanceFromTopWindow),!e&&t._canSearch&&t.input.focus(),t.passedElement.triggerEvent("showDropdown")})),this},e.prototype.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("hideDropdown")})),this):this},e.prototype.getValue=function(e){var t=this;void 0===e&&(e=!1);var i=this._store.items.reduce((function(i,n){var s=e?n.value:t._getChoiceForOutput(n);return i.push(s),i}),[]);return this._isSelectOneElement||this.config.singleModeForMultiSelect?i[0]:i},e.prototype.setValue=function(e){var t=this;return this.initialisedOK?(this._store.withTxn((function(){e.forEach((function(e){e&&t._addChoice(O(e,!1))}))})),this._searcher.reset(),this):(this._warnChoicesInitFailed("setValue"),this)},e.prototype.setChoiceByValue=function(e){var t=this;return this.initialisedOK?(this._isTextElement||(this._store.withTxn((function(){(Array.isArray(e)?e:[e]).forEach((function(e){return t._findAndSelectChoiceByValue(e)}))})),this._searcher.reset()),this):(this._warnChoicesInitFailed("setChoiceByValue"),this)},e.prototype.setChoices=function(e,t,n,s){var o=this;if(void 0===e&&(e=[]),void 0===t&&(t="value"),void 0===n&&(n="label"),void 0===s&&(s=!1),!this.initialisedOK)return this._warnChoicesInitFailed("setChoices"),this;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(s&&this.clearChoices(),"function"==typeof e){var r=e(this);if("function"==typeof Promise&&r instanceof Promise)return new Promise((function(e){return requestAnimationFrame(e)})).then((function(){return o._handleLoadingState(!0)})).then((function(){return r})).then((function(e){return o.setChoices(e,t,n,s)})).catch((function(e){o.config.silent||console.error(e)})).then((function(){return o._handleLoadingState(!1)})).then((function(){return o}));if(!Array.isArray(r))throw new TypeError(".setChoices first argument function must return either array of choices or Promise, got: ".concat(typeof r));return this.setChoices(r,t,n,!1)}if(!Array.isArray(e))throw new TypeError(".setChoices must be called either with array of choices with a function resulting into Promise of array of choices");return this.containerOuter.removeLoadingState(),this._store.withTxn((function(){var s="value"===t,r="label"===n;e.forEach((function(e){if("choices"in e){var a=e;r||(a=i(i({},a),{label:a[n]})),o._addGroup(O(a,!0))}else{var c=e;r&&s||(c=i(i({},c),{value:c[t],label:c[n]})),o._addChoice(O(c,!1))}}))})),this._searcher.reset(),this},e.prototype.refresh=function(e,t,i){var n=this;return void 0===e&&(e=!1),void 0===t&&(t=!1),void 0===i&&(i=!1),this._isSelectElement?(this._store.withTxn((function(){var s=n.passedElement.optionsAsChoices(),o=n._store.items,r={};i||o.forEach((function(e){e.id&&e.active&&e.selected&&!e.disabled&&(r[e.value]=!0)})),s.forEach((function(e){if(!("choices"in e)){var t=e;i?t.selected=!1:r[t.value]&&(t.selected=!0)}})),n.clearStore(),n._addPredefinedChoices(s,t,e),n._isSearching&&n._searchChoices(n.input.value)})),this):(this.config.silent||console.warn("refresh method can only be used on choices backed by a element"),this)},e.prototype.removeChoice=function(e){var t=this._store.choices.find((function(t){return t.value===e}));return t?(this._store.dispatch(function(e){return{type:"REMOVE_CHOICE",choice:e}}(t)),this._searcher.reset(),t.selected&&this.passedElement.triggerEvent("removeItem",this._getChoiceForOutput(t)),this):this},e.prototype.clearChoices=function(){return this.passedElement.element.innerHTML="",this._store.dispatch({type:"CLEAR_CHOICES"}),this._searcher.reset(),this},e.prototype.clearStore=function(){return this._store.resetStore(),this._lastAddedChoiceId=0,this._lastAddedGroupId=0,this._searcher.reset(),this},e.prototype.clearInput=function(){var e=!this._isSelectOneElement;return this.input.clear(e),this._isSearching&&this._stopSearch(),this},e.prototype._validateConfig=function(){var e,t,i,n,s=(e=this.config,t=T,i=Object.keys(e).sort(),n=Object.keys(t).sort(),i.filter((function(e){return n.indexOf(e)<0})));s.length&&console.warn("Unknown config option(s) passed",s.join(", ")),this.config.allowHTML&&this.config.allowHtmlUserInput&&(this.config.addItems&&console.warn("Warning: allowHTML/allowHtmlUserInput/addItems all being true is strongly not recommended and may lead to XSS attacks"),this.config.addChoices&&console.warn("Warning: allowHTML/allowHtmlUserInput/addChoices all being true is strongly not recommended and may lead to XSS attacks"))},e.prototype._render=function(e){if(!this._store.inTxn()){var t=null==e?void 0:e.items;((null==e?void 0:e.choices)||(null==e?void 0:e.groups)||t)&&(this._isSelectElement&&this._renderChoices(),t&&this._renderItems())}},e.prototype._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){if(!this._hasNonChoicePlaceholder){var o=n.filter((function(e){return e.placeholder&&-1===e.groupId}));o.length>=1&&(s=this._createChoicesFragment(o,s))}s=this._createGroupsFragment(i,n,s)}else n.length>=1&&(s=this._createChoicesFragment(n,s));var r=this.input.value,a=this._canAddItem(this._store.items,r);if(s.childNodes&&s.childNodes.length>0){var c=!a.response;if(a.response&&(this.choiceList.append(s),this._highlightChoice(),this._canAddUserChoices&&r&&a.notice&&(c=!n.find((function(t){return e.config.valueComparer(t.value,r)})))),c){var l=this._templates.notice(this.config,a.notice,this._canAddUserChoices?"add-choice":"");this.choiceList.prepend(l)}}else{var h=void 0;if(a.response&&this._canAddUserChoices&&r)h=this._templates.notice(this.config,a.notice,"add-choice");else if(this._isSearching){l="function"==typeof this.config.noResultsText?this.config.noResultsText():this.config.noResultsText;h=this._templates.notice(this.config,l,"no-results")}else{l="function"==typeof this.config.noChoicesText?this.config.noChoicesText():this.config.noChoicesText;h=this._templates.notice(this.config,l,"no-choices")}this.choiceList.append(h)}},e.prototype._renderItems=function(){var e=this._store.items||[];this.itemList.clear();var t=this._createItemsFragment(e);t.childNodes&&this.itemList.append(t)},e.prototype._createGroupsFragment=function(e,t,i){var n=this;void 0===i&&(i=document.createDocumentFragment());this.config.shouldSort&&e.sort(this.config.sorter);var s=t.filter((function(e){return 0===e.groupId}));return s.length>0&&this._createChoicesFragment(s,i,!1),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 o=n._templates.choiceGroup(n.config,e);i.appendChild(o),n._createChoicesFragment(s,i,!0)}})),i},e.prototype._createChoicesFragment=function(e,t,i){var s=this;void 0===t&&(t=document.createDocumentFragment()),void 0===i&&(i=!1);var o=this.config,r=o.renderSelectedChoices,a=o.searchResultLimit,c=o.renderChoiceLimit,l=[],u=this.config.appendGroupInSearch&&this._isSearching;u&&this._store.groups.forEach((function(e){l[e.id]=e.label}));var d=function(e){if("auto"!==r||(s._isSelectOneElement||!e.selected)){var i=s._templates.choice(s.config,e,s.config.itemSelectText);if(u&&e.groupId>0){var n=l[e.groupId];n&&(i.innerHTML+=" (".concat(n,")"))}t.appendChild(i)}},p=e;if("auto"!==r||this._isSelectOneElement||(p=e.filter((function(e){return!e.selected}))),this._isSelectElement){var m=e.filter((function(e){return!e.element}));0!==m.length&&this.passedElement.addOptions(m)}var f=[],v=[];this._hasNonChoicePlaceholder?v=p:p.forEach((function(e){e.placeholder?f.push(e):v.push(e)})),this._isSearching?v.sort(h):this.config.shouldSort&&v.sort(this.config.sorter);var g=p.length,_=this._isSelectOneElement&&0!==f.length?n(n([],f,!0),v,!0):v;this._isSearching?g=a:c&&c>0&&!i&&(g=c);for(var y=0;y0?this._store.getGroupById(e.groupId):null;return{id:e.id,highlighted:e.highlighted,labelClass:e.labelClass,labelDescription:e.labelDescription,customProperties:e.customProperties,disabled:e.disabled,active:e.active,label:e.label,placeholder:e.placeholder,value:e.value,groupValue:i&&i.label?i.label:void 0,element:e.element,keyCode:t}}},e.prototype._triggerChange=function(e){null!=e&&this.passedElement.triggerEvent("change",{value:e})},e.prototype._handleButtonAction=function(e,t){if(0!==e.length&&this.config.removeItems&&this.config.removeItemButton){var i=t&&H(t.parentNode),n=i&&e.find((function(e){return e.id===i}));if(n&&(this._removeItem(n),this._triggerChange(n.value),this._isSelectOneElement&&!this._hasNonChoicePlaceholder)){var s=this._store.choices.reverse().find((function(e){return!e.disabled&&e.placeholder}));s&&(this._addItem(s),s.value&&this._triggerChange(s.value))}}},e.prototype._handleItemAction=function(e,t,i){var n=this;if(void 0===i&&(i=!1),0!==e.length&&this.config.removeItems&&!this._isSelectOneElement){var s=H(t);s&&(e.forEach((function(e){e.id!==s||e.highlighted?!i&&e.highlighted&&n.unhighlightItem(e):n.highlightItem(e)})),this.input.focus())}},e.prototype._handleChoiceAction=function(e,t,i){var n=this,s=H(t),o=s&&this._store.getChoiceById(s);if(!o)return!1;var r=this.dropdown.isActive,a=!1;return this._store.withTxn((function(){if(!o.selected&&!o.disabled&&n._canAddItem(e,o.value).response){if(n.config.singleModeForMultiSelect&&0!==e.length){var t=e[e.length-1];n._removeItem(t)}n.passedElement.triggerEvent("choice",n._getChoiceForOutput(o,i)),n._addItem(o),n.clearInput(),a=!0}})),!!a&&(this._triggerChange(o.value),r&&(this.config.singleModeForMultiSelect||this._isSelectOneElement)&&(this.hideDropdown(!0),this.containerOuter.focus()),!0)},e.prototype._handleBackspace=function(e){if(this.config.removeItems&&0!==e.length){var t=e[e.length-1],i=e.some((function(e){return e.highlighted}));this.config.editItems&&!i&&t?(this.input.value=t.value,this.input.setWidth(),this._removeItem(t),this._triggerChange(t.value)):(i||this.highlightItem(t,!1),this.removeHighlightedItems(!0))}},e.prototype._loadChoices=function(){var e;if(this._isTextElement){this._presetChoices=this.config.items.map((function(e){return w(e,!1)}));var t=this.passedElement.value;if(t){var i=t.split(this.config.delimiter).map((function(e){return w(e,!1)}));this._presetChoices=this._presetChoices.concat(i)}this._presetChoices.forEach((function(e){e.selected=!0}))}else if(this._isSelectElement){this._presetChoices=this.config.choices.map((function(e){return w(e,!0)}));var n=this.passedElement.optionsAsChoices();n&&(e=this._presetChoices).push.apply(e,n)}},e.prototype._handleLoadingState=function(e){void 0===e&&(e=!0);var t=this.itemList.element.querySelector(d(this.config.classNames.placeholder));e?(this.disable(),this.containerOuter.addLoadingState(),this._isSelectOneElement?t?t.innerHTML=this.config.loadingText:(t=this._templates.placeholder(this.config,this.config.loadingText))&&this.itemList.append(t):this.input.placeholder=this.config.loadingText):(this.enable(),this.containerOuter.removeLoadingState(),this._isSelectOneElement?t&&(t.innerHTML=this._placeholderValue||""):this.input.placeholder=this._placeholderValue||"")},e.prototype._handleSearch=function(e){if(this.input.isFocussed){var t=this._store.choices,i=this.config,n=i.searchFloor,s=i.searchChoices,o=t.some((function(e){return!e.active}));if(null!=e&&e.length>=n){var r=s?this._searchChoices(e):0;null!==r&&this.passedElement.triggerEvent("search",{value:e,resultCount:r})}else o&&this._stopSearch()}},e.prototype._canAddItem=function(e,t){var i=this,n=!0,s="";(this.config.maxItemCount>0&&this.config.maxItemCount<=e.length&&(this.config.singleModeForMultiSelect||(n=!1,s="function"==typeof this.config.maxItemText?this.config.maxItemText(this.config.maxItemCount):this.config.maxItemText)),n&&this._canAddUserChoices&&""!==t&&"function"==typeof this.config.addItemFilter&&!this.config.addItemFilter(t)&&(n=!1,s="function"==typeof this.config.customAddItemText?this.config.customAddItemText(a(t),t):this.config.customAddItemText),!n||""===t||!this._isSelectElement&&this.config.duplicateItemsAllowed)||this._store.items.find((function(e){return i.config.valueComparer(e.value,t)}))&&(n=!1,s="function"==typeof this.config.uniqueItemText?this.config.uniqueItemText(a(t),t):this.config.uniqueItemText);return n&&(s="function"==typeof this.config.addItemText?this.config.addItemText(a(t),t):this.config.addItemText),{response:n,notice:{trusted:s}}},e.prototype._searchChoices=function(e){var t=e.trim().replace(/\s{2,}/," ");if(0===t.length||t===this._currentValue)return null;var i=this._searcher;i.isEmptyIndex()&&i.index(this._store.searchableChoices);var n=i.search(t);return this._currentValue=t,this._highlightPosition=0,this._isSearching=!0,this._store.dispatch(function(e){return{type:"FILTER_CHOICES",results:e}}(n)),n.length},e.prototype._stopSearch=function(){var e=this._isSearching;this._currentValue="",this._isSearching=!1,e&&this._store.dispatch({type:"ACTIVATE_CHOICES",active:!0})},e.prototype._addEventListeners=function(){var e=this.config.shadowRoot||document.documentElement;e.addEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.addEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.addEventListener("mousedown",this._onMouseDown,!0),e.addEventListener("click",this._onClick,{passive:!0}),e.addEventListener("touchmove",this._onTouchMove,{passive:!0}),this.dropdown.element.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("input",this._onInput,{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()},e.prototype._removeEventListeners=function(){var e=this.config.shadowRoot||document.documentElement;e.removeEventListener("touchend",this._onTouchEnd,!0),this.containerOuter.element.removeEventListener("keydown",this._onKeyDown,!0),this.containerOuter.element.removeEventListener("mousedown",this._onMouseDown,!0),e.removeEventListener("click",this._onClick),e.removeEventListener("touchmove",this._onTouchMove),this.dropdown.element.removeEventListener("mouseover",this._onMouseOver),this._isSelectOneElement&&(this.containerOuter.element.removeEventListener("focus",this._onFocus),this.containerOuter.element.removeEventListener("blur",this._onBlur)),this.input.element.removeEventListener("keyup",this._onKeyUp),this.input.element.removeEventListener("input",this._onInput),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()},e.prototype._onKeyDown=function(e){var t=e.keyCode,i=this._store.items,n=this.input.isFocussed,s=this.dropdown.isActive,o=this.itemList.hasChildren(),r=1===e.key.length||2===e.key.length&&e.key.charCodeAt(0)>=55296||"Unidentified"===e.key;switch(this._isTextElement||s||(this.showDropdown(),!this.input.isFocussed&&r&&(this.input.value+=e.key)),t){case 65:return this._onSelectKey(e,o);case 13:return this._onEnterKey(e,i,s);case 27:return this._onEscapeKey(e,s);case 38:case 33:case 40:case 34:return this._onDirectionKey(e,s);case 8:case 46:return this._onDeleteKey(e,i,n)}},e.prototype._onKeyUp=function(){this._canSearch=this.config.searchEnabled},e.prototype._onInput=function(){var e=this.input.value;if(e){if(this._isTextElement){var t=this._canAddItem(this._store.items,e);t.notice&&(this._displayAddItemNotice(t),this.showDropdown(!0))}if(this._canSearch){this._handleSearch(e);var i=this._canAddItem(this._store.items,e);i.response||this._displayAddItemNotice(i),this._canAddUserChoices&&(this._highlightPosition=0,this._highlightChoice())}}else this._isTextElement?this.hideDropdown(!0):this._stopSearch()},e.prototype._displayAddItemNotice=function(e){var t=this._templates.notice(this.config,e.notice,"add-choice"),i="".concat(d(this.config.classNames.addChoice),"[data-choice-selectable]"),n=this.choiceList.element.querySelector(i);n?n.outerHTML=t.outerHTML:this.choiceList.prepend(t)},e.prototype._onSelectKey=function(e,t){var i=e.ctrlKey,n=e.metaKey;(i||n)&&t&&(this._canSearch=!1,this.config.removeItems&&!this.input.value&&this.input.element===document.activeElement&&this.highlightAll())},e.prototype._onEnterKey=function(e,t,i){var n=this,s=this.input.value,o=e.target;if(o&&o.hasAttribute("data-button"))return e.preventDefault(),void this._handleButtonAction(t,o);if(!i&&this._isSelectOneElement)return e.preventDefault(),void this.showDropdown();if(i){var r=this.dropdown.element.querySelector(d(this.config.classNames.highlightedState));if(r&&this._handleChoiceAction(t,r,13))return e.preventDefault(),void this.unhighlightAll();s||this.hideDropdown(!0)}o&&s&&this._canAddUserChoices&&(this._canAddItem(t,s).response&&(this._store.withTxn((function(){if((n._isSelectOneElement||n.config.singleModeForMultiSelect)&&0!==t.length){var e=t[t.length-1];n._removeItem(e)}var i=!0;if(!n._isSelectElement&&n.config.duplicateItemsAllowed||(i=!n._findAndSelectChoiceByValue(s)),i){var o=a(s),r=n.config.allowHtmlUserInput||o===s?s:{escaped:o,raw:s};n._addChoice(w({value:r,label:r,selected:!0},!1))}n.clearInput(),n.unhighlightAll(),n._triggerChange(s)})),(this._isTextElement||this._isSelectOneElement)&&this.hideDropdown(!0)))},e.prototype._onEscapeKey=function(e,t){t&&(e.stopPropagation(),this.hideDropdown(!0),this.containerOuter.focus())},e.prototype._onDirectionKey=function(e,t){var i,n,s,o=e.keyCode,r=e.metaKey;if(t||this._isSelectOneElement){this.showDropdown(),this._canSearch=!1;var a=40===o||34===o?1:-1,c="[data-choice-selectable]",l=void 0;if(r||34===o||33===o)l=a>0?this.dropdown.element.querySelector("".concat(c,":last-of-type")):this.dropdown.element.querySelector(c);else{var h=this.dropdown.element.querySelector(d(this.config.classNames.highlightedState));l=h?function(e,t,i){void 0===i&&(i=1);for(var n="".concat(i>0?"next":"previous","ElementSibling"),s=e[n];s;){if(s.matches(t))return s;s=s[n]}return s}(h,c,a):this.dropdown.element.querySelector(c)}l&&(i=l,n=this.choiceList.element,void 0===(s=a)&&(s=1),i&&(s>0?n.scrollTop+n.offsetHeight>=i.offsetTop+i.offsetHeight:i.offsetTop>=n.scrollTop)||this.choiceList.scrollToChildElement(l,a),this._highlightChoice(l)),e.preventDefault()}},e.prototype._onDeleteKey=function(e,t,i){var n=e.target;this._isSelectOneElement||n.value||!i||(this._handleBackspace(t),e.preventDefault())},e.prototype._onTouchMove=function(){this._wasTap&&(this._wasTap=!1)},e.prototype._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},e.prototype._onMouseDown=function(e){var t=e.target;if(t instanceof HTMLElement){if(M&&this.choiceList.element.contains(t)){var i=this.choiceList.element.firstElementChild;this._isScrollingOnIe="ltr"===this._direction?e.offsetX>=i.offsetWidth:e.offsetX0&&this.unhighlightAll(),this.containerOuter.removeFocusState(),this.hideDropdown(!0))},e.prototype._onFocus=function(e){var t,i=this,n=e.target;n&&this.containerOuter.element.contains(n)&&((t={})[f]=function(){n===i.input.element&&i.containerOuter.addFocusState()},t[v]=function(){i.containerOuter.addFocusState(),n===i.input.element&&i.showDropdown(!0)},t[g]=function(){n===i.input.element&&(i.showDropdown(!0),i.containerOuter.addFocusState())},t)[this._elementType]()},e.prototype._onBlur=function(e){var t,i=this,n=e.target;if(n&&this.containerOuter.element.contains(n)&&!this._isScrollingOnIe){var s=this._store.activeChoices.some((function(e){return e.highlighted}));((t={})[f]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),s&&i.unhighlightAll(),i.hideDropdown(!0))},t[v]=function(){i.containerOuter.removeFocusState(),(n===i.input.element||n===i.containerOuter.element&&!i._canSearch)&&i.hideDropdown(!0)},t[g]=function(){n===i.input.element&&(i.containerOuter.removeFocusState(),i.hideDropdown(!0),s&&i.unhighlightAll())},t)[this._elementType]()}else this._isScrollingOnIe=!1,this.input.element.focus()},e.prototype._onFormReset=function(){var e=this;this._store.withTxn((function(){e.clearInput(),e.hideDropdown(),e.refresh(!1,!1,!0),0!==e._initialItems.length&&e.setChoiceByValue(e._initialItems)}))},e.prototype._highlightChoice=function(e){var t,i=this;void 0===e&&(e=null);var n=Array.from(this.dropdown.element.querySelectorAll("[data-choice-selectable]"));if(n.length){var s=e;Array.from(this.dropdown.element.querySelectorAll(d(this.config.classNames.highlightedState))).forEach((function(e){var t;(t=e.classList).remove.apply(t,u(i.config.classNames.highlightedState)),e.setAttribute("aria-selected","false")})),s?this._highlightPosition=n.indexOf(s):(s=n.length>this._highlightPosition?n[this._highlightPosition]:n[n.length-1])||(s=n[0]),(t=s.classList).add.apply(t,u(this.config.classNames.highlightedState)),s.setAttribute("aria-selected","true"),this.passedElement.triggerEvent("highlightChoice",{el:s}),this.dropdown.isActive&&(this.input.setActiveDescendant(s.id),this.containerOuter.setActiveDescendant(s.id))}},e.prototype._addItem=function(e,t){void 0===t&&(t=!0);var i=e.id;if(0===i)throw new TypeError("item.id must be set before _addItem is called for a choice/item");this._store.dispatch(function(e){return{type:"ADD_ITEM",item:e}}(e)),this._isSelectOneElement&&this.removeActiveItems(i),t&&this.passedElement.triggerEvent("addItem",this._getChoiceForOutput(e))},e.prototype._removeItem=function(e){e.id&&(this._store.dispatch(function(e){return{type:"REMOVE_ITEM",item:e}}(e)),this.passedElement.triggerEvent("removeItem",this._getChoiceForOutput(e)))},e.prototype._addChoice=function(e,t){if(void 0===t&&(t=!0),0!==e.id)throw new TypeError("Can not re-add a choice which has already been added");var i=e;this._lastAddedChoiceId++,i.id=this._lastAddedChoiceId,i.elementId="".concat(this._baseId,"-").concat(this._idNames.itemChoice,"-").concat(i.id),this.config.prependValue&&(i.value=this.config.prependValue+i.value),this.config.appendValue&&(i.value+=this.config.appendValue.toString()),(this.config.prependValue||this.config.appendValue)&&i.element&&(i.element.value=i.value),this._store.dispatch(function(e){return{type:"ADD_CHOICE",choice:e}}(e)),e.selected&&this._addItem(e,t)},e.prototype._addGroup=function(e,t){var i=this;if(void 0===t&&(t=!0),0!==e.id)throw new TypeError("Can not re-add a group which has already been added");if(this._store.dispatch(function(e){return{type:"ADD_GROUP",group:e}}(e)),e.choices){var n=e;this._lastAddedGroupId++,n.id=this._lastAddedGroupId;var s=e.id,o=e.choices;n.choices=[],o.forEach((function(n){var o=n;o.groupId=s,e.disabled&&(o.disabled=!0),i._addChoice(o,t)}))}},e.prototype._createTemplates=function(){var e=this,t=this.config.callbackOnCreateTemplates,i={};t&&"function"==typeof t&&(i=t.call(this,c,D));var n={};Object.keys(F).forEach((function(t){n[t]=t in i?i[t].bind(e):F[t].bind(e)})),this._templates=n},e.prototype._createElements=function(){this.containerOuter=new _({element:this._templates.containerOuter(this.config,this._direction,this._isSelectElement,this._isSelectOneElement,this.config.searchEnabled,this._elementType,this.config.labelId),classNames:this.config.classNames,type:this._elementType,position:this.config.position}),this.containerInner=new _({element:this._templates.containerInner(this.config),classNames:this.config.classNames,type:this._elementType,position:this.config.position}),this.input=new y({element:this._templates.input(this.config,this._placeholderValue),classNames:this.config.classNames,type:this._elementType,preventPaste:!this.config.paste}),this.choiceList=new b({element:this._templates.choiceList(this.config,this._isSelectOneElement)}),this.itemList=new b({element:this._templates.itemList(this.config,this._isSelectOneElement)}),this.dropdown=new m({element:this._templates.dropdown(this.config),classNames:this.config.classNames,type:this._elementType})},e.prototype._createStructure=function(){this.passedElement.conceal(),this.containerInner.wrap(this.passedElement.element),this.containerOuter.wrap(this.containerInner.element),this._isSelectOneElement?this.input.placeholder=this.config.searchPlaceholderValue||"":(this._placeholderValue&&(this.input.placeholder=this._placeholderValue),this.input.setWidth()),this.containerOuter.element.appendChild(this.containerInner.element),this.containerOuter.element.appendChild(this.dropdown.element),this.containerInner.element.appendChild(this.itemList.element),this.dropdown.element.appendChild(this.choiceList.element),this._isSelectOneElement?this.config.searchEnabled&&this.dropdown.element.insertBefore(this.input.element,this.dropdown.element.firstChild):this.containerInner.element.appendChild(this.input.element),this._highlightPosition=0,this._isSearching=!1},e.prototype._initStore=function(){var e=this;this._store.subscribe(this._render),this._store.withTxn((function(){e._addPredefinedChoices(e._presetChoices,e._isSelectOneElement&&!e._hasNonChoicePlaceholder,!1)}))},e.prototype._addPredefinedChoices=function(e,t,i){var n=this;if(void 0===t&&(t=!1),void 0===i&&(i=!0),this.config.shouldSort&&e.sort(this.config.sorter),t){var s=-1===e.findIndex((function(e){return!!e.selected}));if(s){var o=e.findIndex((function(e){return void 0===e.disabled||!e.disabled}));if(-1!==o)e[o].selected=!0}}e.forEach((function(e){"choices"in e?n._isSelectElement&&n._addGroup(e,i):n._addChoice(e,i)}))},e.prototype._findAndSelectChoiceByValue=function(e){var t=this,i=this._store.choices.find((function(i){return t.config.valueComparer(i.value,e)}));return!(!i||i.selected)&&(this._addItem(i),!0)},e.prototype._generatePlaceholderValue=function(){if(!this.config.placeholder)return null;if(this._hasNonChoicePlaceholder)return this.config.placeholderValue;if(this._isSelectElement){var e=this.passedElement.placeholderOption;return e?e.text:null}return null},e.prototype._warnChoicesInitFailed=function(e){if(!this.config.silent){if(!this.initialised)throw new TypeError("".concat(e," called on a non-initialised instance of Choices"));if(!this.initialisedOK)throw new TypeError("".concat(e," called for an element which has multiple instances of Choices initialised on it"))}},e.version="11.0.0-rc5",e}();export{k as default}; diff --git a/public/assets/scripts/choices.search-prefix.mjs b/public/assets/scripts/choices.search-prefix.mjs index f63fc1d9..dfa34d9c 100644 --- a/public/assets/scripts/choices.search-prefix.mjs +++ b/public/assets/scripts/choices.search-prefix.mjs @@ -99,14 +99,6 @@ var highlightItem = function (item, highlighted) { return ({ highlighted: highlighted, }); }; -var clearAll = function () { return ({ - type: "CLEAR_ALL" /* ActionType.CLEAR_ALL */, -}); }; -var setTxn = function (txn) { return ({ - type: "SET_TRANSACTION" /* ActionType.SET_TRANSACTION */, - txn: txn, -}); }; - /* eslint-disable @typescript-eslint/no-explicit-any */ var getRandomNumber = function (min, max) { return Math.floor(Math.random() * (max - min) + min); @@ -234,9 +226,6 @@ var dispatchEvent = function (element, type, customArgs) { }); return element.dispatchEvent(event); }; -var cloneObject = function (obj) { - return obj !== undefined ? JSON.parse(JSON.stringify(obj)) : undefined; -}; /** * Returns an array of keys present on the first but missing on the second object */ @@ -974,447 +963,85 @@ var DEFAULT_CONFIG = { var ObjectsInConfig = ['fuseOptions', 'classNames']; -/** - * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js - * - * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes - * during build. - * @param {number} code - */ -function formatProdErrorMessage(code) { - return "Minified Redux error #" + code + "; visit https://redux.js.org/Errors?code=" + code + " for the full message or " + 'use the non-minified dev environment for full errors. '; -} - -// Inlined version of the `symbol-observable` polyfill -var $$observable = function () { - return typeof Symbol === 'function' && Symbol.observable || '@@observable'; -}(); - -/** - * These are private action types reserved by Redux. - * For any unknown actions, you must return the current state. - * If the current state is undefined, you must return the initial state. - * Do not reference these action types directly in your code. - */ -var randomString = function randomString() { - return Math.random().toString(36).substring(7).split('').join('.'); -}; -var ActionTypes = { - INIT: "@@redux/INIT" + randomString(), - REPLACE: "@@redux/REPLACE" + randomString(), - PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() { - return "@@redux/PROBE_UNKNOWN_ACTION" + randomString(); - } -}; - -/** - * @param {any} obj The object to inspect. - * @returns {boolean} True if the argument appears to be a plain object. - */ -function isPlainObject(obj) { - if (typeof obj !== 'object' || obj === null) return false; - var proto = obj; - while (Object.getPrototypeOf(proto) !== null) { - proto = Object.getPrototypeOf(proto); - } - return Object.getPrototypeOf(obj) === proto; -} - -/** - * @deprecated - * - * **We recommend using the `configureStore` method - * of the `@reduxjs/toolkit` package**, which replaces `createStore`. - * - * Redux Toolkit is our recommended approach for writing Redux logic today, - * including store setup, reducers, data fetching, and more. - * - * **For more details, please read this Redux docs page:** - * **https://redux.js.org/introduction/why-rtk-is-redux-today** - * - * `configureStore` from Redux Toolkit is an improved version of `createStore` that - * simplifies setup and helps avoid common bugs. - * - * You should not be using the `redux` core package by itself today, except for learning purposes. - * The `createStore` method from the core `redux` package will not be removed, but we encourage - * all users to migrate to using Redux Toolkit for all Redux code. - * - * If you want to use `createStore` without this visual deprecation warning, use - * the `legacy_createStore` import instead: - * - * `import { legacy_createStore as createStore} from 'redux'` - * - */ - -function createStore(reducer, preloadedState, enhancer) { - var _ref2; - if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') { - throw new Error(formatProdErrorMessage(0) ); - } - if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { - enhancer = preloadedState; - preloadedState = undefined; - } - if (typeof enhancer !== 'undefined') { - if (typeof enhancer !== 'function') { - throw new Error(formatProdErrorMessage(1) ); - } - return enhancer(createStore)(reducer, preloadedState); - } - if (typeof reducer !== 'function') { - throw new Error(formatProdErrorMessage(2) ); - } - var currentReducer = reducer; - var currentState = preloadedState; - var currentListeners = []; - var nextListeners = currentListeners; - var isDispatching = false; - /** - * This makes a shallow copy of currentListeners so we can use - * nextListeners as a temporary list while dispatching. - * - * This prevents any bugs around consumers calling - * subscribe/unsubscribe in the middle of a dispatch. - */ - - function ensureCanMutateNextListeners() { - if (nextListeners === currentListeners) { - nextListeners = currentListeners.slice(); - } - } - /** - * Reads the state tree managed by the store. - * - * @returns {any} The current state tree of your application. - */ - - function getState() { - if (isDispatching) { - throw new Error(formatProdErrorMessage(3) ); - } - return currentState; - } - /** - * Adds a change listener. It will be called any time an action is dispatched, - * and some part of the state tree may potentially have changed. You may then - * call `getState()` to read the current state tree inside the callback. - * - * You may call `dispatch()` from a change listener, with the following - * caveats: - * - * 1. The subscriptions are snapshotted just before every `dispatch()` call. - * If you subscribe or unsubscribe while the listeners are being invoked, this - * will not have any effect on the `dispatch()` that is currently in progress. - * However, the next `dispatch()` call, whether nested or not, will use a more - * recent snapshot of the subscription list. - * - * 2. The listener should not expect to see all state changes, as the state - * might have been updated multiple times during a nested `dispatch()` before - * the listener is called. It is, however, guaranteed that all subscribers - * registered before the `dispatch()` started will be called with the latest - * state by the time it exits. - * - * @param {Function} listener A callback to be invoked on every dispatch. - * @returns {Function} A function to remove this change listener. - */ - - function subscribe(listener) { - if (typeof listener !== 'function') { - throw new Error(formatProdErrorMessage(4) ); - } - if (isDispatching) { - throw new Error(formatProdErrorMessage(5) ); - } - var isSubscribed = true; - ensureCanMutateNextListeners(); - nextListeners.push(listener); - return function unsubscribe() { - if (!isSubscribed) { - return; - } - if (isDispatching) { - throw new Error(formatProdErrorMessage(6) ); - } - isSubscribed = false; - ensureCanMutateNextListeners(); - var index = nextListeners.indexOf(listener); - nextListeners.splice(index, 1); - currentListeners = null; - }; - } - /** - * Dispatches an action. It is the only way to trigger a state change. - * - * The `reducer` function, used to create the store, will be called with the - * current state tree and the given `action`. Its return value will - * be considered the **next** state of the tree, and the change listeners - * will be notified. - * - * The base implementation only supports plain object actions. If you want to - * dispatch a Promise, an Observable, a thunk, or something else, you need to - * wrap your store creating function into the corresponding middleware. For - * example, see the documentation for the `redux-thunk` package. Even the - * middleware will eventually dispatch plain object actions using this method. - * - * @param {Object} action A plain object representing “what changed”. It is - * a good idea to keep actions serializable so you can record and replay user - * sessions, or use the time travelling `redux-devtools`. An action must have - * a `type` property which may not be `undefined`. It is a good idea to use - * string constants for action types. - * - * @returns {Object} For convenience, the same action object you dispatched. - * - * Note that, if you use a custom middleware, it may wrap `dispatch()` to - * return something else (for example, a Promise you can await). - */ - - function dispatch(action) { - if (!isPlainObject(action)) { - throw new Error(formatProdErrorMessage(7) ); - } - if (typeof action.type === 'undefined') { - throw new Error(formatProdErrorMessage(8) ); - } - if (isDispatching) { - throw new Error(formatProdErrorMessage(9) ); - } - try { - isDispatching = true; - currentState = currentReducer(currentState, action); - } finally { - isDispatching = false; - } - var listeners = currentListeners = nextListeners; - for (var i = 0; i < listeners.length; i++) { - var listener = listeners[i]; - listener(); - } - return action; - } - /** - * Replaces the reducer currently used by the store to calculate the state. - * - * You might need this if your app implements code splitting and you want to - * load some of the reducers dynamically. You might also need this if you - * implement a hot reloading mechanism for Redux. - * - * @param {Function} nextReducer The reducer for the store to use instead. - * @returns {void} - */ - - function replaceReducer(nextReducer) { - if (typeof nextReducer !== 'function') { - throw new Error(formatProdErrorMessage(10) ); - } - currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT. - // Any reducers that existed in both the new and old rootReducer - // will receive the previous state. This effectively populates - // the new state tree with any relevant data from the old one. - - dispatch({ - type: ActionTypes.REPLACE - }); - } - /** - * Interoperability point for observable/reactive libraries. - * @returns {observable} A minimal observable of state changes. - * For more information, see the observable proposal: - * https://github.com/tc39/proposal-observable - */ - - function observable() { - var _ref; - var outerSubscribe = subscribe; - return _ref = { - /** - * The minimal observable subscription method. - * @param {Object} observer Any object that can be used as an observer. - * The observer object should have a `next` method. - * @returns {subscription} An object with an `unsubscribe` method that can - * be used to unsubscribe the observable from the store, and prevent further - * emission of values from the observable. - */ - subscribe: function subscribe(observer) { - if (typeof observer !== 'object' || observer === null) { - throw new Error(formatProdErrorMessage(11) ); - } - function observeState() { - if (observer.next) { - observer.next(getState()); - } - } - observeState(); - var unsubscribe = outerSubscribe(observeState); - return { - unsubscribe: unsubscribe - }; - } - }, _ref[$$observable] = function () { - return this; - }, _ref; - } // When a store is created, an "INIT" action is dispatched so that every - // reducer returns their initial state. This effectively populates - // the initial state tree. - - dispatch({ - type: ActionTypes.INIT - }); - return _ref2 = { - dispatch: dispatch, - subscribe: subscribe, - getState: getState, - replaceReducer: replaceReducer - }, _ref2[$$observable] = observable, _ref2; -} -function assertReducerShape(reducers) { - Object.keys(reducers).forEach(function (key) { - var reducer = reducers[key]; - var initialState = reducer(undefined, { - type: ActionTypes.INIT - }); - if (typeof initialState === 'undefined') { - throw new Error(formatProdErrorMessage(12) ); - } - if (typeof reducer(undefined, { - type: ActionTypes.PROBE_UNKNOWN_ACTION() - }) === 'undefined') { - throw new Error(formatProdErrorMessage(13) ); - } - }); -} -/** - * Turns an object whose values are different reducer functions, into a single - * reducer function. It will call every child reducer, and gather their results - * into a single state object, whose keys correspond to the keys of the passed - * reducer functions. - * - * @param {Object} reducers An object whose values correspond to different - * reducer functions that need to be combined into one. One handy way to obtain - * it is to use ES6 `import * as reducers` syntax. The reducers may never return - * undefined for any action. Instead, they should return their initial state - * if the state passed to them was undefined, and the current state for any - * unrecognized action. - * - * @returns {Function} A reducer function that invokes every reducer inside the - * passed object, and builds a state object with the same shape. - */ - -function combineReducers(reducers) { - var reducerKeys = Object.keys(reducers); - var finalReducers = {}; - for (var i = 0; i < reducerKeys.length; i++) { - var key = reducerKeys[i]; - if (typeof reducers[key] === 'function') { - finalReducers[key] = reducers[key]; - } - } - var finalReducerKeys = Object.keys(finalReducers); // This is used to make sure we don't warn about the same - var shapeAssertionError; - try { - assertReducerShape(finalReducers); - } catch (e) { - shapeAssertionError = e; - } - return function combination(state, action) { - if (state === void 0) { - state = {}; - } - if (shapeAssertionError) { - throw shapeAssertionError; - } - var hasChanged = false; - var nextState = {}; - for (var _i = 0; _i < finalReducerKeys.length; _i++) { - var _key = finalReducerKeys[_i]; - var reducer = finalReducers[_key]; - var previousStateForKey = state[_key]; - var nextStateForKey = reducer(previousStateForKey, action); - if (typeof nextStateForKey === 'undefined') { - action && action.type; - throw new Error(formatProdErrorMessage(14) ); - } - nextState[_key] = nextStateForKey; - hasChanged = hasChanged || nextStateForKey !== previousStateForKey; - } - hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length; - return hasChanged ? nextState : state; - }; -} - -function items(state, action) { - if (state === void 0) { state = []; } - if (action === void 0) { action = {}; } +function items(s, action) { + var state = s; + var update = false; switch (action.type) { case "ADD_ITEM" /* ActionType.ADD_ITEM */: { var item = action.item; - if (!item.id) { - return state; + if (item.id) { + item.selected = true; + var el = item.element; + if (el) { + el.selected = true; + el.setAttribute('selected', ''); + } + update = true; + state.push(item); + state.forEach(function (obj) { + // eslint-disable-next-line no-param-reassign + obj.highlighted = false; + }); } - item.selected = true; - var el = item.element; - if (el) { - el.selected = true; - el.setAttribute('selected', ''); - } - return __spreadArray(__spreadArray([], state, true), [item], false).map(function (obj) { - var choice = obj; - choice.highlighted = false; - return choice; - }); + break; } case "REMOVE_ITEM" /* ActionType.REMOVE_ITEM */: { var item_1 = action.item; - if (!item_1.id) { - return state; + if (item_1.id) { + item_1.selected = false; + var el = item_1.element; + if (el) { + el.selected = false; + el.removeAttribute('selected'); + } + update = true; + state = state.filter(function (choice) { return choice.id !== item_1.id; }); } - item_1.selected = false; - var el = item_1.element; - if (el) { - el.selected = false; - el.removeAttribute('selected'); - } - return state.filter(function (choice) { return choice.id !== item_1.id; }); + break; } case "REMOVE_CHOICE" /* ActionType.REMOVE_CHOICE */: { var choice_1 = action.choice; - return state.filter(function (item) { return item.id !== choice_1.id; }); + update = true; + state = state.filter(function (item) { return item.id !== choice_1.id; }); + break; } case "HIGHLIGHT_ITEM" /* ActionType.HIGHLIGHT_ITEM */: { var highlightItemAction_1 = action; - return state.map(function (obj) { + update = true; + state.forEach(function (obj) { var item = obj; if (item.id === highlightItemAction_1.item.id) { item.highlighted = highlightItemAction_1.highlighted; } - return item; }); - } - default: { - return state; + break; } } + return { state: state, update: update }; } -function groups(state, action) { - if (state === void 0) { state = []; } - if (action === void 0) { action = {}; } +function groups(s, action) { + var state = s; + var update = false; switch (action.type) { case "ADD_GROUP" /* ActionType.ADD_GROUP */: { var addGroupAction = action; - return __spreadArray(__spreadArray([], state, true), [addGroupAction.group], false); + update = true; + state.push(addGroupAction.group); + break; } case "CLEAR_CHOICES" /* ActionType.CLEAR_CHOICES */: { - return []; - } - default: { - return state; + update = true; + state = []; + break; } } + return { state: state, update: update }; } -function choices(state, action) { - if (state === void 0) { state = []; } - if (action === void 0) { action = {}; } +function choices(s, action) { + var state = s; + var update = false; switch (action.type) { case "ADD_CHOICE" /* ActionType.ADD_CHOICE */: { var choice = action.choice; @@ -1423,36 +1050,41 @@ function choices(state, action) { A selected choice has been added to the passed input's value (added as an item) An active choice appears within the choice dropdown */ - return __spreadArray(__spreadArray([], state, true), [choice], false); + state.push(choice); + update = true; + break; } case "REMOVE_CHOICE" /* ActionType.REMOVE_CHOICE */: { var choice_1 = action.choice; - return state.filter(function (obj) { return obj.id !== choice_1.id; }); + update = true; + state = state.filter(function (obj) { return obj.id !== choice_1.id; }); + break; } case "ADD_ITEM" /* ActionType.ADD_ITEM */: { var item = action.item; // trigger a rebuild of the choices list as the item can not be added multiple times if (item.id && item.selected) { - return __spreadArray([], state, true); + update = true; } - return state; + break; } case "REMOVE_ITEM" /* ActionType.REMOVE_ITEM */: { var item = action.item; // trigger a rebuild of the choices list as the item can be added if (item.id && !item.selected) { - return __spreadArray([], state, true); + update = true; } - return state; + break; } case "FILTER_CHOICES" /* ActionType.FILTER_CHOICES */: { var results = action.results; + update = true; // avoid O(n^2) algorithm complexity when searching/filtering choices var scoreLookup_1 = []; results.forEach(function (result) { scoreLookup_1[result.item.id] = result; }); - return state.map(function (obj) { + state.forEach(function (obj) { var choice = obj; var result = scoreLookup_1[choice.id]; if (result !== undefined) { @@ -1465,102 +1097,110 @@ function choices(state, action) { choice.rank = 0; choice.active = false; } - return choice; }); + break; } case "ACTIVATE_CHOICES" /* ActionType.ACTIVATE_CHOICES */: { var active_1 = action.active; - return state.map(function (obj) { + update = true; + state.forEach(function (obj) { var choice = obj; choice.active = active_1; return choice; }); + break; } case "CLEAR_CHOICES" /* ActionType.CLEAR_CHOICES */: { - return []; - } - default: { - return state; + update = true; + state = []; + break; } } + return { state: state, update: update }; } -var general = function (state, action) { - if (state === void 0) { state = 0; } - if (action === void 0) { action = {}; } - switch (action.type) { - case "SET_TRANSACTION" /* ActionType.SET_TRANSACTION */: { - if (action.txn) { - return state + 1; - } - return Math.max(0, state - 1); - } - default: { - return state; - } - } -}; - -var defaultState = { - groups: [], - items: [], - choices: [], - txn: 0, -}; -var appReducer = combineReducers({ - items: items, +var reducers = { groups: groups, + items: items, choices: choices, - txn: general, -}); -var rootReducer = function (passedState, action) { - var state = passedState; - // If we are clearing all items, groups and options we reassign - // state and then pass that state to our proper reducer. This isn't - // mutating our actual state - // See: http://stackoverflow.com/a/35641992 - if (action.type === "CLEAR_ALL" /* ActionType.CLEAR_ALL */) { - // preserve the txn state as to allow withTxn to work - var paused = state.txn; - state = cloneObject(defaultState); - state.txn = paused; - } - return appReducer(state, action); }; - -/* eslint-disable @typescript-eslint/no-explicit-any */ var Store = /** @class */ (function () { function Store() { - this._store = createStore(rootReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && - window.__REDUX_DEVTOOLS_EXTENSION__()); + this._store = this.defaultState; + this._listeners = []; + this._txn = 0; } - /** - * Subscribe store to function call (wrapped Redux method) - */ - Store.prototype.subscribe = function (onChange) { - this._store.subscribe(onChange); + Object.defineProperty(Store.prototype, "defaultState", { + // eslint-disable-next-line class-methods-use-this + get: function () { + return { + groups: [], + items: [], + choices: [], + }; + }, + enumerable: false, + configurable: true + }); + // eslint-disable-next-line class-methods-use-this + Store.prototype.changeSet = function (init) { + return { + groups: init, + items: init, + choices: init, + }; + }; + Store.prototype.resetStore = function () { + this._store = this.defaultState; + var changes = this.changeSet(true); + this._listeners.forEach(function (l) { return l(changes); }); + }; + Store.prototype.subscribe = function (onChange) { + this._listeners.push(onChange); }; - /** - * Dispatch event to store (wrapped Redux method) - */ Store.prototype.dispatch = function (action) { - this._store.dispatch(action); + var state = this._store; + var hasChanges = false; + var changes = this._outstandingChanges || this.changeSet(false); + Object.keys(reducers).forEach(function (key) { + var stateUpdate = reducers[key](state[key], action); + if (stateUpdate.update) { + hasChanges = true; + changes[key] = true; + state[key] = stateUpdate.state; + } + }); + if (hasChanges) { + if (this._txn) { + this._outstandingChanges = changes; + } + else { + this._listeners.forEach(function (l) { return l(changes); }); + } + } }; Store.prototype.withTxn = function (func) { - this._store.dispatch(setTxn(true)); + this._txn++; try { func(); } finally { - this._store.dispatch(setTxn(false)); + this._txn = Math.max(0, this._txn - 1); + if (!this._txn) { + var changeSet_1 = this._outstandingChanges; + if (changeSet_1) { + this._outstandingChanges = undefined; + this._listeners.forEach(function (l) { return l(changeSet_1); }); + } + } } }; Object.defineProperty(Store.prototype, "state", { /** - * Get store object (wrapping Redux method) + * Get store object */ get: function () { - return this._store.getState(); + return this._store; }, enumerable: false, configurable: true @@ -1630,10 +1270,10 @@ var Store = /** @class */ (function () { * Get active groups from store */ get: function () { - var _a = this, groups = _a.groups, choices = _a.choices; - return groups.filter(function (group) { + var _this = this; + return this.state.groups.filter(function (group) { var isActive = group.active && !group.disabled; - var hasActiveOptions = choices.some(function (choice) { return choice.active && !choice.disabled; }); + var hasActiveOptions = _this.state.choices.some(function (choice) { return choice.active && !choice.disabled; }); return isActive && hasActiveOptions; }, []); }, @@ -1641,7 +1281,7 @@ var Store = /** @class */ (function () { configurable: true }); Store.prototype.inTxn = function () { - return this.state.txn > 0; + return this._txn > 0; }; /** * Get single choice by it's ID @@ -2102,9 +1742,6 @@ var Choices = /** @class */ (function () { } this.initialised = false; this._store = new Store(); - this._initialState = defaultState; - this._currentState = defaultState; - this._prevState = defaultState; this._currentValue = ''; this.config.searchEnabled = (!this._isTextElement && this.config.searchEnabled) || @@ -2187,8 +1824,7 @@ var Choices = /** @class */ (function () { this._createTemplates(); this._createElements(); this._createStructure(); - this._store.subscribe(this._render); - this._render(); + this._initStore(); this._addEventListeners(); var shouldDisable = (this._isTextElement && !this.config.addItems) || this.passedElement.element.hasAttribute('disabled') || @@ -2212,6 +1848,7 @@ var Choices = /** @class */ (function () { this.passedElement.reveal(); this.containerOuter.unwrap(this.passedElement.element); this.clearStore(); + this._store._listeners = []; this._stopSearch(); this._templates = templates; this.initialised = false; @@ -2617,7 +2254,7 @@ var Choices = /** @class */ (function () { return this; }; Choices.prototype.clearStore = function () { - this._store.dispatch(clearAll()); + this._store.resetStore(); this._lastAddedChoiceId = 0; this._lastAddedGroupId = 0; // @todo integrate with Store @@ -2646,15 +2283,12 @@ var Choices = /** @class */ (function () { } } }; - Choices.prototype._render = function () { + Choices.prototype._render = function (changes) { if (this._store.inTxn()) { return; } - this._currentState = this._store.state; - var shouldRenderItems = this._currentState.items !== this._prevState.items; - var stateChanged = this._currentState.choices !== this._prevState.choices || - this._currentState.groups !== this._prevState.groups || - shouldRenderItems; + var shouldRenderItems = changes === null || changes === void 0 ? void 0 : changes.items; + var stateChanged = (changes === null || changes === void 0 ? void 0 : changes.choices) || (changes === null || changes === void 0 ? void 0 : changes.groups) || shouldRenderItems; if (!stateChanged) { return; } @@ -2664,7 +2298,6 @@ var Choices = /** @class */ (function () { if (shouldRenderItems) { this._renderItems(); } - this._prevState = this._currentState; }; Choices.prototype._renderChoices = function () { var _this = this; @@ -3883,7 +3516,6 @@ var Choices = /** @class */ (function () { }); }; Choices.prototype._createStructure = function () { - var _this = this; // Hide original element this.passedElement.conceal(); // Wrap input in container preserving DOM ordering @@ -3911,6 +3543,10 @@ var Choices = /** @class */ (function () { } this._highlightPosition = 0; this._isSearching = false; + }; + Choices.prototype._initStore = function () { + var _this = this; + this._store.subscribe(this._render); this._store.withTxn(function () { _this._addPredefinedChoices(_this._presetChoices, _this._isSelectOneElement && !_this._hasNonChoicePlaceholder, false); }); diff --git a/public/types/src/scripts/actions/choices.d.ts b/public/types/src/scripts/actions/choices.d.ts index 00a1e7ef..111e4e90 100644 --- a/public/types/src/scripts/actions/choices.d.ts +++ b/public/types/src/scripts/actions/choices.d.ts @@ -1,24 +1,21 @@ import { ChoiceFull } from '../interfaces/choice-full'; import { ActionType } from '../interfaces'; import { SearchResult } from '../interfaces/search'; -export interface AddChoiceAction { - type: ActionType.ADD_CHOICE; +import { AnyAction } from '../interfaces/store'; +export type ChoiceActions = AddChoiceAction | RemoveChoiceAction | FilterChoicesAction | ActivateChoicesAction | ClearChoicesAction; +export interface AddChoiceAction extends AnyAction { choice: ChoiceFull; } -export interface RemoveChoiceAction { - type: ActionType.REMOVE_CHOICE; +export interface RemoveChoiceAction extends AnyAction { choice: ChoiceFull; } -export interface FilterChoicesAction { - type: ActionType.FILTER_CHOICES; +export interface FilterChoicesAction extends AnyAction { results: SearchResult[]; } -export interface ActivateChoicesAction { - type: ActionType.ACTIVATE_CHOICES; +export interface ActivateChoicesAction extends AnyAction { active: boolean; } -export interface ClearChoicesAction { - type: ActionType.CLEAR_CHOICES; +export interface ClearChoicesAction extends AnyAction { } export declare const addChoice: (choice: ChoiceFull) => AddChoiceAction; export declare const removeChoice: (choice: ChoiceFull) => RemoveChoiceAction; diff --git a/public/types/src/scripts/actions/groups.d.ts b/public/types/src/scripts/actions/groups.d.ts index 4eadf2aa..9b5c63f3 100644 --- a/public/types/src/scripts/actions/groups.d.ts +++ b/public/types/src/scripts/actions/groups.d.ts @@ -1,7 +1,8 @@ import { GroupFull } from '../interfaces/group-full'; import { ActionType } from '../interfaces'; -export interface AddGroupAction { - type: ActionType.ADD_GROUP; +import { AnyAction } from '../interfaces/store'; +export type GroupActions = AddGroupAction; +export interface AddGroupAction extends AnyAction { group: GroupFull; } export declare const addGroup: (group: GroupFull) => AddGroupAction; diff --git a/public/types/src/scripts/actions/items.d.ts b/public/types/src/scripts/actions/items.d.ts index ff9721cc..f0b5ec13 100644 --- a/public/types/src/scripts/actions/items.d.ts +++ b/public/types/src/scripts/actions/items.d.ts @@ -1,15 +1,14 @@ import { ChoiceFull } from '../interfaces/choice-full'; import { ActionType } from '../interfaces'; -export interface AddItemAction { - type: ActionType.ADD_ITEM; +import { AnyAction } from '../interfaces/store'; +export type ItemActions = AddItemAction | RemoveItemAction | HighlightItemAction; +export interface AddItemAction extends AnyAction { item: ChoiceFull; } -export interface RemoveItemAction { - type: ActionType.REMOVE_ITEM; +export interface RemoveItemAction extends AnyAction { item: ChoiceFull; } -export interface HighlightItemAction { - type: ActionType.HIGHLIGHT_ITEM; +export interface HighlightItemAction extends AnyAction { item: ChoiceFull; highlighted: boolean; } diff --git a/public/types/src/scripts/actions/misc.d.ts b/public/types/src/scripts/actions/misc.d.ts deleted file mode 100644 index a3e9feee..00000000 --- a/public/types/src/scripts/actions/misc.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { ActionType } from '../interfaces'; -export interface ClearAllAction { - type: ActionType.CLEAR_ALL; -} -export interface SetTransactionStateAction { - type: ActionType.SET_TRANSACTION; - txn: boolean; -} -export declare const clearAll: () => ClearAllAction; -export declare const setTxn: (txn: boolean) => SetTransactionStateAction; diff --git a/public/types/src/scripts/choices.d.ts b/public/types/src/scripts/choices.d.ts index 91910e23..8722561d 100644 --- a/public/types/src/scripts/choices.d.ts +++ b/public/types/src/scripts/choices.d.ts @@ -3,7 +3,7 @@ import { InputChoice } from './interfaces/input-choice'; import { InputGroup } from './interfaces/input-group'; import { Notice } from './interfaces/notice'; import { Options } from './interfaces/options'; -import { State } from './interfaces/state'; +import { StateChangeSet } from './interfaces/state'; import Store from './store/store'; import { ChoiceFull } from './interfaces/choice-full'; import { GroupFull } from './interfaces/group-full'; @@ -41,9 +41,6 @@ declare class Choices { _canAddUserChoices: boolean; _store: Store; _templates: Templates; - _initialState: State; - _currentState: State; - _prevState: State; _lastAddedChoiceId: number; _lastAddedGroupId: number; _currentValue: string; @@ -148,7 +145,7 @@ declare class Choices { clearStore(): this; clearInput(): this; _validateConfig(): void; - _render(): void; + _render(changes?: StateChangeSet): void; _renderChoices(): void; _renderItems(): void; _createGroupsFragment(groups: GroupFull[], choices: ChoiceFull[], fragment?: DocumentFragment): DocumentFragment; @@ -200,6 +197,7 @@ declare class Choices { _createTemplates(): void; _createElements(): void; _createStructure(): void; + _initStore(): void; _addPredefinedChoices(choices: (ChoiceFull | GroupFull)[], selectFirstOption?: boolean, withEvents?: boolean): void; _findAndSelectChoiceByValue(value: string): boolean; _generatePlaceholderValue(): string | null; diff --git a/public/types/src/scripts/interfaces/action-type.d.ts b/public/types/src/scripts/interfaces/action-type.d.ts index 6f8a8998..da43ba8d 100644 --- a/public/types/src/scripts/interfaces/action-type.d.ts +++ b/public/types/src/scripts/interfaces/action-type.d.ts @@ -7,7 +7,5 @@ export declare const enum ActionType { ADD_GROUP = "ADD_GROUP", ADD_ITEM = "ADD_ITEM", REMOVE_ITEM = "REMOVE_ITEM", - HIGHLIGHT_ITEM = "HIGHLIGHT_ITEM", - CLEAR_ALL = "CLEAR_ALL", - SET_TRANSACTION = "SET_TRANSACTION" + HIGHLIGHT_ITEM = "HIGHLIGHT_ITEM" } diff --git a/public/types/src/scripts/interfaces/state.d.ts b/public/types/src/scripts/interfaces/state.d.ts index 9f0fd995..31320e95 100644 --- a/public/types/src/scripts/interfaces/state.d.ts +++ b/public/types/src/scripts/interfaces/state.d.ts @@ -4,5 +4,7 @@ export interface State { choices: ChoiceFull[]; groups: GroupFull[]; items: ChoiceFull[]; - txn: number; } +export type StateChangeSet = { + [K in keyof State]: boolean; +}; diff --git a/public/types/src/scripts/interfaces/store.d.ts b/public/types/src/scripts/interfaces/store.d.ts index 43cf9d04..e47b22fb 100644 --- a/public/types/src/scripts/interfaces/store.d.ts +++ b/public/types/src/scripts/interfaces/store.d.ts @@ -1,10 +1,23 @@ -import { State } from './state'; +import { StateChangeSet, State } from './state'; import { ChoiceFull } from './choice-full'; import { GroupFull } from './group-full'; +import { ActionType } from './action-type'; +export interface AnyAction { + type: A; +} +export interface StateUpdate { + update: boolean; + state: T; +} +export type Reducer = (state: T, action: AnyAction) => StateUpdate; +export type StoreListener = (changes: StateChangeSet) => void; export interface Store { + dispatch(action: AnyAction): void; + subscribe(onChange: StoreListener): void; withTxn(func: () => void): void; + get defaultState(): State; /** - * Get store object (wrapping Redux method) + * Get store object */ get state(): State; /** diff --git a/public/types/src/scripts/reducers/choices.d.ts b/public/types/src/scripts/reducers/choices.d.ts index 3e05e4d3..f9485f6a 100644 --- a/public/types/src/scripts/reducers/choices.d.ts +++ b/public/types/src/scripts/reducers/choices.d.ts @@ -1,6 +1,8 @@ -import { AddChoiceAction, RemoveChoiceAction, FilterChoicesAction, ActivateChoicesAction, ClearChoicesAction } from '../actions/choices'; -import { AddItemAction, RemoveItemAction } from '../actions/items'; -import { ChoiceFull } from '../interfaces/choice-full'; -type ActionTypes = AddChoiceAction | RemoveChoiceAction | FilterChoicesAction | ActivateChoicesAction | ClearChoicesAction | AddItemAction | RemoveItemAction | Record; -export default function choices(state?: ChoiceFull[], action?: ActionTypes): ChoiceFull[]; +import { State } from '../interfaces'; +import { StateUpdate } from '../interfaces/store'; +import { ChoiceActions } from '../actions/choices'; +import { ItemActions } from '../actions/items'; +type ActionTypes = ChoiceActions | ItemActions; +type StateType = State['choices']; +export default function choices(s: StateType, action: ActionTypes): StateUpdate; export {}; diff --git a/public/types/src/scripts/reducers/groups.d.ts b/public/types/src/scripts/reducers/groups.d.ts index e556597c..d91bf7f7 100644 --- a/public/types/src/scripts/reducers/groups.d.ts +++ b/public/types/src/scripts/reducers/groups.d.ts @@ -1,7 +1,8 @@ -import { AddGroupAction } from '../actions/groups'; -import { ClearChoicesAction } from '../actions/choices'; +import { GroupActions } from '../actions/groups'; import { State } from '../interfaces/state'; -import { GroupFull } from '../interfaces/group-full'; -type ActionTypes = AddGroupAction | ClearChoicesAction | Record; -export default function groups(state?: GroupFull[], action?: ActionTypes): State['groups']; +import { StateUpdate } from '../interfaces/store'; +import { ChoiceActions } from '../actions/choices'; +type ActionTypes = ChoiceActions | GroupActions; +type StateType = State['groups']; +export default function groups(s: StateType, action: ActionTypes): StateUpdate; export {}; diff --git a/public/types/src/scripts/reducers/index.d.ts b/public/types/src/scripts/reducers/index.d.ts deleted file mode 100644 index 87bedde0..00000000 --- a/public/types/src/scripts/reducers/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { AnyAction } from 'redux'; -import { State } from '../interfaces'; -export declare const defaultState: State; -declare const rootReducer: (passedState: State, action: AnyAction) => object; -export default rootReducer; diff --git a/public/types/src/scripts/reducers/items.d.ts b/public/types/src/scripts/reducers/items.d.ts index ce2f09d2..1d8700bb 100644 --- a/public/types/src/scripts/reducers/items.d.ts +++ b/public/types/src/scripts/reducers/items.d.ts @@ -1,7 +1,8 @@ -import { AddItemAction, RemoveItemAction, HighlightItemAction } from '../actions/items'; +import { ItemActions } from '../actions/items'; import { State } from '../interfaces/state'; -import { RemoveChoiceAction } from '../actions/choices'; -import { ChoiceFull } from '../interfaces/choice-full'; -type ActionTypes = AddItemAction | RemoveChoiceAction | RemoveItemAction | HighlightItemAction | Record; -export default function items(state?: ChoiceFull[], action?: ActionTypes): State['items']; +import { ChoiceActions } from '../actions/choices'; +import { StateUpdate } from '../interfaces/store'; +type ActionTypes = ChoiceActions | ItemActions; +type StateType = State['items']; +export default function items(s: StateType, action: ActionTypes): StateUpdate; export {}; diff --git a/public/types/src/scripts/reducers/txn.d.ts b/public/types/src/scripts/reducers/txn.d.ts deleted file mode 100644 index c34db5c0..00000000 --- a/public/types/src/scripts/reducers/txn.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { SetTransactionStateAction } from '../actions/misc'; -import { State } from '../interfaces/state'; -type ActionTypes = SetTransactionStateAction | Record; -declare const general: (state?: number, action?: ActionTypes) => State["txn"]; -export default general; diff --git a/public/types/src/scripts/store/store.d.ts b/public/types/src/scripts/store/store.d.ts index f5838ec2..bbf9391f 100644 --- a/public/types/src/scripts/store/store.d.ts +++ b/public/types/src/scripts/store/store.d.ts @@ -1,22 +1,20 @@ -import { Store as ReduxStore, AnyAction } from 'redux'; -import { Store as IStore } from '../interfaces/store'; -import { State } from '../interfaces/state'; +import { AnyAction, Store as IStore, StoreListener } from '../interfaces/store'; +import { StateChangeSet, State } from '../interfaces/state'; import { ChoiceFull } from '../interfaces/choice-full'; import { GroupFull } from '../interfaces/group-full'; export default class Store implements IStore { - _store: ReduxStore; - constructor(); - /** - * Subscribe store to function call (wrapped Redux method) - */ - subscribe(onChange: () => void): void; - /** - * Dispatch event to store (wrapped Redux method) - */ + _store: State; + _listeners: StoreListener[]; + _txn: number; + _outstandingChanges?: StateChangeSet; + get defaultState(): State; + changeSet(init: boolean): StateChangeSet; + resetStore(): void; + subscribe(onChange: StoreListener): void; dispatch(action: AnyAction): void; withTxn(func: () => void): void; /** - * Get store object (wrapping Redux method) + * Get store object */ get state(): State; /** diff --git a/src/scripts/actions/choices.ts b/src/scripts/actions/choices.ts index e05c1b54..e9432628 100644 --- a/src/scripts/actions/choices.ts +++ b/src/scripts/actions/choices.ts @@ -1,30 +1,36 @@ import { ChoiceFull } from '../interfaces/choice-full'; import { ActionType } from '../interfaces'; import { SearchResult } from '../interfaces/search'; +import { AnyAction } from '../interfaces/store'; -export interface AddChoiceAction { - type: ActionType.ADD_CHOICE; +export type ChoiceActions = + | AddChoiceAction + | RemoveChoiceAction + | FilterChoicesAction + | ActivateChoicesAction + | ClearChoicesAction; + +export interface AddChoiceAction extends AnyAction { choice: ChoiceFull; } -export interface RemoveChoiceAction { - type: ActionType.REMOVE_CHOICE; +export interface RemoveChoiceAction + extends AnyAction { choice: ChoiceFull; } -export interface FilterChoicesAction { - type: ActionType.FILTER_CHOICES; +export interface FilterChoicesAction + extends AnyAction { results: SearchResult[]; } -export interface ActivateChoicesAction { - type: ActionType.ACTIVATE_CHOICES; +export interface ActivateChoicesAction + extends AnyAction { active: boolean; } -export interface ClearChoicesAction { - type: ActionType.CLEAR_CHOICES; -} +export interface ClearChoicesAction + extends AnyAction {} export const addChoice = (choice: ChoiceFull): AddChoiceAction => ({ type: ActionType.ADD_CHOICE, diff --git a/src/scripts/actions/groups.ts b/src/scripts/actions/groups.ts index 0e2f4d6c..10433fb5 100644 --- a/src/scripts/actions/groups.ts +++ b/src/scripts/actions/groups.ts @@ -1,8 +1,10 @@ import { GroupFull } from '../interfaces/group-full'; import { ActionType } from '../interfaces'; +import { AnyAction } from '../interfaces/store'; -export interface AddGroupAction { - type: ActionType.ADD_GROUP; +export type GroupActions = AddGroupAction; + +export interface AddGroupAction extends AnyAction { group: GroupFull; } diff --git a/src/scripts/actions/items.ts b/src/scripts/actions/items.ts index 200db5a2..8084c45c 100644 --- a/src/scripts/actions/items.ts +++ b/src/scripts/actions/items.ts @@ -1,18 +1,22 @@ import { ChoiceFull } from '../interfaces/choice-full'; import { ActionType } from '../interfaces'; +import { AnyAction } from '../interfaces/store'; -export interface AddItemAction { - type: ActionType.ADD_ITEM; +export type ItemActions = + | AddItemAction + | RemoveItemAction + | HighlightItemAction; + +export interface AddItemAction extends AnyAction { item: ChoiceFull; } -export interface RemoveItemAction { - type: ActionType.REMOVE_ITEM; +export interface RemoveItemAction extends AnyAction { item: ChoiceFull; } -export interface HighlightItemAction { - type: ActionType.HIGHLIGHT_ITEM; +export interface HighlightItemAction + extends AnyAction { item: ChoiceFull; highlighted: boolean; } diff --git a/src/scripts/actions/misc.ts b/src/scripts/actions/misc.ts deleted file mode 100644 index e7591df5..00000000 --- a/src/scripts/actions/misc.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { ActionType } from '../interfaces'; - -export interface ClearAllAction { - type: ActionType.CLEAR_ALL; -} - -export interface SetTransactionStateAction { - type: ActionType.SET_TRANSACTION; - txn: boolean; -} - -export const clearAll = (): ClearAllAction => ({ - type: ActionType.CLEAR_ALL, -}); - -export const setTxn = (txn: boolean): SetTransactionStateAction => ({ - type: ActionType.SET_TRANSACTION, - txn, -}); diff --git a/src/scripts/choices.ts b/src/scripts/choices.ts index 0895bcd1..bbebcb9c 100644 --- a/src/scripts/choices.ts +++ b/src/scripts/choices.ts @@ -8,7 +8,6 @@ import { } from './actions/choices'; import { addGroup } from './actions/groups'; import { addItem, highlightItem, removeItem } from './actions/items'; -import { clearAll } from './actions/misc'; import { Container, Dropdown, @@ -23,7 +22,7 @@ import { InputChoice } from './interfaces/input-choice'; import { InputGroup } from './interfaces/input-group'; import { Notice } from './interfaces/notice'; import { Options, ObjectsInConfig } from './interfaces/options'; -import { State } from './interfaces/state'; +import { StateChangeSet } from './interfaces/state'; import { diff, generateId, @@ -35,7 +34,6 @@ import { sortByRank, strToEl, } from './lib/utils'; -import { defaultState } from './reducers'; import Store from './store/store'; import templates, { escapeForTemplate } from './templates'; import { mapInputToChoice } from './lib/choice-input'; @@ -131,12 +129,6 @@ class Choices { _templates: Templates; - _initialState: State; - - _currentState: State; - - _prevState: State; - _lastAddedChoiceId: number = 0; _lastAddedGroupId: number = 0; @@ -273,9 +265,6 @@ class Choices { this.initialised = false; this._store = new Store(); - this._initialState = defaultState; - this._currentState = defaultState; - this._prevState = defaultState; this._currentValue = ''; this.config.searchEnabled = (!this._isTextElement && this.config.searchEnabled) || @@ -358,10 +347,7 @@ class Choices { this._createTemplates(); this._createElements(); this._createStructure(); - - this._store.subscribe(this._render); - - this._render(); + this._initStore(); this._addEventListeners(); const shouldDisable = @@ -393,6 +379,7 @@ class Choices { this.containerOuter.unwrap(this.passedElement.element); this.clearStore(); + this._store._listeners = []; this._stopSearch(); this._templates = templates; @@ -898,7 +885,7 @@ class Choices { } clearStore(): this { - this._store.dispatch(clearAll()); + this._store.resetStore(); this._lastAddedChoiceId = 0; this._lastAddedGroupId = 0; // @todo integrate with Store @@ -941,19 +928,14 @@ class Choices { } } - _render(): void { + _render(changes?: StateChangeSet): void { if (this._store.inTxn()) { return; } - this._currentState = this._store.state; - - const shouldRenderItems = - this._currentState.items !== this._prevState.items; + const shouldRenderItems = changes?.items; const stateChanged = - this._currentState.choices !== this._prevState.choices || - this._currentState.groups !== this._prevState.groups || - shouldRenderItems; + changes?.choices || changes?.groups || shouldRenderItems; if (!stateChanged) { return; @@ -966,8 +948,6 @@ class Choices { if (shouldRenderItems) { this._renderItems(); } - - this._prevState = this._currentState; } _renderChoices(): void { @@ -2570,6 +2550,11 @@ class Choices { this._highlightPosition = 0; this._isSearching = false; + } + + _initStore(): void { + this._store.subscribe(this._render); + this._store.withTxn(() => { this._addPredefinedChoices( this._presetChoices, diff --git a/src/scripts/interfaces/action-type.ts b/src/scripts/interfaces/action-type.ts index 617bfe8c..7b4078e4 100644 --- a/src/scripts/interfaces/action-type.ts +++ b/src/scripts/interfaces/action-type.ts @@ -8,6 +8,4 @@ export const enum ActionType { ADD_ITEM = 'ADD_ITEM', REMOVE_ITEM = 'REMOVE_ITEM', HIGHLIGHT_ITEM = 'HIGHLIGHT_ITEM', - CLEAR_ALL = 'CLEAR_ALL', - SET_TRANSACTION = 'SET_TRANSACTION', } diff --git a/src/scripts/interfaces/state.ts b/src/scripts/interfaces/state.ts index d30230d4..942c70af 100644 --- a/src/scripts/interfaces/state.ts +++ b/src/scripts/interfaces/state.ts @@ -5,5 +5,8 @@ export interface State { choices: ChoiceFull[]; groups: GroupFull[]; items: ChoiceFull[]; - txn: number; } + +export type StateChangeSet = { + [K in keyof State]: boolean; +}; diff --git a/src/scripts/interfaces/store.ts b/src/scripts/interfaces/store.ts index 5cb92b14..1acd00f8 100644 --- a/src/scripts/interfaces/store.ts +++ b/src/scripts/interfaces/store.ts @@ -1,12 +1,32 @@ -import { State } from './state'; +import { StateChangeSet, State } from './state'; import { ChoiceFull } from './choice-full'; import { GroupFull } from './group-full'; +import { ActionType } from './action-type'; + +export interface AnyAction { + type: A; +} + +export interface StateUpdate { + update: boolean; + state: T; +} + +export type Reducer = (state: T, action: AnyAction) => StateUpdate; + +export type StoreListener = (changes: StateChangeSet) => void; export interface Store { + dispatch(action: AnyAction): void; + + subscribe(onChange: StoreListener): void; + withTxn(func: () => void): void; + get defaultState(): State; + /** - * Get store object (wrapping Redux method) + * Get store object */ get state(): State; diff --git a/src/scripts/reducers/choices.ts b/src/scripts/reducers/choices.ts index 17b197c1..f667eab1 100644 --- a/src/scripts/reducers/choices.ts +++ b/src/scripts/reducers/choices.ts @@ -1,77 +1,73 @@ -import { - AddChoiceAction, - RemoveChoiceAction, - FilterChoicesAction, - ActivateChoicesAction, - ClearChoicesAction, -} from '../actions/choices'; -import { AddItemAction, RemoveItemAction } from '../actions/items'; -import { ChoiceFull } from '../interfaces/choice-full'; -import { ActionType } from '../interfaces'; +import { ActionType, State } from '../interfaces'; +import { StateUpdate } from '../interfaces/store'; +import { ChoiceActions } from '../actions/choices'; +import { ItemActions } from '../actions/items'; import { SearchResult } from '../interfaces/search'; +import { ChoiceFull } from '../interfaces/choice-full'; -type ActionTypes = - | AddChoiceAction - | RemoveChoiceAction - | FilterChoicesAction - | ActivateChoicesAction - | ClearChoicesAction - | AddItemAction - | RemoveItemAction - | Record; +type ActionTypes = ChoiceActions | ItemActions; +type StateType = State['choices']; export default function choices( - state: ChoiceFull[] = [], - action: ActionTypes = {}, -): ChoiceFull[] { + s: StateType, + action: ActionTypes, +): StateUpdate { + let state = s; + let update = false; + switch (action.type) { case ActionType.ADD_CHOICE: { - const { choice } = action as AddChoiceAction; + const { choice } = action; /* A disabled choice appears in the choice dropdown but cannot be selected A selected choice has been added to the passed input's value (added as an item) An active choice appears within the choice dropdown */ - return [...state, choice]; + state.push(choice); + update = true; + break; } case ActionType.REMOVE_CHOICE: { - const { choice } = action as RemoveChoiceAction; + const { choice } = action; - return state.filter((obj) => obj.id !== choice.id); + update = true; + state = state.filter((obj) => obj.id !== choice.id); + break; } case ActionType.ADD_ITEM: { - const { item } = action as AddItemAction; + const { item } = action; // trigger a rebuild of the choices list as the item can not be added multiple times if (item.id && item.selected) { - return [...state]; + update = true; } - return state; + break; } case ActionType.REMOVE_ITEM: { - const { item } = action as RemoveItemAction; + const { item } = action; // trigger a rebuild of the choices list as the item can be added if (item.id && !item.selected) { - return [...state]; + update = true; } - return state; + break; } case ActionType.FILTER_CHOICES: { - const { results } = action as FilterChoicesAction; + const { results } = action; + update = true; // avoid O(n^2) algorithm complexity when searching/filtering choices const scoreLookup: SearchResult[] = []; results.forEach((result) => { scoreLookup[result.item.id] = result; }); - return state.map((obj) => { + state.forEach((obj) => { const choice = obj; const result = scoreLookup[choice.id]; if (result !== undefined) { @@ -83,28 +79,33 @@ export default function choices( choice.rank = 0; choice.active = false; } - - return choice; }); + + break; } case ActionType.ACTIVATE_CHOICES: { - const { active } = action as ActivateChoicesAction; + const { active } = action; - return state.map((obj) => { + update = true; + state.forEach((obj) => { const choice = obj; choice.active = active; return choice; }); + break; } case ActionType.CLEAR_CHOICES: { - return []; + update = true; + state = []; + break; } - default: { - return state; - } + default: + break; } + + return { state, update }; } diff --git a/src/scripts/reducers/groups.ts b/src/scripts/reducers/groups.ts index 9901ddda..06e3b430 100644 --- a/src/scripts/reducers/groups.ts +++ b/src/scripts/reducers/groups.ts @@ -1,28 +1,37 @@ -import { AddGroupAction } from '../actions/groups'; -import { ClearChoicesAction } from '../actions/choices'; +import { GroupActions } from '../actions/groups'; import { State } from '../interfaces/state'; -import { GroupFull } from '../interfaces/group-full'; import { ActionType } from '../interfaces'; +import { StateUpdate } from '../interfaces/store'; +import { ChoiceActions } from '../actions/choices'; -type ActionTypes = AddGroupAction | ClearChoicesAction | Record; +type ActionTypes = ChoiceActions | GroupActions; +type StateType = State['groups']; export default function groups( - state: GroupFull[] = [], - action: ActionTypes = {}, -): State['groups'] { + s: StateType, + action: ActionTypes, +): StateUpdate { + let state = s; + let update = false; + switch (action.type) { case ActionType.ADD_GROUP: { - const addGroupAction = action as AddGroupAction; + const addGroupAction = action; - return [...state, addGroupAction.group]; + update = true; + state.push(addGroupAction.group); + break; } case ActionType.CLEAR_CHOICES: { - return []; + update = true; + state = []; + break; } - default: { - return state; - } + default: + break; } + + return { state, update }; } diff --git a/src/scripts/reducers/index.ts b/src/scripts/reducers/index.ts deleted file mode 100644 index 0a5e2871..00000000 --- a/src/scripts/reducers/index.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { AnyAction, combineReducers } from 'redux'; -import items from './items'; -import groups from './groups'; -import choices from './choices'; -import txn from './txn'; -import { cloneObject } from '../lib/utils'; -import { ActionType, State } from '../interfaces'; - -export const defaultState: State = { - groups: [], - items: [], - choices: [], - txn: 0, -}; - -const appReducer = combineReducers({ - items, - groups, - choices, - txn, -}); - -const rootReducer = (passedState: State, action: AnyAction): object => { - let state = passedState; - // If we are clearing all items, groups and options we reassign - // state and then pass that state to our proper reducer. This isn't - // mutating our actual state - // See: http://stackoverflow.com/a/35641992 - if (action.type === ActionType.CLEAR_ALL) { - // preserve the txn state as to allow withTxn to work - const paused = state.txn; - state = cloneObject(defaultState); - state.txn = paused; - } - - return appReducer(state, action); -}; - -export default rootReducer; diff --git a/src/scripts/reducers/items.ts b/src/scripts/reducers/items.ts index 02ec3a04..54a7e874 100644 --- a/src/scripts/reducers/items.ts +++ b/src/scripts/reducers/items.ts @@ -1,83 +1,82 @@ -import { - AddItemAction, - RemoveItemAction, - HighlightItemAction, -} from '../actions/items'; +import { ItemActions } from '../actions/items'; import { State } from '../interfaces/state'; -import { RemoveChoiceAction } from '../actions/choices'; -import { ChoiceFull } from '../interfaces/choice-full'; +import { ChoiceActions } from '../actions/choices'; import { ActionType } from '../interfaces'; +import { StateUpdate } from '../interfaces/store'; -type ActionTypes = - | AddItemAction - | RemoveChoiceAction - | RemoveItemAction - | HighlightItemAction - | Record; +type ActionTypes = ChoiceActions | ItemActions; +type StateType = State['items']; export default function items( - state: ChoiceFull[] = [], - action: ActionTypes = {}, -): State['items'] { + s: StateType, + action: ActionTypes, +): StateUpdate { + let state = s; + let update = false; + switch (action.type) { case ActionType.ADD_ITEM: { - const { item } = action as AddItemAction; - if (!item.id) { - return state; + const { item } = action; + if (item.id) { + item.selected = true; + const el = item.element as HTMLOptionElement | undefined; + if (el) { + el.selected = true; + el.setAttribute('selected', ''); + } + + update = true; + state.push(item); + state.forEach((obj) => { + // eslint-disable-next-line no-param-reassign + obj.highlighted = false; + }); } - item.selected = true; - const el = item.element as HTMLOptionElement; - if (el) { - el.selected = true; - el.setAttribute('selected', ''); - } - - return [...state, item].map((obj) => { - const choice = obj; - choice.highlighted = false; - - return choice; - }); + break; } case ActionType.REMOVE_ITEM: { - const { item } = action as RemoveItemAction; - if (!item.id) { - return state; - } + const { item } = action; + if (item.id) { + item.selected = false; + const el = item.element as HTMLOptionElement | undefined; + if (el) { + el.selected = false; + el.removeAttribute('selected'); + } - item.selected = false; - const el = item.element as HTMLOptionElement; - if (el) { - el.selected = false; - el.removeAttribute('selected'); + update = true; + state = state.filter((choice) => choice.id !== item.id); } - - return state.filter((choice) => choice.id !== item.id); + break; } case ActionType.REMOVE_CHOICE: { - const { choice } = action as RemoveChoiceAction; + const { choice } = action; - return state.filter((item) => item.id !== choice.id); + update = true; + state = state.filter((item) => item.id !== choice.id); + break; } case ActionType.HIGHLIGHT_ITEM: { - const highlightItemAction = action as HighlightItemAction; + const highlightItemAction = action; - return state.map((obj) => { + update = true; + state.forEach((obj) => { const item = obj; if (item.id === highlightItemAction.item.id) { item.highlighted = highlightItemAction.highlighted; } - - return item; }); + + break; } - default: { - return state; - } + default: + break; } + + return { state, update }; } diff --git a/src/scripts/reducers/txn.ts b/src/scripts/reducers/txn.ts deleted file mode 100644 index 28bf847f..00000000 --- a/src/scripts/reducers/txn.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { SetTransactionStateAction } from '../actions/misc'; -import { State } from '../interfaces/state'; -import { ActionType } from '../interfaces'; - -type ActionTypes = SetTransactionStateAction | Record; - -const general = (state: number = 0, action: ActionTypes = {}): State['txn'] => { - switch (action.type) { - case ActionType.SET_TRANSACTION: { - if (action.txn) { - return state + 1; - } - - return Math.max(0, state - 1); - } - - default: { - return state; - } - } -}; - -export default general; diff --git a/src/scripts/store/store.ts b/src/scripts/store/store.ts index cb1b33f6..177a6081 100644 --- a/src/scripts/store/store.ts +++ b/src/scripts/store/store.ts @@ -1,51 +1,109 @@ -/* eslint-disable @typescript-eslint/no-explicit-any */ -import { createStore, Store as ReduxStore, AnyAction } from 'redux'; -import { Store as IStore } from '../interfaces/store'; -import { State } from '../interfaces/state'; -import rootReducer from '../reducers/index'; -import { setTxn } from '../actions/misc'; +import { + AnyAction, + Reducer, + Store as IStore, + StoreListener, +} from '../interfaces/store'; +import { StateChangeSet, State } from '../interfaces/state'; import { ChoiceFull } from '../interfaces/choice-full'; import { GroupFull } from '../interfaces/group-full'; +import items from '../reducers/items'; +import groups from '../reducers/groups'; +import choices from '../reducers/choices'; + +type ReducerList = { [K in keyof State]: Reducer }; + +const reducers: ReducerList = { + groups, + items, + choices, +} as const; export default class Store implements IStore { - _store: ReduxStore; + _store: State = this.defaultState; - constructor() { - this._store = createStore( - rootReducer, - (window as any).__REDUX_DEVTOOLS_EXTENSION__ && - (window as any).__REDUX_DEVTOOLS_EXTENSION__(), - ); + _listeners: StoreListener[] = []; + + _txn: number = 0; + + _outstandingChanges?: StateChangeSet; + + // eslint-disable-next-line class-methods-use-this + get defaultState(): State { + return { + groups: [], + items: [], + choices: [], + }; } - /** - * Subscribe store to function call (wrapped Redux method) - */ - subscribe(onChange: () => void): void { - this._store.subscribe(onChange); + // eslint-disable-next-line class-methods-use-this + changeSet(init: boolean): StateChangeSet { + return { + groups: init, + items: init, + choices: init, + }; + } + + resetStore(): void { + this._store = this.defaultState; + const changes = this.changeSet(true); + this._listeners.forEach((l) => l(changes)); + } + + subscribe(onChange: StoreListener): void { + this._listeners.push(onChange); } - /** - * Dispatch event to store (wrapped Redux method) - */ dispatch(action: AnyAction): void { - this._store.dispatch(action); + const state = this._store; + let hasChanges = false; + const changes = this._outstandingChanges || this.changeSet(false); + + Object.keys(reducers).forEach((key: string) => { + const stateUpdate = (reducers[key] as Reducer)( + state[key], + action, + ); + if (stateUpdate.update) { + hasChanges = true; + changes[key] = true; + state[key] = stateUpdate.state; + } + }); + + if (hasChanges) { + if (this._txn) { + this._outstandingChanges = changes; + } else { + this._listeners.forEach((l) => l(changes)); + } + } } withTxn(func: () => void): void { - this._store.dispatch(setTxn(true)); + this._txn++; try { func(); } finally { - this._store.dispatch(setTxn(false)); + this._txn = Math.max(0, this._txn - 1); + + if (!this._txn) { + const changeSet = this._outstandingChanges; + if (changeSet) { + this._outstandingChanges = undefined; + this._listeners.forEach((l) => l(changeSet)); + } + } } } /** - * Get store object (wrapping Redux method) + * Get store object */ get state(): State { - return this._store.getState(); + return this._store; } /** @@ -98,11 +156,9 @@ export default class Store implements IStore { * Get active groups from store */ get activeGroups(): GroupFull[] { - const { groups, choices } = this; - - return groups.filter((group) => { + return this.state.groups.filter((group) => { const isActive = group.active && !group.disabled; - const hasActiveOptions = choices.some( + const hasActiveOptions = this.state.choices.some( (choice) => choice.active && !choice.disabled, ); @@ -111,7 +167,7 @@ export default class Store implements IStore { } inTxn(): boolean { - return this.state.txn > 0; + return this._txn > 0; } /** diff --git a/test/scripts/actions/misc.test.ts b/test/scripts/actions/misc.test.ts deleted file mode 100644 index 98da93e6..00000000 --- a/test/scripts/actions/misc.test.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { expect } from 'chai'; -import * as actions from '../../../src/scripts/actions/misc'; -import { ActionType } from '../../../src'; - -describe('actions/misc', () => { - describe('clearAll action', () => { - it('returns CLEAR_ALL action', () => { - const expectedAction: actions.ClearAllAction = { - type: ActionType.CLEAR_ALL, - }; - - expect(actions.clearAll()).to.deep.equal(expectedAction); - }); - }); - - describe('setTxn action', () => { - describe('setting paused state to true', () => { - it('returns expected action', () => { - const expectedAction: actions.SetTransactionStateAction = { - type: ActionType.SET_TRANSACTION, - txn: true, - }; - - expect(actions.setTxn(true)).to.deep.equal(expectedAction); - }); - }); - - describe('setting paused state to false', () => { - it('returns expected action', () => { - const expectedAction: actions.SetTransactionStateAction = { - type: ActionType.SET_TRANSACTION, - txn: false, - }; - - expect(actions.setTxn(false)).to.deep.equal(expectedAction); - }); - }); - }); -}); diff --git a/test/scripts/choices.test.ts b/test/scripts/choices.test.ts index c365f2ab..945e63d6 100644 --- a/test/scripts/choices.test.ts +++ b/test/scripts/choices.test.ts @@ -352,8 +352,8 @@ describe('choices', () => { expect(storeSubscribeSpy.lastCall.args[0]).to.equal(instance._render); }); - it('fires initial render', () => { - expect(renderSpy.called).to.equal(true); + it('does not fire initial render with no items or choices', () => { + expect(renderSpy.called).to.equal(false); }); it('adds event listeners', () => { @@ -633,9 +633,8 @@ describe('choices', () => { expect( passedElementTriggerEventStub.lastCall.args[0], ).to.deep.equal(EventType.showDropdown); - expect( - passedElementTriggerEventStub.lastCall.args[1], - ).to.undefined; + expect(passedElementTriggerEventStub.lastCall.args[1]).to + .undefined; done(true); }); })); @@ -737,9 +736,8 @@ describe('choices', () => { expect( passedElementTriggerEventStub.lastCall.args[0], ).to.deep.equal(EventType.hideDropdown); - expect( - passedElementTriggerEventStub.lastCall.args[1], - ).to.undefined; + expect(passedElementTriggerEventStub.lastCall.args[1]).to + .undefined; done(true); }); })); @@ -1137,31 +1135,6 @@ describe('choices', () => { }); }); - describe('clearStore', () => { - let storeDispatchStub; - - beforeEach(() => { - storeDispatchStub = stub(); - instance._store.dispatch = storeDispatchStub; - - output = instance.clearStore(); - }); - - afterEach(() => { - instance._store.dispatch.reset(); - }); - - it('returns this', () => { - expect(output).to.deep.equal(instance); - }); - - it('dispatches clearAll action', () => { - expect(storeDispatchStub.lastCall.args[0]).to.deep.equal({ - type: ActionType.CLEAR_ALL, - }); - }); - }); - describe('clearInput', () => { let inputClearSpy; let storeDispatchStub; diff --git a/test/scripts/reducers/choices.test.ts b/test/scripts/reducers/choices.test.ts index 62261ec4..b22174c6 100644 --- a/test/scripts/reducers/choices.test.ts +++ b/test/scripts/reducers/choices.test.ts @@ -3,15 +3,9 @@ import choices from '../../../src/scripts/reducers/choices'; import { cloneObject } from '../../../src/scripts/lib/utils'; import { ChoiceFull } from '../../../src/scripts/interfaces/choice-full'; import { ActionType } from '../../../src'; -import { defaultState } from '../../../src/scripts/reducers'; +import { StateUpdate } from '../../../src/scripts/interfaces/store'; describe('reducers/choices', () => { - it('should return same state when no action matches', () => { - expect(choices(defaultState.choices, {} as any)).to.equal( - defaultState.choices, - ); - }); - describe('when choices do not exist', () => { describe('ADD_CHOICE', () => { const choice: ChoiceFull = { @@ -34,9 +28,12 @@ describe('reducers/choices', () => { describe('passing expected values', () => { it('adds choice', () => { - const expectedResponse = [choice]; + const expectedResponse: StateUpdate = { + update: true, + state: [choice], + }; - const actualResponse = choices(undefined, { + const actualResponse = choices([], { type: ActionType.ADD_CHOICE, choice: cloneObject(choice), }); @@ -51,9 +48,12 @@ describe('reducers/choices', () => { const item = Object.assign(cloneObject(choice), { placeholder: false, }); - const expectedResponse = [item]; + const expectedResponse: StateUpdate = { + update: true, + state: [item], + }; - const actualResponse = choices(undefined, { + const actualResponse = choices([], { type: ActionType.ADD_CHOICE, choice: cloneObject(item), }); @@ -126,7 +126,7 @@ describe('reducers/choices', () => { rank, }, ], - }).find((choice) => choice.id === id); + }).state.find((choice) => choice.id === id); expect(actualResponse).to.deep.equal(expectedResponse); }); @@ -134,16 +134,19 @@ describe('reducers/choices', () => { describe('ACTIVATE_CHOICES', () => { it('sets active flag to passed value', () => { - const expectedResponse = [ - { - ...state[0], - active: true, - }, - { - ...state[1], - active: true, - }, - ] as ChoiceFull[]; + const expectedResponse: StateUpdate = { + update: true, + state: [ + { + ...state[0], + active: true, + }, + { + ...state[1], + active: true, + }, + ], + }; const actualResponse = choices(cloneObject(state), { type: ActionType.ACTIVATE_CHOICES, @@ -154,43 +157,21 @@ describe('reducers/choices', () => { }); }); - describe('REMOVE_CHOICE', () => { - it('the choice is removed', () => { - const choice = state[0]; - const expectedResponse = state.filter((s) => s.id !== choice.id); - - const actualResponse = choices(cloneObject(state), { - type: ActionType.REMOVE_CHOICE, - choice: cloneObject(choice), - }); - - expect(actualResponse).to.deep.equal(expectedResponse); - }); - }); - - describe('CLEAR_CHOICES', () => { - it('restores to defaultState', () => { - const expectedResponse = defaultState.choices; - const actualResponse = choices(cloneObject(state), { - type: ActionType.CLEAR_CHOICES, - }); - - expect(actualResponse).to.deep.equal(expectedResponse); - }); - }); - describe('ADD_ITEM', () => { describe('when action has a choice id', () => { it('disables choice corresponding with id', () => { - const expectedResponse = [ - { - ...state[0], - }, - { - ...state[1], - selected: true, - }, - ] as ChoiceFull[]; + const expectedResponse: StateUpdate = { + update: true, + state: [ + { + ...state[0], + }, + { + ...state[1], + selected: true, + }, + ], + }; const actualResponse = choices(cloneObject(state), { type: ActionType.ADD_ITEM, diff --git a/test/scripts/reducers/groups.test.ts b/test/scripts/reducers/groups.test.ts index d7190e33..0577541e 100644 --- a/test/scripts/reducers/groups.test.ts +++ b/test/scripts/reducers/groups.test.ts @@ -3,15 +3,9 @@ import groups from '../../../src/scripts/reducers/groups'; import { cloneObject } from '../../../src/scripts/lib/utils'; import { GroupFull } from '../../../src/scripts/interfaces/group-full'; import { ActionType } from '../../../src'; -import { defaultState } from '../../../src/scripts/reducers'; +import { StateUpdate } from '../../../src/scripts/interfaces/store'; describe('reducers/groups', () => { - it('should return same state when no action matches', () => { - expect(groups(defaultState.groups, {} as any)).to.equal( - defaultState.groups, - ); - }); - describe('when groups do not exist', () => { describe('ADD_GROUP', () => { it('adds group', () => { @@ -23,9 +17,12 @@ describe('reducers/groups', () => { choices: [], }; - const expectedResponse = [group]; + const expectedResponse: StateUpdate = { + update: true, + state: [group], + }; - const actualResponse = groups(undefined, { + const actualResponse = groups([], { type: ActionType.ADD_GROUP, group: cloneObject(group), }); @@ -34,38 +31,4 @@ describe('reducers/groups', () => { }); }); }); - - describe('when groups exist', () => { - let state: GroupFull[]; - - beforeEach(() => { - state = [ - { - id: 1, - label: 'Group one', - active: true, - disabled: false, - choices: [], - }, - { - id: 2, - label: 'Group two', - active: true, - disabled: false, - choices: [], - }, - ]; - }); - - describe('CLEAR_CHOICES', () => { - it('restores to defaultState', () => { - const expectedResponse = defaultState.groups; - const actualResponse = groups(cloneObject(state), { - type: ActionType.CLEAR_CHOICES, - }); - - expect(actualResponse).to.deep.equal(expectedResponse); - }); - }); - }); }); diff --git a/test/scripts/reducers/index.test.ts b/test/scripts/reducers/index.test.ts deleted file mode 100644 index 896041a8..00000000 --- a/test/scripts/reducers/index.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { createStore } from 'redux'; -import { expect } from 'chai'; -import rootReducer from '../../../src/scripts/reducers'; -import groups from '../../../src/scripts/reducers/groups'; -import choices from '../../../src/scripts/reducers/choices'; -import items from '../../../src/scripts/reducers/items'; -import txn from '../../../src/scripts/reducers/txn'; -import { ActionType } from '../../../src'; - -describe('reducers/rootReducer', () => { - const store = createStore(rootReducer); - - it('returns expected reducers', () => { - const state = store.getState(); - - expect(state.groups).to.deep.equal(groups(undefined, {} as any)); - expect(state.choices).to.deep.equal(choices(undefined, {} as any)); - expect(state.items).to.deep.equal(items(undefined, {} as any)); - expect(state.txn).to.deep.equal(txn(undefined, {} as any)); - }); - - describe('CLEAR_ALL', () => { - it('resets state', () => { - const output = rootReducer( - { - items: [1, 2, 3], - groups: [1, 2, 3], - choices: [1, 2, 3], - }, - { - type: ActionType.CLEAR_ALL, - }, - ); - - expect(output).to.deep.equal({ - items: [], - groups: [], - choices: [], - txn: 0, - }); - }); - }); -}); diff --git a/test/scripts/reducers/items.test.ts b/test/scripts/reducers/items.test.ts index 8311b565..ac7f30ef 100644 --- a/test/scripts/reducers/items.test.ts +++ b/test/scripts/reducers/items.test.ts @@ -4,15 +4,9 @@ import { RemoveItemAction } from '../../../src/scripts/actions/items'; import { cloneObject } from '../../../src/scripts/lib/utils'; import { ChoiceFull } from '../../../src/scripts/interfaces/choice-full'; import { ActionType } from '../../../src'; -import { defaultState } from '../../../src/scripts/reducers'; +import { StateUpdate } from '../../../src/scripts/interfaces/store'; describe('reducers/items', () => { - it('should return same state when no action matches', () => { - expect(items(defaultState.items, {} as any)).to.deep.equal( - defaultState.items, - ); - }); - describe('when items do not exist', () => { describe('ADD_ITEM', () => { const choice: ChoiceFull = { @@ -36,10 +30,10 @@ describe('reducers/items', () => { let actualResponse: ChoiceFull[]; beforeEach(() => { - actualResponse = items(undefined, { + actualResponse = items([], { type: ActionType.ADD_ITEM, item: cloneObject(choice), - }); + }).state; }); it('adds item', () => { @@ -61,9 +55,12 @@ describe('reducers/items', () => { placeholder: false, }); it('adds item with placeholder set to false', () => { - const expectedResponse = [item]; + const expectedResponse: StateUpdate = { + update: true, + state: [item], + }; - const actualResponse = items(undefined, { + const actualResponse = items([], { type: ActionType.ADD_ITEM, item: cloneObject(item), }); @@ -113,11 +110,14 @@ describe('reducers/items', () => { describe('REMOVE_ITEM', () => { it('sets an item to be inactive based on passed ID', () => { - const expectedResponse = [ - { - ...state[0], - }, - ] as ChoiceFull[]; + const expectedResponse: StateUpdate = { + update: true, + state: [ + { + ...state[0], + }, + ], + }; const actualResponse = items(cloneObject(state), { type: ActionType.REMOVE_ITEM, @@ -131,7 +131,10 @@ describe('reducers/items', () => { describe('REMOVE_CHOICE', () => { it('the item is removed', () => { const choice = state[0]; - const expectedResponse = state.filter((s) => s.id !== choice.id); + const expectedResponse: StateUpdate = { + update: true, + state: state.filter((s) => s.id !== choice.id), + }; const actualResponse = items(cloneObject(state), { type: ActionType.REMOVE_CHOICE, @@ -144,15 +147,18 @@ describe('reducers/items', () => { describe('HIGHLIGHT_ITEM', () => { it('sets an item to be inactive based on passed ID', () => { - const expectedResponse = [ - { - ...state[0], - }, - { - ...state[1], - highlighted: true, - }, - ] as ChoiceFull[]; + const expectedResponse: StateUpdate = { + update: true, + state: [ + { + ...state[0], + }, + { + ...state[1], + highlighted: true, + }, + ], + }; const actualResponse = items(cloneObject(state), { type: ActionType.HIGHLIGHT_ITEM, diff --git a/test/scripts/reducers/txn.test.ts b/test/scripts/reducers/txn.test.ts deleted file mode 100644 index 82e34592..00000000 --- a/test/scripts/reducers/txn.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { expect } from 'chai'; -import general from '../../../src/scripts/reducers/txn'; -import { ActionType, State } from '../../../src'; -import { defaultState } from '../../../src/scripts/reducers'; - -describe('reducers/txn', () => { - it('should return same state when no action matches', () => { - expect(general(defaultState.txn, {} as any)).to.equal(defaultState.txn); - }); - - describe('SET_TRANSACTION', () => { - it('sets transaction state', () => { - const expectedState: State['txn'] = 1; - - const actualState = general(undefined, { - type: ActionType.SET_TRANSACTION, - txn: true, - }); - - expect(expectedState).to.deep.equal(actualState); - }); - }); -}); diff --git a/test/scripts/store/store.test.ts b/test/scripts/store/store.test.ts index 1a7922e4..299dd806 100644 --- a/test/scripts/store/store.test.ts +++ b/test/scripts/store/store.test.ts @@ -1,21 +1,24 @@ import { expect } from 'chai'; import sinon from 'sinon'; -import { AnyAction, Unsubscribe } from 'redux'; import Store from '../../../src/scripts/store/store'; -import { State } from '../../../src'; +import { ActionType, State } from '../../../src'; import { cloneObject } from '../../../src/scripts/lib/utils'; +import { + AnyAction, + StoreListener, +} from '../../../src/scripts/interfaces/store'; describe('reducers/store', () => { let instance: Store; - let subscribeStub: sinon.SinonStub<[listener: () => void], Unsubscribe>; - let dispatchStub: sinon.SinonStub<[action: AnyAction], AnyAction>; - let getStateStub: sinon.SinonStub<[], State>; + let subscribeStub: sinon.SinonStub<[listener: StoreListener], void>; + let dispatchStub: sinon.SinonStub<[action: AnyAction], void>; + let getStateStub: sinon.SinonStub; beforeEach(() => { instance = new Store(); - subscribeStub = sinon.stub(instance._store, 'subscribe'); - dispatchStub = sinon.stub(instance._store, 'dispatch'); - getStateStub = sinon.stub(instance._store, 'getState'); + subscribeStub = sinon.stub(instance, 'subscribe'); + dispatchStub = sinon.stub(instance, 'dispatch'); + getStateStub = sinon.stub(instance, 'state'); }); afterEach(() => { @@ -25,17 +28,13 @@ describe('reducers/store', () => { }); describe('constructor', () => { - it('creates redux store', () => { - expect(instance._store).to.contain.keys([ - 'subscribe', - 'dispatch', - 'getState', - ]); + it('creates redux-like store', () => { + expect(instance).to.contain.keys(['_store', '_listeners', '_txn']); }); }); describe('subscribe', () => { - it('wraps redux subscribe method', () => { + it('wraps redux-like subscribe method', () => { const onChange = (): void => {}; expect(subscribeStub.callCount).to.equal(0); instance.subscribe(onChange); @@ -45,8 +44,8 @@ describe('reducers/store', () => { }); describe('dispatch', () => { - it('wraps redux dispatch method', () => { - const action = { type: 'TEST_ACTION' }; + it('wraps redux-like dispatch method', () => { + const action: AnyAction = { type: ActionType.CLEAR_CHOICES }; expect(dispatchStub.callCount).to.equal(0); instance.dispatch(action); expect(dispatchStub.callCount).to.equal(1); @@ -56,8 +55,8 @@ describe('reducers/store', () => { describe('state getter', () => { it('returns state', () => { - const state: State = { items: [], choices: [], groups: [], txn: 0 }; - getStateStub.returns(cloneObject(state)); + const state: State = { items: [], choices: [], groups: [] }; + getStateStub.value(cloneObject(state)); expect(instance.state).to.deep.equal(state); }); @@ -68,7 +67,6 @@ describe('reducers/store', () => { beforeEach(() => { state = { - txn: 0, items: [ { id: 1, @@ -163,7 +161,7 @@ describe('reducers/store', () => { ], }; - getStateStub.returns(state); + getStateStub.value(state); }); describe('items getter', () => {