From ab22347d7be00977d46a1256a05a2b8fa1e6bb84 Mon Sep 17 00:00:00 2001
From: Josh Johnson
Date: Sun, 3 Nov 2019 17:45:16 +0000
Subject: [PATCH] Code refactoring (#735)
* Add placeholder options to demo page
* Use constant types in components
* Refactor adding predefined groups/items/choices
* Add 'highlighted' flag to Item type
* Fix dispatch param type
* Build
* Add jsdoc comments to utils
* Remove unused file
* Add default values to js doc comments
* Use Redux Action type
* Housekeeping
* Increase utils coverage
* Apply suggestions from code review
* Add _getTemplate unit tests
---
package-lock.json | 66 +-
package.json | 1 +
public/assets/scripts/choices.js | 1394 ++++++++++++++++----------
public/assets/scripts/choices.min.js | 2 +-
public/index.html | 32 +-
src/scripts/actions/choices.js | 9 +-
src/scripts/actions/groups.js | 3 +-
src/scripts/actions/items.js | 7 +-
src/scripts/actions/misc.js | 10 +-
src/scripts/choices.js | 213 ++--
src/scripts/choices.test.js | 33 +-
src/scripts/components/container.js | 5 +-
src/scripts/components/input.js | 3 +-
src/scripts/components/list.js | 2 +-
src/scripts/lib/delegate-events.js | 45 -
src/scripts/lib/utils.js | 124 ++-
src/scripts/lib/utils.test.js | 49 +-
src/scripts/store/store.js | 2 +-
types/index.d.ts | 5 +-
19 files changed, 1198 insertions(+), 807 deletions(-)
delete mode 100644 src/scripts/lib/delegate-events.js
diff --git a/package-lock.json b/package-lock.json
index b23b218..d9683ae 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1944,7 +1944,7 @@
},
"browserify-aes": {
"version": "1.2.0",
- "resolved": "http://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz",
+ "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz",
"integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==",
"dev": true,
"requires": {
@@ -1981,7 +1981,7 @@
},
"browserify-rsa": {
"version": "4.0.1",
- "resolved": "http://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz",
+ "resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz",
"integrity": "sha1-IeCr+vbyApzy+vsTNWenAdQTVSQ=",
"dev": true,
"requires": {
@@ -2026,7 +2026,7 @@
},
"buffer": {
"version": "4.9.1",
- "resolved": "http://registry.npmjs.org/buffer/-/buffer-4.9.1.tgz",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.1.tgz",
"integrity": "sha1-bRu2AbB6TvztlwlBMgkwJ8lbwpg=",
"dev": true,
"requires": {
@@ -2213,7 +2213,7 @@
},
"camelcase-keys": {
"version": "2.1.0",
- "resolved": "http://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz",
+ "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz",
"integrity": "sha1-MIvur/3ygRkFHvodkyITyRuPkuc=",
"dev": true,
"requires": {
@@ -2807,7 +2807,7 @@
},
"create-hash": {
"version": "1.2.0",
- "resolved": "http://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz",
+ "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz",
"integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==",
"dev": true,
"requires": {
@@ -2820,7 +2820,7 @@
},
"create-hmac": {
"version": "1.1.7",
- "resolved": "http://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz",
+ "resolved": "https://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz",
"integrity": "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==",
"dev": true,
"requires": {
@@ -3350,7 +3350,7 @@
},
"diffie-hellman": {
"version": "5.0.3",
- "resolved": "http://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz",
+ "resolved": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz",
"integrity": "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==",
"dev": true,
"requires": {
@@ -3420,7 +3420,7 @@
},
"duplexer": {
"version": "0.1.1",
- "resolved": "http://registry.npmjs.org/duplexer/-/duplexer-0.1.1.tgz",
+ "resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.1.tgz",
"integrity": "sha1-rOb/gIwc5mtX0ev5eXessCM0z8E=",
"dev": true
},
@@ -4092,7 +4092,7 @@
"dependencies": {
"pify": {
"version": "2.3.0",
- "resolved": "http://registry.npmjs.org/pify/-/pify-2.3.0.tgz",
+ "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz",
"integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=",
"dev": true
}
@@ -5873,7 +5873,7 @@
},
"get-stream": {
"version": "3.0.0",
- "resolved": "http://registry.npmjs.org/get-stream/-/get-stream-3.0.0.tgz",
+ "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-3.0.0.tgz",
"integrity": "sha1-jpQ9E1jcN1VQVOy+LtsFqhdO3hQ=",
"dev": true
},
@@ -6038,7 +6038,7 @@
},
"got": {
"version": "6.7.1",
- "resolved": "http://registry.npmjs.org/got/-/got-6.7.1.tgz",
+ "resolved": "https://registry.npmjs.org/got/-/got-6.7.1.tgz",
"integrity": "sha1-JAzQV4WpoY5WHcG0S0HHY+8ejbA=",
"dev": true,
"requires": {
@@ -6903,7 +6903,7 @@
},
"is-obj": {
"version": "1.0.1",
- "resolved": "http://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz",
+ "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz",
"integrity": "sha1-PkcprB9f3gJc19g6iW2rn09n2w8=",
"dev": true
},
@@ -7866,7 +7866,7 @@
},
"load-json-file": {
"version": "2.0.0",
- "resolved": "http://registry.npmjs.org/load-json-file/-/load-json-file-2.0.0.tgz",
+ "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-2.0.0.tgz",
"integrity": "sha1-eUfkIUmvgNaWy/eXvKq8/h/inKg=",
"dev": true,
"requires": {
@@ -7887,7 +7887,7 @@
},
"pify": {
"version": "2.3.0",
- "resolved": "http://registry.npmjs.org/pify/-/pify-2.3.0.tgz",
+ "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz",
"integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=",
"dev": true
}
@@ -8145,7 +8145,7 @@
},
"media-typer": {
"version": "0.3.0",
- "resolved": "http://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
"integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=",
"dev": true
},
@@ -8186,7 +8186,7 @@
},
"meow": {
"version": "3.7.0",
- "resolved": "http://registry.npmjs.org/meow/-/meow-3.7.0.tgz",
+ "resolved": "https://registry.npmjs.org/meow/-/meow-3.7.0.tgz",
"integrity": "sha1-cstmi0JSKCkKu/qFaJJYcwioAfs=",
"dev": true,
"requires": {
@@ -8214,7 +8214,7 @@
},
"load-json-file": {
"version": "1.1.0",
- "resolved": "http://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz",
+ "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz",
"integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=",
"dev": true,
"requires": {
@@ -8256,7 +8256,7 @@
},
"pify": {
"version": "2.3.0",
- "resolved": "http://registry.npmjs.org/pify/-/pify-2.3.0.tgz",
+ "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz",
"integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=",
"dev": true
},
@@ -8454,7 +8454,7 @@
},
"mkdirp": {
"version": "0.5.1",
- "resolved": "http://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz",
+ "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz",
"integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=",
"dev": true,
"requires": {
@@ -8724,7 +8724,7 @@
"dependencies": {
"semver": {
"version": "5.3.0",
- "resolved": "http://registry.npmjs.org/semver/-/semver-5.3.0.tgz",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-5.3.0.tgz",
"integrity": "sha1-myzl094C0XxgEq0yaqa00M9U+U8=",
"dev": true
}
@@ -9603,7 +9603,7 @@
},
"onetime": {
"version": "1.1.0",
- "resolved": "http://registry.npmjs.org/onetime/-/onetime-1.1.0.tgz",
+ "resolved": "https://registry.npmjs.org/onetime/-/onetime-1.1.0.tgz",
"integrity": "sha1-ofeDj4MUxRbwXs78vEzP4EtO14k=",
"dev": true
},
@@ -9653,7 +9653,7 @@
},
"ora": {
"version": "0.2.3",
- "resolved": "http://registry.npmjs.org/ora/-/ora-0.2.3.tgz",
+ "resolved": "https://registry.npmjs.org/ora/-/ora-0.2.3.tgz",
"integrity": "sha1-N1J9Igrc1Tw5tzVx11QVbV22V6Q=",
"dev": true,
"requires": {
@@ -9704,7 +9704,7 @@
},
"os-locale": {
"version": "1.4.0",
- "resolved": "http://registry.npmjs.org/os-locale/-/os-locale-1.4.0.tgz",
+ "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-1.4.0.tgz",
"integrity": "sha1-IPnxeuKe00XoveWDsT0gCYA8FNk=",
"dev": true,
"requires": {
@@ -9940,7 +9940,7 @@
"dependencies": {
"pify": {
"version": "2.3.0",
- "resolved": "http://registry.npmjs.org/pify/-/pify-2.3.0.tgz",
+ "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz",
"integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=",
"dev": true
}
@@ -11770,7 +11770,7 @@
},
"safe-regex": {
"version": "1.1.0",
- "resolved": "http://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz",
+ "resolved": "https://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz",
"integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=",
"dev": true,
"requires": {
@@ -12134,7 +12134,7 @@
},
"sha.js": {
"version": "2.4.11",
- "resolved": "http://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz",
+ "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz",
"integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==",
"dev": true,
"requires": {
@@ -12201,6 +12201,12 @@
"supports-color": "^5.5.0"
}
},
+ "sinon-chai": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/sinon-chai/-/sinon-chai-3.3.0.tgz",
+ "integrity": "sha512-r2JhDY7gbbmh5z3Q62pNbrjxZdOAjpsqW/8yxAZRSqLZqowmfGZPGUZPFf3UX36NLis0cv8VEM5IJh9HgkSOAA==",
+ "dev": true
+ },
"slash": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz",
@@ -12209,7 +12215,7 @@
},
"slice-ansi": {
"version": "0.0.4",
- "resolved": "http://registry.npmjs.org/slice-ansi/-/slice-ansi-0.0.4.tgz",
+ "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-0.0.4.tgz",
"integrity": "sha1-7b+JA/ZvfOL46v1s7tZeJkyDGzU=",
"dev": true
},
@@ -12629,7 +12635,7 @@
},
"strip-ansi": {
"version": "3.0.1",
- "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz",
"integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=",
"dev": true,
"requires": {
@@ -12644,7 +12650,7 @@
},
"strip-eof": {
"version": "1.0.0",
- "resolved": "http://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz",
+ "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz",
"integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=",
"dev": true
},
@@ -12977,7 +12983,7 @@
},
"through": {
"version": "2.3.8",
- "resolved": "http://registry.npmjs.org/through/-/through-2.3.8.tgz",
+ "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz",
"integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=",
"dev": true
},
diff --git a/package.json b/package.json
index b1abf12..20bc93d 100644
--- a/package.json
+++ b/package.json
@@ -84,6 +84,7 @@
"postcss-cli": "^6.1.3",
"prettier": "^1.18.2",
"sinon": "^7.5.0",
+ "sinon-chai": "^3.3.0",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.9",
"webpack-dev-middleware": "^3.7.2",
diff --git a/public/assets/scripts/choices.js b/public/assets/scripts/choices.js
index b748d0f..45dd55f 100644
--- a/public/assets/scripts/choices.js
+++ b/public/assets/scripts/choices.js
@@ -1266,34 +1266,61 @@ var general = function general(state, action) {
/* harmony default export */ var reducers_general = (general);
// CONCATENATED MODULE: ./src/scripts/lib/utils.js
+/**
+ * @param {number} min
+ * @param {number} max
+ * @returns {number}
+ */
var getRandomNumber = function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min) + min);
};
+/**
+ * @param {number} length
+ * @returns {string}
+ */
+
var generateChars = function generateChars(length) {
- var chars = '';
-
- for (var i = 0; i < length; i++) {
- var randomChar = getRandomNumber(0, 36);
- chars += randomChar.toString(36);
- }
-
- return chars;
+ return Array.from({
+ length: length
+ }, function () {
+ return getRandomNumber(0, 36).toString(36);
+ }).join('');
};
+/**
+ * @param {HTMLInputElement | HTMLSelectElement} element
+ * @param {string} prefix
+ * @returns {string}
+ */
+
var generateId = function generateId(element, prefix) {
var id = element.id || element.name && element.name + "-" + generateChars(2) || generateChars(4);
id = id.replace(/(:|\.|\[|\]|,)/g, '');
id = prefix + "-" + id;
return id;
};
+/**
+ * @param {any} obj
+ * @returns {string}
+ */
+
var getType = function getType(obj) {
return Object.prototype.toString.call(obj).slice(8, -1);
};
+/**
+ * @param {string} type
+ * @param {any} obj
+ * @returns {boolean}
+ */
+
var isType = function isType(type, obj) {
return obj !== undefined && obj !== null && getType(obj) === type;
};
-var isElement = function isElement(element) {
- return element instanceof Element;
-};
+/**
+ * @param {HTMLElement} element
+ * @param {HTMLElement} [wrapper={HTMLDivElement}]
+ * @returns {HTMLElement}
+ */
+
var utils_wrap = function wrap(element, wrapper) {
if (wrapper === void 0) {
wrapper = document.createElement('div');
@@ -1315,49 +1342,79 @@ var utils_wrap = function wrap(element, wrapper) {
var findAncestorByAttrName = function findAncestorByAttrName(el, attr) {
return el.closest("[" + attr + "]");
};
-var getAdjacentEl = function getAdjacentEl(startEl, className, direction) {
+/**
+ * @param {Element} startEl
+ * @param {string} selector
+ * @param {1 | -1} direction
+ * @returns {Element | undefined}
+ */
+
+var getAdjacentEl = function getAdjacentEl(startEl, selector, direction) {
if (direction === void 0) {
direction = 1;
}
- if (!startEl || !className) {
- return;
+ if (!(startEl instanceof Element) || typeof selector !== 'string') {
+ return undefined;
}
- var parent = startEl.parentNode.parentNode;
- var children = Array.from(parent.querySelectorAll(className));
- var startPos = children.indexOf(startEl);
- var operatorDirection = direction > 0 ? 1 : -1;
- return children[startPos + operatorDirection];
+ var prop = (direction > 0 ? 'next' : 'previous') + "ElementSibling";
+ var sibling = startEl[prop];
+
+ while (sibling) {
+ if (sibling.matches(selector)) {
+ return sibling;
+ }
+
+ sibling = sibling[prop];
+ }
+
+ return sibling;
};
-var isScrolledIntoView = function isScrolledIntoView(el, parent, direction) {
+/**
+ * @param {HTMLElement} element
+ * @param {HTMLElement} parent
+ * @param {-1 | 1} direction
+ * @returns {boolean}
+ */
+
+var isScrolledIntoView = function isScrolledIntoView(element, parent, direction) {
if (direction === void 0) {
direction = 1;
}
- if (!el) {
- return;
+ if (!element) {
+ return false;
}
var isVisible;
if (direction > 0) {
// In view from bottom
- isVisible = parent.scrollTop + parent.offsetHeight >= el.offsetTop + el.offsetHeight;
+ isVisible = parent.scrollTop + parent.offsetHeight >= element.offsetTop + element.offsetHeight;
} else {
// In view from top
- isVisible = el.offsetTop >= parent.scrollTop;
+ isVisible = element.offsetTop >= parent.scrollTop;
}
return isVisible;
};
+/**
+ * @param {any} value
+ * @returns {any}
+ */
+
var sanitise = function sanitise(value) {
- if (!isType('String', value)) {
+ if (typeof value !== 'string') {
return value;
}
return value.replace(/&/g, '&').replace(/>/g, '&rt;').replace(/\"" + sanitise(value) + "\"";
+ },
+ maxItemText: function maxItemText(maxItemCount) {
+ return "Only " + maxItemCount + " values can be added";
+ },
+ valueComparer: function valueComparer(value1, value2) {
+ return value1 === value2;
+ },
+ fuseOptions: {
+ includeScore: true
+ },
+ callbackOnInit: null,
+ callbackOnCreateTemplates: null,
+ classNames: DEFAULT_CLASSNAMES
+};
+var EVENTS = {
+ showDropdown: 'showDropdown',
+ hideDropdown: 'hideDropdown',
+ change: 'change',
+ choice: 'choice',
+ search: 'search',
+ addItem: 'addItem',
+ removeItem: 'removeItem',
+ highlightItem: 'highlightItem',
+ highlightChoice: 'highlightChoice'
+};
+var ACTION_TYPES = {
+ ADD_CHOICE: 'ADD_CHOICE',
+ FILTER_CHOICES: 'FILTER_CHOICES',
+ ACTIVATE_CHOICES: 'ACTIVATE_CHOICES',
+ CLEAR_CHOICES: 'CLEAR_CHOICES',
+ ADD_GROUP: 'ADD_GROUP',
+ ADD_ITEM: 'ADD_ITEM',
+ REMOVE_ITEM: 'REMOVE_ITEM',
+ HIGHLIGHT_ITEM: 'HIGHLIGHT_ITEM',
+ CLEAR_ALL: 'CLEAR_ALL'
+};
+var KEY_CODES = {
+ BACK_KEY: 46,
+ DELETE_KEY: 8,
+ ENTER_KEY: 13,
+ A_KEY: 65,
+ ESC_KEY: 27,
+ UP_KEY: 38,
+ DOWN_KEY: 40,
+ PAGE_UP_KEY: 33,
+ PAGE_DOWN_KEY: 34
+};
+var TEXT_TYPE = 'text';
+var SELECT_ONE_TYPE = 'select-one';
+var SELECT_MULTIPLE_TYPE = 'select-multiple';
+var SCROLLING_SPEED = 4;
// CONCATENATED MODULE: ./src/scripts/components/container.js
+/**
+ * @typedef {import('../../../types/index').Choices.passedElement} passedElement
+ * @typedef {import('../../../types/index').Choices.ClassNames} ClassNames
+ */
+
var container_Container =
/*#__PURE__*/
function () {
+ /**
+ * @param {{
+ * element: HTMLElement,
+ * type: passedElement['type'],
+ * classNames: ClassNames,
+ * position
+ * }} args
+ */
function Container(_ref) {
var element = _ref.element,
type = _ref.type,
classNames = _ref.classNames,
position = _ref.position;
- Object.assign(this, {
- element: element,
- classNames: classNames,
- type: type,
- position: position
- });
+ this.element = element;
+ this.classNames = classNames;
+ this.type = type;
+ this.position = position;
this.isOpen = false;
this.isFlipped = false;
this.isFocussed = false;
@@ -1774,42 +2006,28 @@ function () {
this._onFocus = this._onFocus.bind(this);
this._onBlur = this._onBlur.bind(this);
}
- /**
- * Add event listeners
- */
-
var _proto = Container.prototype;
_proto.addEventListeners = function addEventListeners() {
this.element.addEventListener('focus', this._onFocus);
this.element.addEventListener('blur', this._onBlur);
- }
- /**
- * Remove event listeners
- */
-
- /** */
- ;
+ };
_proto.removeEventListeners = function removeEventListeners() {
this.element.removeEventListener('focus', this._onFocus);
this.element.removeEventListener('blur', this._onBlur);
}
/**
- * Determine whether container should be flipped
- * based on passed dropdown position
- * @param {Number} dropdownPos
- * @returns
+ * Determine whether container should be flipped based on passed
+ * dropdown position
+ * @param {number} dropdownPos
+ * @returns {boolean}
*/
;
- _proto.shouldFlip = function shouldFlip(dropdownPos, windowHeight) {
- if (windowHeight === void 0) {
- windowHeight = getWindowHeight();
- }
-
- if (dropdownPos === undefined) {
+ _proto.shouldFlip = function shouldFlip(dropdownPos) {
+ if (typeof dropdownPos !== 'number') {
return false;
} // If flip is enabled and the dropdown bottom position is
// greater than the window height flip the dropdown.
@@ -1818,7 +2036,7 @@ function () {
var shouldFlip = false;
if (this.position === 'auto') {
- shouldFlip = dropdownPos >= windowHeight;
+ shouldFlip = !window.matchMedia("(min-height: " + (dropdownPos + 1) + "px)").matches;
} else if (this.position === 'top') {
shouldFlip = true;
}
@@ -1826,22 +2044,21 @@ function () {
return shouldFlip;
}
/**
- * Set active descendant attribute
- * @param {Number} activeDescendant ID of active descendant
+ * @param {string} activeDescendantID
*/
;
_proto.setActiveDescendant = function setActiveDescendant(activeDescendantID) {
this.element.setAttribute('aria-activedescendant', activeDescendantID);
- }
- /**
- * Remove active descendant attribute
- */
- ;
+ };
_proto.removeActiveDescendant = function removeActiveDescendant() {
this.element.removeAttribute('aria-activedescendant');
- };
+ }
+ /**
+ * @param {number} dropdownPos
+ */
+ ;
_proto.open = function open(dropdownPos) {
this.element.classList.add(this.classNames.openState);
@@ -1878,80 +2095,64 @@ function () {
_proto.removeFocusState = function removeFocusState() {
this.element.classList.remove(this.classNames.focusState);
- }
- /**
- * Remove disabled state
- */
- ;
+ };
_proto.enable = function enable() {
this.element.classList.remove(this.classNames.disabledState);
this.element.removeAttribute('aria-disabled');
- if (this.type === 'select-one') {
+ if (this.type === SELECT_ONE_TYPE) {
this.element.setAttribute('tabindex', '0');
}
this.isDisabled = false;
- }
- /**
- * Set disabled state
- */
- ;
+ };
_proto.disable = function disable() {
this.element.classList.add(this.classNames.disabledState);
this.element.setAttribute('aria-disabled', 'true');
- if (this.type === 'select-one') {
+ if (this.type === SELECT_ONE_TYPE) {
this.element.setAttribute('tabindex', '-1');
}
this.isDisabled = true;
- };
+ }
+ /**
+ * @param {HTMLElement} element
+ */
+ ;
_proto.wrap = function wrap(element) {
utils_wrap(element, this.element);
- };
+ }
+ /**
+ * @param {Element} element
+ */
+ ;
_proto.unwrap = function unwrap(element) {
// Move passed element outside this element
this.element.parentNode.insertBefore(element, this.element); // Remove this element
this.element.parentNode.removeChild(this.element);
- }
- /**
- * Add loading state to element
- */
- ;
+ };
_proto.addLoadingState = function addLoadingState() {
this.element.classList.add(this.classNames.loadingState);
this.element.setAttribute('aria-busy', 'true');
this.isLoading = true;
- }
- /**
- * Remove loading state from element
- */
- ;
+ };
_proto.removeLoadingState = function removeLoadingState() {
this.element.classList.remove(this.classNames.loadingState);
this.element.removeAttribute('aria-busy');
this.isLoading = false;
- }
- /**
- * Set focussed state
- */
- ;
+ };
_proto._onFocus = function _onFocus() {
this.isFocussed = true;
- }
- /**
- * Remove blurred state
- */
- ;
+ };
_proto._onBlur = function _onBlur() {
this.isFocussed = false;
@@ -1968,14 +2169,21 @@ function input_createClass(Constructor, protoProps, staticProps) { if (protoProp
+/**
+ * @typedef {import('../../../types/index').Choices.passedElement} passedElement
+ * @typedef {import('../../../types/index').Choices.ClassNames} ClassNames
+ */
+
var input_Input =
/*#__PURE__*/
function () {
/**
- *
- * @typedef {import('../../../types/index').Choices.passedElement} passedElement
- * @typedef {import('../../../types/index').Choices.ClassNames} ClassNames
- * @param {{element: HTMLInputElement, type: passedElement['type'], classNames: ClassNames, preventPaste: boolean }} p
+ * @param {{
+ * element: HTMLInputElement,
+ * type: passedElement['type'],
+ * classNames: ClassNames,
+ * preventPaste: boolean
+ * }} args
*/
function Input(_ref) {
var element = _ref.element,
@@ -1993,6 +2201,10 @@ function () {
this._onFocus = this._onFocus.bind(this);
this._onBlur = this._onBlur.bind(this);
}
+ /**
+ * @param {string} placeholder
+ */
+
var _proto = Input.prototype;
@@ -2045,8 +2257,8 @@ function () {
}
/**
* Set value of input to blank
- * @return {Object} Class instance
- * @public
+ * @param {boolean} setWidth
+ * @returns {this}
*/
;
@@ -2079,7 +2291,11 @@ function () {
placeholder = _this$element.placeholder;
style.minWidth = placeholder.length + 1 + "ch";
style.width = value.length + 1 + "ch";
- };
+ }
+ /**
+ * @param {string} activeDescendantID
+ */
+ ;
_proto.setActiveDescendant = function setActiveDescendant(activeDescendantID) {
this.element.setAttribute('aria-activedescendant', activeDescendantID);
@@ -2090,10 +2306,14 @@ function () {
};
_proto._onInput = function _onInput() {
- if (this.type !== 'select-one') {
+ if (this.type !== SELECT_ONE_TYPE) {
this.setWidth();
}
- };
+ }
+ /**
+ * @param {Event} event
+ */
+ ;
_proto._onPaste = function _onPaste(event) {
if (this.preventPaste) {
@@ -2114,11 +2334,19 @@ function () {
set: function set(placeholder) {
this.element.placeholder = placeholder;
}
+ /**
+ * @returns {string}
+ */
+
}, {
key: "value",
get: function get() {
return sanitise(this.element.value);
- },
+ }
+ /**
+ * @param {string} value
+ */
+ ,
set: function set(value) {
this.element.value = value;
}
@@ -2128,132 +2356,21 @@ function () {
}();
-// CONCATENATED MODULE: ./src/scripts/constants.js
-
-var DEFAULT_CLASSNAMES = {
- containerOuter: 'choices',
- containerInner: 'choices__inner',
- input: 'choices__input',
- inputCloned: 'choices__input--cloned',
- list: 'choices__list',
- listItems: 'choices__list--multiple',
- listSingle: 'choices__list--single',
- listDropdown: 'choices__list--dropdown',
- item: 'choices__item',
- itemSelectable: 'choices__item--selectable',
- itemDisabled: 'choices__item--disabled',
- itemChoice: 'choices__item--choice',
- placeholder: 'choices__placeholder',
- group: 'choices__group',
- groupHeading: 'choices__heading',
- button: 'choices__button',
- activeState: 'is-active',
- focusState: 'is-focused',
- openState: 'is-open',
- disabledState: 'is-disabled',
- highlightedState: 'is-highlighted',
- flippedState: 'is-flipped',
- loadingState: 'is-loading',
- noResults: 'has-no-results',
- noChoices: 'has-no-choices'
-};
-var DEFAULT_CONFIG = {
- items: [],
- choices: [],
- silent: false,
- renderChoiceLimit: -1,
- maxItemCount: -1,
- addItems: true,
- addItemFilter: null,
- removeItems: true,
- removeItemButton: false,
- editItems: false,
- duplicateItemsAllowed: true,
- delimiter: ',',
- paste: true,
- searchEnabled: true,
- searchChoices: true,
- searchFloor: 1,
- searchResultLimit: 4,
- searchFields: ['label', 'value'],
- position: 'auto',
- resetScrollPosition: true,
- shouldSort: true,
- shouldSortItems: false,
- sortFn: sortByAlpha,
- placeholder: true,
- placeholderValue: null,
- searchPlaceholderValue: null,
- prependValue: null,
- appendValue: null,
- renderSelectedChoices: 'auto',
- loadingText: 'Loading...',
- noResultsText: 'No results found',
- noChoicesText: 'No choices to choose from',
- itemSelectText: 'Press to select',
- uniqueItemText: 'Only unique values can be added',
- customAddItemText: 'Only values matching specific conditions can be added',
- addItemText: function addItemText(value) {
- return "Press Enter to add \"" + sanitise(value) + "\"";
- },
- maxItemText: function maxItemText(maxItemCount) {
- return "Only " + maxItemCount + " values can be added";
- },
- itemComparer: function itemComparer(choice, item) {
- return choice === item;
- },
- fuseOptions: {
- includeScore: true
- },
- callbackOnInit: null,
- callbackOnCreateTemplates: null,
- classNames: DEFAULT_CLASSNAMES
-};
-var EVENTS = {
- showDropdown: 'showDropdown',
- hideDropdown: 'hideDropdown',
- change: 'change',
- choice: 'choice',
- search: 'search',
- addItem: 'addItem',
- removeItem: 'removeItem',
- highlightItem: 'highlightItem',
- highlightChoice: 'highlightChoice'
-};
-var ACTION_TYPES = {
- ADD_CHOICE: 'ADD_CHOICE',
- FILTER_CHOICES: 'FILTER_CHOICES',
- ACTIVATE_CHOICES: 'ACTIVATE_CHOICES',
- CLEAR_CHOICES: 'CLEAR_CHOICES',
- ADD_GROUP: 'ADD_GROUP',
- ADD_ITEM: 'ADD_ITEM',
- REMOVE_ITEM: 'REMOVE_ITEM',
- HIGHLIGHT_ITEM: 'HIGHLIGHT_ITEM',
- CLEAR_ALL: 'CLEAR_ALL'
-};
-var KEY_CODES = {
- BACK_KEY: 46,
- DELETE_KEY: 8,
- ENTER_KEY: 13,
- A_KEY: 65,
- ESC_KEY: 27,
- UP_KEY: 38,
- DOWN_KEY: 40,
- PAGE_UP_KEY: 33,
- PAGE_DOWN_KEY: 34
-};
-var SCROLLING_SPEED = 4;
// CONCATENATED MODULE: ./src/scripts/components/list.js
+/**
+ * @typedef {import('../../../types/index').Choices.Choice} Choice
+ */
var list_List =
/*#__PURE__*/
function () {
+ /**
+ * @param {{ element: HTMLElement }} args
+ */
function List(_ref) {
var element = _ref.element;
- Object.assign(this, {
- element: element
- });
+ this.element = element;
this.scrollPos = this.element.scrollTop;
this.height = this.element.offsetHeight;
}
@@ -2262,15 +2379,28 @@ function () {
_proto.clear = function clear() {
this.element.innerHTML = '';
- };
+ }
+ /**
+ * @param {Element} node
+ */
+ ;
_proto.append = function append(node) {
this.element.appendChild(node);
- };
+ }
+ /**
+ * @param {string} selector
+ * @returns {Element | null}
+ */
+ ;
_proto.getChild = function getChild(selector) {
return this.element.querySelector(selector);
- };
+ }
+ /**
+ * @returns {boolean}
+ */
+ ;
_proto.hasChildren = function hasChildren() {
return this.element.hasChildNodes();
@@ -2278,41 +2408,63 @@ function () {
_proto.scrollToTop = function scrollToTop() {
this.element.scrollTop = 0;
- };
+ }
+ /**
+ * @param {HTMLElement} element
+ * @param {1 | -1} direction
+ */
+ ;
- _proto.scrollToChoice = function scrollToChoice(choice, direction) {
+ _proto.scrollToChildElement = function scrollToChildElement(element, direction) {
var _this = this;
- if (!choice) {
+ if (!element) {
return;
}
- var dropdownHeight = this.element.offsetHeight;
- var choiceHeight = choice.offsetHeight; // Distance from bottom of element to top of parent
+ var listHeight = this.element.offsetHeight; // Scroll position of dropdown
- var choicePos = choice.offsetTop + choiceHeight; // Scroll position of dropdown
+ var listScrollPosition = this.element.scrollTop + listHeight;
+ var elementHeight = element.offsetHeight; // Distance from bottom of element to top of parent
- var containerScrollPos = this.element.scrollTop + dropdownHeight; // Difference between the choice and scroll position
+ var elementPos = element.offsetTop + elementHeight; // Difference between the element and scroll position
- var destination = direction > 0 ? this.element.scrollTop + choicePos - containerScrollPos : choice.offsetTop;
- requestAnimationFrame(function (time) {
- _this._animateScroll(time, destination, direction);
+ var destination = direction > 0 ? this.element.scrollTop + elementPos - listScrollPosition : element.offsetTop;
+ requestAnimationFrame(function () {
+ _this._animateScroll(destination, direction);
});
- };
+ }
+ /**
+ * @param {number} scrollPos
+ * @param {number} strength
+ * @param {number} destination
+ */
+ ;
_proto._scrollDown = function _scrollDown(scrollPos, strength, destination) {
var easing = (destination - scrollPos) / strength;
var distance = easing > 1 ? easing : 1;
this.element.scrollTop = scrollPos + distance;
- };
+ }
+ /**
+ * @param {number} scrollPos
+ * @param {number} strength
+ * @param {number} destination
+ */
+ ;
_proto._scrollUp = function _scrollUp(scrollPos, strength, destination) {
var easing = (scrollPos - destination) / strength;
var distance = easing > 1 ? easing : 1;
this.element.scrollTop = scrollPos - distance;
- };
+ }
+ /**
+ * @param {*} destination
+ * @param {*} direction
+ */
+ ;
- _proto._animateScroll = function _animateScroll(time, destination, direction) {
+ _proto._animateScroll = function _animateScroll(destination, direction) {
var _this2 = this;
var strength = SCROLLING_SPEED;
@@ -2335,7 +2487,7 @@ function () {
if (continueAnimation) {
requestAnimationFrame(function () {
- _this2._animateScroll(time, destination, direction);
+ _this2._animateScroll(destination, direction);
});
}
};
@@ -2350,19 +2502,27 @@ function wrapped_element_defineProperties(target, props) { for (var i = 0; i < p
function wrapped_element_createClass(Constructor, protoProps, staticProps) { if (protoProps) wrapped_element_defineProperties(Constructor.prototype, protoProps); if (staticProps) wrapped_element_defineProperties(Constructor, staticProps); return Constructor; }
+/**
+ * @typedef {import('../../../types/index').Choices.passedElement} passedElement
+ * @typedef {import('../../../types/index').Choices.ClassNames} ClassNames
+ */
var wrapped_element_WrappedElement =
/*#__PURE__*/
function () {
+ /**
+ * @param {{
+ * element: HTMLInputElement | HTMLSelectElement,
+ * classNames: ClassNames,
+ * }} args
+ */
function WrappedElement(_ref) {
var element = _ref.element,
classNames = _ref.classNames;
- Object.assign(this, {
- element: element,
- classNames: classNames
- });
+ this.element = element;
+ this.classNames = classNames;
- if (!isElement(element)) {
+ if (!(element instanceof HTMLInputElement) && !(element instanceof HTMLSelectElement)) {
throw new TypeError('Invalid element passed');
}
@@ -2376,7 +2536,7 @@ function () {
this.element.classList.add(this.classNames.input);
this.element.hidden = true; // Remove element from tab index
- this.element.tabIndex = '-1'; // Backup original styles if any
+ this.element.tabIndex = -1; // Backup original styles if any
var origStyle = this.element.getAttribute('style');
@@ -2425,6 +2585,16 @@ function () {
};
wrapped_element_createClass(WrappedElement, [{
+ key: "isActive",
+ get: function get() {
+ return this.element.dataset.choice === 'active';
+ }
+ }, {
+ key: "dir",
+ get: function get() {
+ return this.element.dir;
+ }
+ }, {
key: "value",
get: function get() {
return this.element.value;
@@ -2447,12 +2617,23 @@ function wrapped_input_createClass(Constructor, protoProps, staticProps) { if (p
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+/**
+ * @typedef {import('../../../types/index').Choices.ClassNames} ClassNames
+ * @typedef {import('../../../types/index').Choices.Item} Item
+ */
var WrappedInput =
/*#__PURE__*/
function (_WrappedElement) {
_inheritsLoose(WrappedInput, _WrappedElement);
+ /**
+ * @param {{
+ * element: HTMLInputElement,
+ * classNames: ClassNames,
+ * delimiter: string
+ * }} args
+ */
function WrappedInput(_ref) {
var _this;
@@ -2466,12 +2647,20 @@ function (_WrappedElement) {
_this.delimiter = delimiter;
return _this;
}
+ /**
+ * @returns {string}
+ */
+
wrapped_input_createClass(WrappedInput, [{
key: "value",
get: function get() {
return this.element.value;
- },
+ }
+ /**
+ * @param {Item[]} items
+ */
+ ,
set: function set(items) {
var itemValues = items.map(function (_ref2) {
var value = _ref2.value;
@@ -2495,12 +2684,25 @@ function wrapped_select_createClass(Constructor, protoProps, staticProps) { if (
function wrapped_select_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+/**
+ * @typedef {import('../../../types/index').Choices.ClassNames} ClassNames
+ * @typedef {import('../../../types/index').Choices.Item} Item
+ * @typedef {import('../../../types/index').Choices.Choice} Choice
+ */
var WrappedSelect =
/*#__PURE__*/
function (_WrappedElement) {
wrapped_select_inheritsLoose(WrappedSelect, _WrappedElement);
+ /**
+ * @param {{
+ * element: HTMLSelectElement,
+ * classNames: ClassNames,
+ * delimiter: string
+ * template: function
+ * }} args
+ */
function WrappedSelect(_ref) {
var _this;
@@ -2517,6 +2719,9 @@ function (_WrappedElement) {
var _proto = WrappedSelect.prototype;
+ /**
+ * @param {DocumentFragment} fragment
+ */
_proto.appendDocFragment = function appendDocFragment(fragment) {
this.element.innerHTML = '';
this.element.appendChild(fragment);
@@ -2528,16 +2733,28 @@ function (_WrappedElement) {
return this.element.querySelector('option[value=""]') || // Backward compatibility layer for the non-standard placeholder attribute supported in older versions.
this.element.querySelector('option[placeholder]');
}
+ /**
+ * @returns {Element[]}
+ */
+
}, {
key: "optionGroups",
get: function get() {
return Array.from(this.element.getElementsByTagName('OPTGROUP'));
}
+ /**
+ * @returns {Item[] | Choice[]}
+ */
+
}, {
key: "options",
get: function get() {
return Array.from(this.element.options);
- },
+ }
+ /**
+ * @param {Item[] | Choice[]} options
+ */
+ ,
set: function set(options) {
var _this2 = this;
@@ -2827,6 +3044,14 @@ var TEMPLATES =
};
/* harmony default export */ var templates = (TEMPLATES);
// CONCATENATED MODULE: ./src/scripts/actions/choices.js
+/**
+ * @typedef {import('../../../types/index').Choices.Choice} Choice
+ */
+
+/**
+ * @argument {Choice} choice
+ * @returns {{ type: string } & Choice}
+ */
var choices_addChoice = function addChoice(_ref) {
var value = _ref.value,
@@ -2851,12 +3076,22 @@ var choices_addChoice = function addChoice(_ref) {
keyCode: keyCode
};
};
+/**
+ * @argument {Choice[]} results
+ * @returns {{ type: string, results: Choice[] }}
+ */
+
var choices_filterChoices = function filterChoices(results) {
return {
type: ACTION_TYPES.FILTER_CHOICES,
results: results
};
};
+/**
+ * @argument {boolean} active
+ * @returns {{ type: string, active: boolean }}
+ */
+
var choices_activateChoices = function activateChoices(active) {
if (active === void 0) {
active = true;
@@ -2867,6 +3102,10 @@ var choices_activateChoices = function activateChoices(active) {
active: active
};
};
+/**
+ * @returns {{ type: string }}
+ */
+
var choices_clearChoices = function clearChoices() {
return {
type: ACTION_TYPES.CLEAR_CHOICES
@@ -2874,6 +3113,15 @@ var choices_clearChoices = function clearChoices() {
};
// CONCATENATED MODULE: ./src/scripts/actions/items.js
+/**
+ * @typedef {import('../../../types/index').Choices.Item} Item
+ */
+
+/**
+ * @param {Item} item
+ * @returns {{ type: string } & Item}
+ */
+
var items_addItem = function addItem(_ref) {
var value = _ref.value,
label = _ref.label,
@@ -2895,6 +3143,12 @@ var items_addItem = function addItem(_ref) {
keyCode: keyCode
};
};
+/**
+ * @param {string} id
+ * @param {string} choiceId
+ * @returns {{ type: string, id: string, choiceId: string }}
+ */
+
var items_removeItem = function removeItem(id, choiceId) {
return {
type: ACTION_TYPES.REMOVE_ITEM,
@@ -2902,6 +3156,12 @@ var items_removeItem = function removeItem(id, choiceId) {
choiceId: choiceId
};
};
+/**
+ * @param {string} id
+ * @param {boolean} highlighted
+ * @returns {{ type: string, id: string, highlighted: boolean }}
+ */
+
var items_highlightItem = function highlightItem(id, highlighted) {
return {
type: ACTION_TYPES.HIGHLIGHT_ITEM,
@@ -2911,7 +3171,20 @@ var items_highlightItem = function highlightItem(id, highlighted) {
};
// CONCATENATED MODULE: ./src/scripts/actions/groups.js
-var groups_addGroup = function addGroup(value, id, active, disabled) {
+/**
+ * @typedef {import('../../../types/index').Choices.Group} Group
+ */
+
+/**
+ * @param {Group} group
+ * @returns {{ type: string } & Group}
+ */
+
+var groups_addGroup = function addGroup(_ref) {
+ var value = _ref.value,
+ id = _ref.id,
+ active = _ref.active,
+ disabled = _ref.disabled;
return {
type: ACTION_TYPES.ADD_GROUP,
value: value,
@@ -2921,18 +3194,30 @@ var groups_addGroup = function addGroup(value, id, active, disabled) {
};
};
// CONCATENATED MODULE: ./src/scripts/actions/misc.js
+/**
+ * @returns {{ type: string }}
+ */
var clearAll = function clearAll() {
return {
type: 'CLEAR_ALL'
};
};
+/**
+ * @param {any} state
+ * @returns {{ type: string, state: object }}
+ */
+
var resetTo = function resetTo(state) {
return {
type: 'RESET_TO',
state: state
};
};
-// CONCATENATED MODULE: ./src/scripts/actions/general.js
+/**
+ * @param {boolean} isLoading
+ * @returns {{ type: string, isLoading: boolean }}
+ */
+
var setIsLoading = function setIsLoading(isLoading) {
return {
type: 'SET_IS_LOADING',
@@ -2955,19 +3240,21 @@ function choices_createClass(Constructor, protoProps, staticProps) { if (protoPr
+/**
+ * @typedef {import('../../types/index').Choices.Choice} Choice
+ * @typedef {import('../../types/index').Choices.Item} Item
+ * @typedef {import('../../types/index').Choices.Group} Group
+ * @typedef {import('../../types/index').Choices.Options} Options
+ */
-var USER_DEFAULTS =
-/** @type {Partial} */
-{};
+/** @type {Partial} */
+
+var USER_DEFAULTS = {};
/**
* Choices
* @author Josh Johnson
*/
-/**
- * @typedef {import('../../types/index').Choices.Choice} Choice
- */
-
var choices_Choices =
/*#__PURE__*/
function () {
@@ -2987,7 +3274,7 @@ function () {
}
/**
* @param {string | HTMLInputElement | HTMLSelectElement} element
- * @param {Partial} userConfig
+ * @param {Partial} userConfig
*/
}]);
@@ -3003,10 +3290,11 @@ function () {
userConfig = {};
}
+ /** @type {Partial} */
this.config = cjs_default.a.all([DEFAULT_CONFIG, Choices.defaults.options, userConfig], // When merging array configs, replace with a copy of the userConfig array,
// instead of concatenating with the default array
{
- arrayMerge: function arrayMerge(destinationArray, sourceArray) {
+ arrayMerge: function arrayMerge(_, sourceArray) {
return [].concat(sourceArray);
}
}); // Convert addItemFilter to function
@@ -3026,15 +3314,15 @@ function () {
this.config.renderSelectedChoices = 'auto';
}
- var passedElement = isType('String', element) ? document.querySelector(element) : element;
+ var passedElement = typeof element === 'string' ? document.querySelector(element) : element;
if (!(passedElement instanceof HTMLInputElement || passedElement instanceof HTMLSelectElement)) {
throw TypeError('Expected one of the following types text|select-one|select-multiple');
}
- this._isTextElement = passedElement.type === 'text';
- this._isSelectOneElement = passedElement.type === 'select-one';
- this._isSelectMultipleElement = passedElement.type === 'select-multiple';
+ this._isTextElement = passedElement.type === TEXT_TYPE;
+ this._isSelectOneElement = passedElement.type === SELECT_ONE_TYPE;
+ this._isSelectMultipleElement = passedElement.type === SELECT_MULTIPLE_TYPE;
this._isSelectElement = this._isSelectOneElement || this._isSelectMultipleElement;
if (this._isTextElement) {
@@ -3071,7 +3359,7 @@ function () {
* @type {HTMLElement['dir']}
*/
- this._direction = this.passedElement.element.dir;
+ this._direction = this.passedElement.dir;
if (!this._direction) {
var _window$getComputedSt = window.getComputedStyle(this.passedElement.element),
@@ -3087,14 +3375,30 @@ function () {
this._idNames = {
itemChoice: 'item-choice'
- }; // Assign preset choices from passed object
+ }; // Assign preset groups from passed element
+
+ this._presetGroups = this.passedElement.optionGroups; // Assign preset choices from passed object
this._presetChoices = this.config.choices; // Assign preset items from passed object first
- this._presetItems = this.config.items; // Then add any values passed from attribute
+ this._presetItems = this.config.items; // Add any values passed from attribute
if (this.passedElement.value) {
this._presetItems = this._presetItems.concat(this.passedElement.value.split(this.config.delimiter));
+ } // Create array of choices from option elements
+
+
+ if (this.passedElement.options) {
+ this.passedElement.options.forEach(function (o) {
+ _this._presetChoices.push({
+ value: o.value,
+ label: o.innerHTML,
+ selected: o.selected,
+ disabled: o.disabled || o.parentNode.disabled,
+ placeholder: o.value === '' || o.hasAttribute('placeholder'),
+ customProperties: o.getAttribute('data-custom-properties')
+ });
+ });
}
this._render = this._render.bind(this);
@@ -3112,16 +3416,9 @@ function () {
this._onEnterKey = this._onEnterKey.bind(this);
this._onEscapeKey = this._onEscapeKey.bind(this);
this._onDirectionKey = this._onDirectionKey.bind(this);
- this._onDeleteKey = this._onDeleteKey.bind(this);
+ this._onDeleteKey = this._onDeleteKey.bind(this); // If element has already been initialised with Choices, fail silently
- if (this.config.shouldSortItems === true && this._isSelectOneElement) {
- if (!this.config.silent) {
- console.warn("shouldSortElements: Type of passed element is 'select-one', falling back to false.");
- }
- } // If element has already been initialised with Choices, fail silently
-
-
- if (this.passedElement.element.getAttribute('data-choice') === 'active') {
+ if (this.passedElement.isActive) {
if (!this.config.silent) {
console.warn('Trying to initialise Choices on element already initialised');
}
@@ -3166,7 +3463,7 @@ function () {
this.initialised = true;
var callbackOnInit = this.config.callbackOnInit; // Run callback if it is a function
- if (callbackOnInit && isType('Function', callbackOnInit)) {
+ if (callbackOnInit && typeof callbackOnInit === 'function') {
callbackOnInit.call(this);
}
};
@@ -3352,7 +3649,7 @@ function () {
requestAnimationFrame(function () {
_this7.dropdown.show();
- _this7.containerOuter.open(_this7.dropdown.distanceFromTopWindow());
+ _this7.containerOuter.open(_this7.dropdown.distanceFromTopWindow);
if (!preventInputFocus && _this7._canSearch) {
_this7.input.focus();
@@ -3425,7 +3722,7 @@ function () {
} // If only one value has been passed, convert to array
- var choiceValue = isType('Array', value) ? value : [value]; // Loop through each value and
+ var choiceValue = Array.isArray(value) ? value : [value]; // Loop through each value and
choiceValue.forEach(function (val) {
return _this10._findAndSelectChoiceByValue(val);
@@ -3441,7 +3738,7 @@ function () {
*
* **Input types affected:** select-one, select-multiple
*
- * @template {object[] | ((instance: Choices) => object[] | Promise
-