UNPKG

choices-vue3

Version:

[![npm version](https://img.shields.io/npm/v/choices-vue3.svg)](https://www.npmjs.com/package/choices-vue3) [![npm downloads](https://img.shields.io/npm/dm/choices-vue3.svg)](https://www.npmjs.com/package/choices-vue3) [![Vue 3 Compatible](https://img.shi

1,662 lines (1,661 loc) 170 kB
import { defineComponent, ref, watch, onMounted, onBeforeUnmount, nextTick } from "vue"; /*! choices.js v11.1.0 | © 2025 Josh Johnson | https://github.com/jshjohnson/Choices#readme */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { d2.__proto__ = b2; } || function(d2, b2) { for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign2(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __spreadArray(to, from, pack) { for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; var ActionType = { ADD_CHOICE: "ADD_CHOICE", REMOVE_CHOICE: "REMOVE_CHOICE", FILTER_CHOICES: "FILTER_CHOICES", ACTIVATE_CHOICES: "ACTIVATE_CHOICES", CLEAR_CHOICES: "CLEAR_CHOICES", ADD_GROUP: "ADD_GROUP", ADD_ITEM: "ADD_ITEM", REMOVE_ITEM: "REMOVE_ITEM", HIGHLIGHT_ITEM: "HIGHLIGHT_ITEM" }; var EventType = { showDropdown: "showDropdown", hideDropdown: "hideDropdown", change: "change", choice: "choice", search: "search", addItem: "addItem", removeItem: "removeItem", highlightItem: "highlightItem", highlightChoice: "highlightChoice", unhighlightItem: "unhighlightItem" }; var KeyCodeMap = { TAB_KEY: 9, SHIFT_KEY: 16, BACK_KEY: 46, DELETE_KEY: 8, ENTER_KEY: 13, A_KEY: 65, ESC_KEY: 27, UP_KEY: 38, DOWN_KEY: 40, PAGE_UP_KEY: 33, PAGE_DOWN_KEY: 34 }; var ObjectsInConfig = ["fuseOptions", "classNames"]; var PassedElementTypes = { Text: "text", SelectOne: "select-one", SelectMultiple: "select-multiple" }; var addChoice = function(choice) { return { type: ActionType.ADD_CHOICE, choice }; }; var removeChoice = function(choice) { return { type: ActionType.REMOVE_CHOICE, choice }; }; var filterChoices = function(results) { return { type: ActionType.FILTER_CHOICES, results }; }; var activateChoices = function(active) { return { type: ActionType.ACTIVATE_CHOICES, active }; }; var addGroup = function(group) { return { type: ActionType.ADD_GROUP, group }; }; var addItem = function(item) { return { type: ActionType.ADD_ITEM, item }; }; var removeItem$1 = function(item) { return { type: ActionType.REMOVE_ITEM, item }; }; var highlightItem = function(item, highlighted) { return { type: ActionType.HIGHLIGHT_ITEM, item, highlighted }; }; var getRandomNumber = function(min, max) { return Math.floor(Math.random() * (max - min) + min); }; var generateChars = function(length) { return Array.from({ length }, function() { return getRandomNumber(0, 36).toString(36); }).join(""); }; var generateId = function(element, prefix) { var id = element.id || element.name && "".concat(element.name, "-").concat(generateChars(2)) || generateChars(4); id = id.replace(/(:|\.|\[|\]|,)/g, ""); id = "".concat(prefix, "-").concat(id); return id; }; var getAdjacentEl = function(startEl, selector, direction) { if (direction === void 0) { direction = 1; } var prop = "".concat(direction > 0 ? "next" : "previous", "ElementSibling"); var sibling = startEl[prop]; while (sibling) { if (sibling.matches(selector)) { return sibling; } sibling = sibling[prop]; } return null; }; var isScrolledIntoView = function(element, parent, direction) { if (direction === void 0) { direction = 1; } var isVisible; if (direction > 0) { isVisible = parent.scrollTop + parent.offsetHeight >= element.offsetTop + element.offsetHeight; } else { isVisible = element.offsetTop >= parent.scrollTop; } return isVisible; }; var sanitise = function(value) { if (typeof value !== "string") { if (value === null || value === void 0) { return ""; } if (typeof value === "object") { if ("raw" in value) { return sanitise(value.raw); } if ("trusted" in value) { return value.trusted; } } return value; } return value.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/'/g, "&#039;").replace(/"/g, "&quot;"); }; var strToEl = function() { var tmpEl = document.createElement("div"); return function(str) { tmpEl.innerHTML = str.trim(); var firstChild = tmpEl.children[0]; while (tmpEl.firstChild) { tmpEl.removeChild(tmpEl.firstChild); } return firstChild; }; }(); var resolveNoticeFunction = function(fn, value) { return typeof fn === "function" ? fn(sanitise(value), value) : fn; }; var resolveStringFunction = function(fn) { return typeof fn === "function" ? fn() : fn; }; var unwrapStringForRaw = function(s) { if (typeof s === "string") { return s; } if (typeof s === "object") { if ("trusted" in s) { return s.trusted; } if ("raw" in s) { return s.raw; } } return ""; }; var unwrapStringForEscaped = function(s) { if (typeof s === "string") { return s; } if (typeof s === "object") { if ("escaped" in s) { return s.escaped; } if ("trusted" in s) { return s.trusted; } } return ""; }; var escapeForTemplate = function(allowHTML, s) { return allowHTML ? unwrapStringForEscaped(s) : sanitise(s); }; var setElementHtml = function(el, allowHtml, html) { el.innerHTML = escapeForTemplate(allowHtml, html); }; var sortByAlpha = function(_a, _b) { var value = _a.value, _c = _a.label, label = _c === void 0 ? value : _c; var value2 = _b.value, _d = _b.label, label2 = _d === void 0 ? value2 : _d; return unwrapStringForRaw(label).localeCompare(unwrapStringForRaw(label2), [], { sensitivity: "base", ignorePunctuation: true, numeric: true }); }; var sortByRank = function(a, b) { return a.rank - b.rank; }; var dispatchEvent = function(element, type, customArgs) { if (customArgs === void 0) { customArgs = null; } var event = new CustomEvent(type, { detail: customArgs, bubbles: true, cancelable: true }); return element.dispatchEvent(event); }; var diff = function(a, b) { var aKeys = Object.keys(a).sort(); var bKeys = Object.keys(b).sort(); return aKeys.filter(function(i) { return bKeys.indexOf(i) < 0; }); }; var getClassNames = function(ClassNames) { return Array.isArray(ClassNames) ? ClassNames : [ClassNames]; }; var getClassNamesSelector = function(option) { if (option && Array.isArray(option)) { return option.map(function(item) { return ".".concat(item); }).join(""); } return ".".concat(option); }; var addClassesToElement = function(element, className) { var _a; (_a = element.classList).add.apply(_a, getClassNames(className)); }; var removeClassesFromElement = function(element, className) { var _a; (_a = element.classList).remove.apply(_a, getClassNames(className)); }; var parseCustomProperties = function(customProperties) { if (typeof customProperties !== "undefined") { try { return JSON.parse(customProperties); } catch (e) { return customProperties; } } return {}; }; var updateClassList = function(item, add, remove) { var itemEl = item.itemEl; if (itemEl) { removeClassesFromElement(itemEl, remove); addClassesToElement(itemEl, add); } }; var Dropdown = ( /** @class */ function() { function Dropdown2(_a) { var element = _a.element, type = _a.type, classNames = _a.classNames; this.element = element; this.classNames = classNames; this.type = type; this.isActive = false; } Dropdown2.prototype.show = function() { addClassesToElement(this.element, this.classNames.activeState); this.element.setAttribute("aria-expanded", "true"); this.isActive = true; return this; }; Dropdown2.prototype.hide = function() { removeClassesFromElement(this.element, this.classNames.activeState); this.element.setAttribute("aria-expanded", "false"); this.isActive = false; return this; }; return Dropdown2; }() ); var Container = ( /** @class */ function() { function Container2(_a) { var element = _a.element, type = _a.type, classNames = _a.classNames, position = _a.position; this.element = element; this.classNames = classNames; this.type = type; this.position = position; this.isOpen = false; this.isFlipped = false; this.isDisabled = false; this.isLoading = false; } Container2.prototype.shouldFlip = function(dropdownPos, dropdownHeight) { var shouldFlip = false; if (this.position === "auto") { shouldFlip = this.element.getBoundingClientRect().top - dropdownHeight >= 0 && !window.matchMedia("(min-height: ".concat(dropdownPos + 1, "px)")).matches; } else if (this.position === "top") { shouldFlip = true; } return shouldFlip; }; Container2.prototype.setActiveDescendant = function(activeDescendantID) { this.element.setAttribute("aria-activedescendant", activeDescendantID); }; Container2.prototype.removeActiveDescendant = function() { this.element.removeAttribute("aria-activedescendant"); }; Container2.prototype.open = function(dropdownPos, dropdownHeight) { addClassesToElement(this.element, this.classNames.openState); this.element.setAttribute("aria-expanded", "true"); this.isOpen = true; if (this.shouldFlip(dropdownPos, dropdownHeight)) { addClassesToElement(this.element, this.classNames.flippedState); this.isFlipped = true; } }; Container2.prototype.close = function() { removeClassesFromElement(this.element, this.classNames.openState); this.element.setAttribute("aria-expanded", "false"); this.removeActiveDescendant(); this.isOpen = false; if (this.isFlipped) { removeClassesFromElement(this.element, this.classNames.flippedState); this.isFlipped = false; } }; Container2.prototype.addFocusState = function() { addClassesToElement(this.element, this.classNames.focusState); }; Container2.prototype.removeFocusState = function() { removeClassesFromElement(this.element, this.classNames.focusState); }; Container2.prototype.enable = function() { removeClassesFromElement(this.element, this.classNames.disabledState); this.element.removeAttribute("aria-disabled"); if (this.type === PassedElementTypes.SelectOne) { this.element.setAttribute("tabindex", "0"); } this.isDisabled = false; }; Container2.prototype.disable = function() { addClassesToElement(this.element, this.classNames.disabledState); this.element.setAttribute("aria-disabled", "true"); if (this.type === PassedElementTypes.SelectOne) { this.element.setAttribute("tabindex", "-1"); } this.isDisabled = true; }; Container2.prototype.wrap = function(element) { var el = this.element; var parentNode = element.parentNode; if (parentNode) { if (element.nextSibling) { parentNode.insertBefore(el, element.nextSibling); } else { parentNode.appendChild(el); } } el.appendChild(element); }; Container2.prototype.unwrap = function(element) { var el = this.element; var parentNode = el.parentNode; if (parentNode) { parentNode.insertBefore(element, el); parentNode.removeChild(el); } }; Container2.prototype.addLoadingState = function() { addClassesToElement(this.element, this.classNames.loadingState); this.element.setAttribute("aria-busy", "true"); this.isLoading = true; }; Container2.prototype.removeLoadingState = function() { removeClassesFromElement(this.element, this.classNames.loadingState); this.element.removeAttribute("aria-busy"); this.isLoading = false; }; return Container2; }() ); var Input = ( /** @class */ function() { function Input2(_a) { var element = _a.element, type = _a.type, classNames = _a.classNames, preventPaste = _a.preventPaste; this.element = element; this.type = type; this.classNames = classNames; this.preventPaste = preventPaste; this.isFocussed = this.element.isEqualNode(document.activeElement); this.isDisabled = element.disabled; this._onPaste = this._onPaste.bind(this); this._onInput = this._onInput.bind(this); this._onFocus = this._onFocus.bind(this); this._onBlur = this._onBlur.bind(this); } Object.defineProperty(Input2.prototype, "placeholder", { set: function(placeholder) { this.element.placeholder = placeholder; }, enumerable: false, configurable: true }); Object.defineProperty(Input2.prototype, "value", { get: function() { return this.element.value; }, set: function(value) { this.element.value = value; }, enumerable: false, configurable: true }); Input2.prototype.addEventListeners = function() { var el = this.element; el.addEventListener("paste", this._onPaste); el.addEventListener("input", this._onInput, { passive: true }); el.addEventListener("focus", this._onFocus, { passive: true }); el.addEventListener("blur", this._onBlur, { passive: true }); }; Input2.prototype.removeEventListeners = function() { var el = this.element; el.removeEventListener("input", this._onInput); el.removeEventListener("paste", this._onPaste); el.removeEventListener("focus", this._onFocus); el.removeEventListener("blur", this._onBlur); }; Input2.prototype.enable = function() { var el = this.element; el.removeAttribute("disabled"); this.isDisabled = false; }; Input2.prototype.disable = function() { var el = this.element; el.setAttribute("disabled", ""); this.isDisabled = true; }; Input2.prototype.focus = function() { if (!this.isFocussed) { this.element.focus(); } }; Input2.prototype.blur = function() { if (this.isFocussed) { this.element.blur(); } }; Input2.prototype.clear = function(setWidth) { if (setWidth === void 0) { setWidth = true; } this.element.value = ""; if (setWidth) { this.setWidth(); } return this; }; Input2.prototype.setWidth = function() { var element = this.element; element.style.minWidth = "".concat(element.placeholder.length + 1, "ch"); element.style.width = "".concat(element.value.length + 1, "ch"); }; Input2.prototype.setActiveDescendant = function(activeDescendantID) { this.element.setAttribute("aria-activedescendant", activeDescendantID); }; Input2.prototype.removeActiveDescendant = function() { this.element.removeAttribute("aria-activedescendant"); }; Input2.prototype._onInput = function() { if (this.type !== PassedElementTypes.SelectOne) { this.setWidth(); } }; Input2.prototype._onPaste = function(event) { if (this.preventPaste) { event.preventDefault(); } }; Input2.prototype._onFocus = function() { this.isFocussed = true; }; Input2.prototype._onBlur = function() { this.isFocussed = false; }; return Input2; }() ); var SCROLLING_SPEED = 4; var List = ( /** @class */ function() { function List2(_a) { var element = _a.element; this.element = element; this.scrollPos = this.element.scrollTop; this.height = this.element.offsetHeight; } List2.prototype.prepend = function(node) { var child = this.element.firstElementChild; if (child) { this.element.insertBefore(node, child); } else { this.element.append(node); } }; List2.prototype.scrollToTop = function() { this.element.scrollTop = 0; }; List2.prototype.scrollToChildElement = function(element, direction) { var _this = this; if (!element) { return; } var listHeight = this.element.offsetHeight; var listScrollPosition = this.element.scrollTop + listHeight; var elementHeight = element.offsetHeight; var elementPos = element.offsetTop + elementHeight; var destination = direction > 0 ? this.element.scrollTop + elementPos - listScrollPosition : element.offsetTop; requestAnimationFrame(function() { _this._animateScroll(destination, direction); }); }; List2.prototype._scrollDown = function(scrollPos, strength, destination) { var easing = (destination - scrollPos) / strength; var distance = easing > 1 ? easing : 1; this.element.scrollTop = scrollPos + distance; }; List2.prototype._scrollUp = function(scrollPos, strength, destination) { var easing = (scrollPos - destination) / strength; var distance = easing > 1 ? easing : 1; this.element.scrollTop = scrollPos - distance; }; List2.prototype._animateScroll = function(destination, direction) { var _this = this; var strength = SCROLLING_SPEED; var choiceListScrollTop = this.element.scrollTop; var continueAnimation = false; if (direction > 0) { this._scrollDown(choiceListScrollTop, strength, destination); if (choiceListScrollTop < destination) { continueAnimation = true; } } else { this._scrollUp(choiceListScrollTop, strength, destination); if (choiceListScrollTop > destination) { continueAnimation = true; } } if (continueAnimation) { requestAnimationFrame(function() { _this._animateScroll(destination, direction); }); } }; return List2; }() ); var WrappedElement = ( /** @class */ function() { function WrappedElement2(_a) { var element = _a.element, classNames = _a.classNames; this.element = element; this.classNames = classNames; this.isDisabled = false; } Object.defineProperty(WrappedElement2.prototype, "isActive", { get: function() { return this.element.dataset.choice === "active"; }, enumerable: false, configurable: true }); Object.defineProperty(WrappedElement2.prototype, "dir", { get: function() { return this.element.dir; }, enumerable: false, configurable: true }); Object.defineProperty(WrappedElement2.prototype, "value", { get: function() { return this.element.value; }, set: function(value) { this.element.setAttribute("value", value); this.element.value = value; }, enumerable: false, configurable: true }); WrappedElement2.prototype.conceal = function() { var el = this.element; addClassesToElement(el, this.classNames.input); el.hidden = true; el.tabIndex = -1; var origStyle = el.getAttribute("style"); if (origStyle) { el.setAttribute("data-choice-orig-style", origStyle); } el.setAttribute("data-choice", "active"); }; WrappedElement2.prototype.reveal = function() { var el = this.element; removeClassesFromElement(el, this.classNames.input); el.hidden = false; el.removeAttribute("tabindex"); var origStyle = el.getAttribute("data-choice-orig-style"); if (origStyle) { el.removeAttribute("data-choice-orig-style"); el.setAttribute("style", origStyle); } else { el.removeAttribute("style"); } el.removeAttribute("data-choice"); }; WrappedElement2.prototype.enable = function() { this.element.removeAttribute("disabled"); this.element.disabled = false; this.isDisabled = false; }; WrappedElement2.prototype.disable = function() { this.element.setAttribute("disabled", ""); this.element.disabled = true; this.isDisabled = true; }; WrappedElement2.prototype.triggerEvent = function(eventType, data) { dispatchEvent(this.element, eventType, data || {}); }; return WrappedElement2; }() ); var WrappedInput = ( /** @class */ function(_super) { __extends(WrappedInput2, _super); function WrappedInput2() { return _super !== null && _super.apply(this, arguments) || this; } return WrappedInput2; }(WrappedElement) ); var coerceBool = function(arg, defaultValue) { if (defaultValue === void 0) { defaultValue = true; } return typeof arg === "undefined" ? defaultValue : !!arg; }; var stringToHtmlClass = function(input) { if (typeof input === "string") { input = input.split(" ").filter(function(s) { return s.length; }); } if (Array.isArray(input) && input.length) { return input; } return void 0; }; var mapInputToChoice = function(value, allowGroup, allowRawString) { if (allowRawString === void 0) { allowRawString = true; } if (typeof value === "string") { var sanitisedValue = sanitise(value); var userValue = allowRawString || sanitisedValue === value ? value : { escaped: sanitisedValue, raw: value }; var result_1 = mapInputToChoice({ value, label: userValue, selected: true }, false); return result_1; } var groupOrChoice = value; if ("choices" in groupOrChoice) { if (!allowGroup) { throw new TypeError("optGroup is not allowed"); } var group = groupOrChoice; var choices2 = group.choices.map(function(e) { return mapInputToChoice(e, false); }); var result_2 = { id: 0, // actual ID will be assigned during _addGroup label: unwrapStringForRaw(group.label) || group.value, active: !!choices2.length, disabled: !!group.disabled, choices: choices2 }; return result_2; } var choice = groupOrChoice; var result = { id: 0, // actual ID will be assigned during _addChoice group: null, // actual group will be assigned during _addGroup but before _addChoice score: 0, // used in search rank: 0, // used in search, stable sort order value: choice.value, label: choice.label || choice.value, active: coerceBool(choice.active), selected: coerceBool(choice.selected, false), disabled: coerceBool(choice.disabled, false), placeholder: coerceBool(choice.placeholder, false), highlighted: false, labelClass: stringToHtmlClass(choice.labelClass), labelDescription: choice.labelDescription, customProperties: choice.customProperties }; return result; }; var isHtmlInputElement = function(e) { return e.tagName === "INPUT"; }; var isHtmlSelectElement = function(e) { return e.tagName === "SELECT"; }; var isHtmlOption = function(e) { return e.tagName === "OPTION"; }; var isHtmlOptgroup = function(e) { return e.tagName === "OPTGROUP"; }; var WrappedSelect = ( /** @class */ function(_super) { __extends(WrappedSelect2, _super); function WrappedSelect2(_a) { var element = _a.element, classNames = _a.classNames, template = _a.template, extractPlaceholder = _a.extractPlaceholder; var _this = _super.call(this, { element, classNames }) || this; _this.template = template; _this.extractPlaceholder = extractPlaceholder; return _this; } Object.defineProperty(WrappedSelect2.prototype, "placeholderOption", { get: function() { return this.element.querySelector('option[value=""]') || // Backward compatibility layer for the non-standard placeholder attribute supported in older versions. this.element.querySelector("option[placeholder]"); }, enumerable: false, configurable: true }); WrappedSelect2.prototype.addOptions = function(choices2) { var _this = this; var fragment = document.createDocumentFragment(); choices2.forEach(function(obj) { var choice = obj; if (choice.element) { return; } var option = _this.template(choice); fragment.appendChild(option); choice.element = option; }); this.element.appendChild(fragment); }; WrappedSelect2.prototype.optionsAsChoices = function() { var _this = this; var choices2 = []; this.element.querySelectorAll(":scope > option, :scope > optgroup").forEach(function(e) { if (isHtmlOption(e)) { choices2.push(_this._optionToChoice(e)); } else if (isHtmlOptgroup(e)) { choices2.push(_this._optgroupToChoice(e)); } }); return choices2; }; WrappedSelect2.prototype._optionToChoice = function(option) { if (!option.hasAttribute("value") && option.hasAttribute("placeholder")) { option.setAttribute("value", ""); option.value = ""; } return { id: 0, group: null, score: 0, rank: 0, value: option.value, // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option // This attribute is text for the label indicating the meaning of the option. If the `label` attribute isn't defined, its value is that of the element text content (ie `innerText`). label: option.label, element: option, active: true, // this returns true if nothing is selected on initial load, which will break placeholder support selected: this.extractPlaceholder ? option.selected : option.hasAttribute("selected"), disabled: option.disabled, highlighted: false, placeholder: this.extractPlaceholder && (!option.value || option.hasAttribute("placeholder")), labelClass: typeof option.dataset.labelClass !== "undefined" ? stringToHtmlClass(option.dataset.labelClass) : void 0, labelDescription: typeof option.dataset.labelDescription !== "undefined" ? option.dataset.labelDescription : void 0, customProperties: parseCustomProperties(option.dataset.customProperties) }; }; WrappedSelect2.prototype._optgroupToChoice = function(optgroup) { var _this = this; var options = optgroup.querySelectorAll("option"); var choices2 = Array.from(options).map(function(option) { return _this._optionToChoice(option); }); return { id: 0, label: optgroup.label || "", element: optgroup, active: !!choices2.length, disabled: optgroup.disabled, choices: choices2 }; }; return WrappedSelect2; }(WrappedElement) ); var DEFAULT_CLASSNAMES = { containerOuter: ["choices"], containerInner: ["choices__inner"], input: ["choices__input"], inputCloned: ["choices__input--cloned"], list: ["choices__list"], listItems: ["choices__list--multiple"], listSingle: ["choices__list--single"], listDropdown: ["choices__list--dropdown"], item: ["choices__item"], itemSelectable: ["choices__item--selectable"], itemDisabled: ["choices__item--disabled"], itemChoice: ["choices__item--choice"], 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"], notice: ["choices__notice"], addChoice: ["choices__item--selectable", "add-choice"], noResults: ["has-no-results"], noChoices: ["has-no-choices"] }; var DEFAULT_CONFIG = { items: [], choices: [], silent: false, renderChoiceLimit: -1, maxItemCount: -1, closeDropdownOnSelect: "auto", singleModeForMultiSelect: false, addChoices: false, addItems: true, addItemFilter: function(value) { return !!value && value !== ""; }, removeItems: true, removeItemButton: false, removeItemButtonAlignLeft: false, editItems: false, allowHTML: false, allowHtmlUserInput: false, duplicateItemsAllowed: true, delimiter: ",", paste: true, searchEnabled: true, searchChoices: true, searchFloor: 1, searchResultLimit: 4, searchFields: ["label", "value"], position: "auto", resetScrollPosition: true, shouldSort: true, shouldSortItems: false, sorter: sortByAlpha, shadowRoot: null, placeholder: true, placeholderValue: null, searchPlaceholderValue: null, prependValue: null, appendValue: null, renderSelectedChoices: "auto", loadingText: "Loading...", noResultsText: "No results found", noChoicesText: "No choices to choose from", itemSelectText: "Press to select", uniqueItemText: "Only unique values can be added", customAddItemText: "Only values matching specific conditions can be added", addItemText: function(value) { return 'Press Enter to add <b>"'.concat(value, '"</b>'); }, removeItemIconText: function() { return "Remove item"; }, removeItemLabelText: function(value) { return "Remove item: ".concat(value); }, maxItemText: function(maxItemCount) { return "Only ".concat(maxItemCount, " values can be added"); }, valueComparer: function(value1, value2) { return value1 === value2; }, fuseOptions: { includeScore: true }, labelId: "", callbackOnInit: null, callbackOnCreateTemplates: null, classNames: DEFAULT_CLASSNAMES, appendGroupInSearch: false }; var removeItem = function(item) { var itemEl = item.itemEl; if (itemEl) { itemEl.remove(); item.itemEl = void 0; } }; function items(s, action, context) { var state = s; var update = true; switch (action.type) { case ActionType.ADD_ITEM: { action.item.selected = true; var el = action.item.element; if (el) { el.selected = true; el.setAttribute("selected", ""); } state.push(action.item); break; } case ActionType.REMOVE_ITEM: { action.item.selected = false; var el = action.item.element; if (el) { el.selected = false; el.removeAttribute("selected"); var select = el.parentElement; if (select && isHtmlSelectElement(select) && select.type === PassedElementTypes.SelectOne) { select.value = ""; } } removeItem(action.item); state = state.filter(function(choice) { return choice.id !== action.item.id; }); break; } case ActionType.REMOVE_CHOICE: { removeItem(action.choice); state = state.filter(function(item2) { return item2.id !== action.choice.id; }); break; } case ActionType.HIGHLIGHT_ITEM: { var highlighted = action.highlighted; var item = state.find(function(obj) { return obj.id === action.item.id; }); if (item && item.highlighted !== highlighted) { item.highlighted = highlighted; if (context) { updateClassList(item, highlighted ? context.classNames.highlightedState : context.classNames.selectedState, highlighted ? context.classNames.selectedState : context.classNames.highlightedState); } } break; } default: { update = false; break; } } return { state, update }; } function groups(s, action) { var state = s; var update = true; switch (action.type) { case ActionType.ADD_GROUP: { state.push(action.group); break; } case ActionType.CLEAR_CHOICES: { state = []; break; } default: { update = false; break; } } return { state, update }; } function choices(s, action, context) { var state = s; var update = true; switch (action.type) { case ActionType.ADD_CHOICE: { state.push(action.choice); break; } case ActionType.REMOVE_CHOICE: { action.choice.choiceEl = void 0; if (action.choice.group) { action.choice.group.choices = action.choice.group.choices.filter(function(obj) { return obj.id !== action.choice.id; }); } state = state.filter(function(obj) { return obj.id !== action.choice.id; }); break; } case ActionType.ADD_ITEM: case ActionType.REMOVE_ITEM: { action.item.choiceEl = void 0; break; } case ActionType.FILTER_CHOICES: { var scoreLookup_1 = []; action.results.forEach(function(result) { scoreLookup_1[result.item.id] = result; }); state.forEach(function(choice) { var result = scoreLookup_1[choice.id]; if (result !== void 0) { choice.score = result.score; choice.rank = result.rank; choice.active = true; } else { choice.score = 0; choice.rank = 0; choice.active = false; } if (context && context.appendGroupInSearch) { choice.choiceEl = void 0; } }); break; } case ActionType.ACTIVATE_CHOICES: { state.forEach(function(choice) { choice.active = action.active; if (context && context.appendGroupInSearch) { choice.choiceEl = void 0; } }); break; } case ActionType.CLEAR_CHOICES: { state = []; break; } default: { update = false; break; } } return { state, update }; } var reducers = { groups, items, choices }; var Store = ( /** @class */ function() { function Store2(context) { this._state = this.defaultState; this._listeners = []; this._txn = 0; this._context = context; } Object.defineProperty(Store2.prototype, "defaultState", { // eslint-disable-next-line class-methods-use-this get: function() { return { groups: [], items: [], choices: [] }; }, enumerable: false, configurable: true }); Store2.prototype.changeSet = function(init) { return { groups: init, items: init, choices: init }; }; Store2.prototype.reset = function() { this._state = this.defaultState; var changes = this.changeSet(true); if (this._txn) { this._changeSet = changes; } else { this._listeners.forEach(function(l) { return l(changes); }); } }; Store2.prototype.subscribe = function(onChange) { this._listeners.push(onChange); return this; }; Store2.prototype.dispatch = function(action) { var _this = this; var state = this._state; var hasChanges = false; var changes = this._changeSet || this.changeSet(false); Object.keys(reducers).forEach(function(key) { var stateUpdate = reducers[key](state[key], action, _this._context); if (stateUpdate.update) { hasChanges = true; changes[key] = true; state[key] = stateUpdate.state; } }); if (hasChanges) { if (this._txn) { this._changeSet = changes; } else { this._listeners.forEach(function(l) { return l(changes); }); } } }; Store2.prototype.withTxn = function(func) { this._txn++; try { func(); } finally { this._txn = Math.max(0, this._txn - 1); if (!this._txn) { var changeSet_1 = this._changeSet; if (changeSet_1) { this._changeSet = void 0; this._listeners.forEach(function(l) { return l(changeSet_1); }); } } } }; Object.defineProperty(Store2.prototype, "state", { /** * Get store object */ get: function() { return this._state; }, enumerable: false, configurable: true }); Object.defineProperty(Store2.prototype, "items", { /** * Get items from store */ get: function() { return this.state.items; }, enumerable: false, configurable: true }); Object.defineProperty(Store2.prototype, "highlightedActiveItems", { /** * Get highlighted items from store */ get: function() { return this.items.filter(function(item) { return item.active && item.highlighted; }); }, enumerable: false, configurable: true }); Object.defineProperty(Store2.prototype, "choices", { /** * Get choices from store */ get: function() { return this.state.choices; }, enumerable: false, configurable: true }); Object.defineProperty(Store2.prototype, "activeChoices", { /** * Get active choices from store */ get: function() { return this.choices.filter(function(choice) { return choice.active; }); }, enumerable: false, configurable: true }); Object.defineProperty(Store2.prototype, "searchableChoices", { /** * Get choices that can be searched (excluding placeholders or disabled choices) */ get: function() { return this.choices.filter(function(choice) { return !choice.disabled && !choice.placeholder; }); }, enumerable: false, configurable: true }); Object.defineProperty(Store2.prototype, "groups", { /** * Get groups from store */ get: function() { return this.state.groups; }, enumerable: false, configurable: true }); Object.defineProperty(Store2.prototype, "activeGroups", { /** * Get active groups from store */ get: function() { var _this = this; return this.state.groups.filter(function(group) { var isActive = group.active && !group.disabled; var hasActiveOptions = _this.state.choices.some(function(choice) { return choice.active && !choice.disabled; }); return isActive && hasActiveOptions; }, []); }, enumerable: false, configurable: true }); Store2.prototype.inTxn = function() { return this._txn > 0; }; Store2.prototype.getChoiceById = function(id) { return this.activeChoices.find(function(choice) { return choice.id === id; }); }; Store2.prototype.getGroupById = function(id) { return this.groups.find(function(group) { return group.id === id; }); }; return Store2; }() ); var NoticeTypes = { noChoices: "no-choices", noResults: "no-results", addChoice: "add-choice", generic: "" }; function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function(r2) { return Object.getOwnPropertyDescriptor(e, r2).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function(r2) { _defineProperty(e, r2, t[r2]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r2) { Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2)); }); } return e; } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function isArray(value) { return !Array.isArray ? getTag(value) === "[object Array]" : Array.isArray(value); } function baseToString(value) { if (typeof value == "string") { return value; } let result = value + ""; return result == "0" && 1 / value == -Infinity ? "-0" : result; } function toString(value) { return value == null ? "" : baseToString(value); } function isString(value) { return typeof value === "string"; } function isNumber(value) { return typeof value === "number"; } function isBoolean(value) { return value === true || value === false || isObjectLike(value) && getTag(value) == "[object Boolean]"; } function isObject(value) { return typeof value === "object"; } function isObjectLike(value) { return isObject(value) && value !== null; } function isDefined(value) { return value !== void 0 && value !== null; } function isBlank(value) { return !value.trim().length; } function getTag(value) { return value == null ? value === void 0 ? "[object Undefined]" : "[object Null]" : Object.prototype.toString.call(value); } const INCORRECT_INDEX_TYPE = "Incorrect 'index' type"; const LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY = (key) => `Invalid value for key ${key}`; const PATTERN_LENGTH_TOO_LARGE = (max) => `Pattern length exceeds max of ${max}.`; const MISSING_KEY_PROPERTY = (name) => `Missing ${name} property in key`; const INVALID_KEY_WEIGHT_VALUE = (key) => `Property 'weight' in key '${key}' must be a positive integer`; const hasOwn = Object.prototype.hasOwnProperty; class KeyStore { constructor(keys) { this._keys = []; this._keyMap = {}; let totalWeight = 0; keys.forEach((key) => { let obj = createKey(key); this._keys.push(obj); this._keyMap[obj.id] = obj; totalWeight += obj.weight; }); this._keys.forEach((key) => { key.weight /= totalWeight; }); } get(keyId) { return this._keyMap[keyId]; } keys() { return this._keys; } toJSON() { return JSON.stringify(this._keys); } } function createKey(key) { let path = null; let id = null; let src = null; let weight = 1; let getFn = null; if (isString(key) || isArray(key)) { src = key; path = createKeyPath(key); id = createKeyId(key); } else { if (!hasOwn.call(key, "name")) { throw new Error(MISSING_KEY_PROPERTY("name")); } const name = key.name; src = name; if (hasOwn.call(key, "weight")) { weight = key.weight; if (weight <= 0) { throw new Error(INVALID_KEY_WEIGHT_VALUE(name)); } } path = createKeyPath(name); id = createKeyId(name); getFn = key.getFn; } return { path, id, weight, src, getFn }; } function createKeyPath(key) { return isArray(key) ? key : key.split("."); } function createKeyId(key) { return isArray(key) ? key.join(".") : key; } function get(obj, path) { let list = []; let arr = false; const deepGet = (obj2, path2, index) => { if (!isDefined(obj2)) { return; } if (!path2[index]) { list.push(obj2); } else { let key = path2[index]; const value = obj2[key]; if (!isDefined(value)) { return; } if (index === path2.length - 1 && (isString(value) || isNumber(value) || isBoolean(value))) { list.push(toString(value)); } else if (isArray(value)) { arr = true; for (let i = 0, len = value.length; i < len; i += 1) { deepGet(value[i], path2, index + 1); } } else if (path2.length) { deepGet(value, path2, index + 1); } } }; deepGet(obj, isString(path) ? path.split(".") : path, 0); return arr ? list : list[0]; } const MatchOptions = { // Whether the matches should be included in the result set. When `true`, each record in the result // set will include the indices of the matched characters. // These can consequently be used for highlighting purposes. includeMatches: false, // When `true`, the matching function will continue to the end of a search pattern even if // a perfect match has already been located in the string. findAllMatches: false, // Minimum number of characters that must be matched before a result is considered a match minMatchCharLength: 1 }; const BasicOptions = { // When `true`, the algorithm continues searching to the end of the input even if a perfect // match is found before the end of the same input. isCaseSensitive: false, // When true, the matching function will continue to the end of a search pattern even if includeScore: false, // List of properties that will be searched. This also supports nested properties. keys: [], // Whether to sort the result list, by score shouldSort: true, // Default sort function: sort by ascending score, ascending index sortFn: (a, b) => a.score === b.score ? a.idx < b.idx ? -1 : 1 : a.score < b.score ? -1 : 1 }; const FuzzyOptions = { // Approximately where in the text is the pattern expected to be found? location: 0, // At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match // (of both letters and location), a threshold of '1.0' would match anything. threshold: 0.6, // Determines how close the match must be to the fuzzy location (specified above). // An exact letter match which is 'distance' characters away from the fuzzy location // would score as a complete mismatch. A distance of '0' requires the match be at // the exact location specified, a threshold of '1000' would require a perfect match // to be within 800 characters of the fuzzy location to be found using a 0.8 threshold. distance: 100 }; const AdvancedOptions = { // When `true`, it enables the use of unix-like search commands useExtendedSearch: false, // The get function to use when fetching an object's properties. // The default will search nested paths *ie foo.bar.baz* getFn: get, // When `true`, search will ignore `location` and `distance`, so it won't matter // where in the string the pattern appears. // More info: https://fusejs.io/concepts/scoring-theory.html#fuzziness-score ignoreLocation: false, // When `true`, the calculation for the relevance score (used for sorting) will // ignore the field-length norm. // More info: https://fusejs.io/concepts/scoring-theory.html#field-length-norm ignoreFieldNorm: false, // The weight to determine how much field length norm effects scoring. fieldNormWeight: 1 }; var Config = _objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({}, BasicOptions), MatchOptions), FuzzyOptions), AdvancedOptions); const SPACE = /[^ ]+/g; function norm(weight = 1, mantissa = 3) { const cache = /* @__PURE__ */ new Map(); const m = Math.pow(10, mantissa); return { get(value) { const numTokens = value.match(SPACE).length; if (cache.has(numTokens)) { return cache.get(numTokens); } const norm2 = 1 / Math.pow(numTokens, 0.5 * weight); const n = parseFloat(Math.round(norm2 * m) / m); cache.set(numTokens, n); return n; }, clear() { cache.clear(); } }; } class FuseIndex { constructor({ getFn = Config.getFn, fieldNormWeight = Config.fieldNormWeight } = {}) { this.norm = norm(fieldNormWeight, 3); this.getFn = getFn; this.isCreated = false; this.setIndexRecords(); } setSources(docs = []) { this.docs = docs; } setIndexRecords(records = []) { this.records = records; } setKeys(keys = []) { this.keys = keys; this._keysMap = {}; keys.forEach((key, idx) => { this._keysMap[key.id] = idx; }); } create() { if (this.isCreated || !this.docs.length) { return; } this.isCreated = true; if (isString(this.docs[0])) { this.docs.forEach((doc, docIndex) => { this._addString(doc, docIndex); }); } else { this.docs.forEach((doc, docIndex) => { this._addObject(doc, docIndex); }); } this.norm.clear(); } // Adds a doc to the end of the index add(doc) { const idx = this.size(); if (isString(doc)) { this._addString(doc, idx); } else { this._addObject(doc, idx); } } // Removes the doc at the specified index of the index removeAt(idx) { this.records.splice(idx, 1); for (let i = idx, len = this.size(); i < len; i += 1) { this.records[i].i -= 1; } } getValueForItemAtKeyId(item, keyId) { return item[this._keysMap[keyId]]; } size() { return this.records.length; } _addString(doc, docIndex) { if (!isDefined(doc) || isBlank(doc)) { return; } let record = { v: doc, i: docIndex, n: this.norm.get(doc) }; this.records.push(record); } _addObject(doc, docIndex) {