Compare commits

...

17 commits

Author SHA1 Message Date
Josh Johnson 9b860da254 Version 3.0.4 2018-03-27 11:31:56 +01:00
c5254061 394bde313d Fix xss vulnerability(escape html in input) 2018-03-25 20:26:55 +01:00
Ed Lomonaco f23beeb63d fixed a small goof I made 2018-03-16 09:28:13 +00:00
Ed Lomonaco 04aff72e11 fixed a small function name bug with typescript definition 2018-03-16 09:28:13 +00:00
Travis Tidwell 0519b99397 Adding an item comparer configuration to allow custom comparisons of items. 2018-03-13 11:03:48 +00:00
Mike Fiedler 5f11caae1b Update README.md
Example had a misplaced quote, breaking the code.
2018-02-17 16:58:38 +00:00
Bharat Ramnani 37e1d6fc52 Correct typo in README.md
Corrected spelling of _disabled_
2018-02-04 22:13:35 +00:00
Josh Johnson c2307de10b Merge remote-tracking branch 'origin/master' 2018-01-05 10:29:29 +00:00
Josh Johnson 31c9d86cd3 Reinstate types file 2018-01-05 10:29:14 +00:00
Josh Johnson 8cd9eeb1fc
Update README.md 2018-01-04 11:47:59 +00:00
Josh Johnson 9d9fd28584 Update version in example file 2018-01-04 11:44:25 +00:00
Josh Johnson 40cc462133 Version 3.0.3 2018-01-04 11:35:32 +00:00
Josh Johnson 3169d8c3d7 Use braces for early return 2018-01-04 11:34:22 +00:00
Josh Johnson 2e59385cc2 Merge branch 'tostringtheory-master' 2018-01-04 11:32:18 +00:00
tostringtheory 38c72cc2bd apply update to choices to set a loading modifier state when manipulating its internal state of choices/groups. This allows bulk updates to occur without re-rendering the list in O(n^2) complexity 2018-01-02 18:55:52 -06:00
Josh Johnson 3e88963326
Update README.md 2017-12-12 09:02:36 +00:00
Josh Johnson 497ed50903 Update example 2017-12-08 15:22:51 +00:00
16 changed files with 1055 additions and 122 deletions

View file

@ -1,10 +1,10 @@
# Choices.js ![Build Status](https://travis-ci.org/jshjohnson/Choices.svg?branch=master)
A vanilla, lightweight (~15kb gzipped 🎉), configurable select box/text input plugin. Similar to Select2 and Selectize but without the jQuery dependency.
A vanilla, lightweight (~18kb gzipped 🎉), configurable select box/text input plugin. Similar to Select2 and Selectize but without the jQuery dependency.
[Demo](https://joshuajohnson.co.uk/Choices/)
---
### 👉 Please use [develop](https://github.com/jshjohnson/Choices/tree/develop) as the base branch for pull requests 👈
### 👉 Please use [develop](https://github.com/jshjohnson/Choices/tree/develop) as the base branch for pull requests. This will be the next major release. Only minor fixes will be pushed into master 👈
---
## TL;DR
@ -52,7 +52,7 @@ Or include Choices directly:
const choices = new Choices(element);
// Pass reference
const choices = new Choices('[data-trigger']);
const choices = new Choices('[data-trigger]');
const choices = new Choices('.js-choice');
// Pass jQuery element
@ -99,6 +99,9 @@ Or include Choices directly:
maxItemText: (maxItemCount) => {
return `Only ${maxItemCount} values can be added.`;
},
itemComparer: (choice, item) => {
return choice === item;
},
classNames: {
containerOuter: 'choices',
containerInner: 'choices__inner',
@ -119,7 +122,7 @@ Or include Choices directly:
activeState: 'is-active',
focusState: 'is-focused',
openState: 'is-open',
disabledState: 'is-disaqbled',
disabledState: 'is-disabled',
highlightedState: 'is-highlighted',
hiddenState: 'is-hidden',
flippedState: 'is-flipped',
@ -458,6 +461,13 @@ const example = new Choices(element, {
**Usage:** The text that is shown when a user has focus on the input but has already reached the [max item count](https://github.com/jshjohnson/Choices#maxitemcount). To access the max item count, pass a function with a `maxItemCount` argument (see the [default config](https://github.com/jshjohnson/Choices#setup) for an example), otherwise pass a string.
### itemComparer
**Type:** `Function` **Default:** `strict equality`
**Input types affected:** `select-one`, `select-multiple`
**Usage:** Compare choice and value in appropriate way (e.g. deep equality for objects). To compare choice and value, pass a function with a `itemComparer` argument (see the [default config](https://github.com/jshjohnson/Choices#setup) for an example).
### classNames
**Type:** `Object` **Default:**

View file

@ -1,4 +1,4 @@
/*! choices.js v3.0.2 | (c) 2017 Josh Johnson | https://github.com/jshjohnson/Choices#readme */
/*! choices.js v3.0.4 | (c) 2018 Josh Johnson | https://github.com/jshjohnson/Choices#readme */
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
@ -78,11 +78,11 @@ return /******/ (function(modules) { // webpackBootstrap
var _index2 = _interopRequireDefault(_index);
var _index3 = __webpack_require__(30);
var _index3 = __webpack_require__(31);
var _utils = __webpack_require__(31);
var _utils = __webpack_require__(32);
__webpack_require__(32);
__webpack_require__(33);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
@ -149,11 +149,14 @@ return /******/ (function(modules) { // webpackBootstrap
noChoicesText: 'No choices to choose from',
itemSelectText: 'Press to select',
addItemText: function addItemText(value) {
return 'Press Enter to add <b>"' + value + '"</b>';
return 'Press Enter to add <b>"' + (0, _utils.stripHTML)(value) + '"</b>';
},
maxItemText: function maxItemText(maxItemCount) {
return 'Only ' + maxItemCount + ' values can be added.';
},
itemComparer: function itemComparer(choice, item) {
return choice === item;
},
uniqueItemText: 'Only unique values can be added.',
classNames: {
containerOuter: 'choices',
@ -576,6 +579,10 @@ return /******/ (function(modules) { // webpackBootstrap
}, {
key: 'render',
value: function render() {
if (this.store.isLoading()) {
return;
}
this.currentState = this.store.getState();
// Only render if our state has actually changed
@ -1063,7 +1070,7 @@ return /******/ (function(modules) { // webpackBootstrap
choiceValue.forEach(function (val) {
var foundChoice = choices.find(function (choice) {
// Check 'value' property exists and the choice isn't already selected
return choice.value === val;
return _this11.config.itemComparer(choice.value, val);
});
if (foundChoice) {
@ -1102,10 +1109,14 @@ return /******/ (function(modules) { // webpackBootstrap
if (!(0, _utils.isType)('Array', choices) || !value) {
return this;
}
// Clear choices if needed
if (replaceChoices) {
this._clearChoices();
}
this._setLoading(true);
// Add choices if passed
if (choices && choices.length) {
this.containerOuter.classList.remove(this.config.classNames.loadingState);
@ -1117,6 +1128,8 @@ return /******/ (function(modules) { // webpackBootstrap
}
});
}
this._setLoading(false);
}
}
return this;
@ -1483,7 +1496,7 @@ return /******/ (function(modules) { // webpackBootstrap
/**
* Apply or remove a loading state to the component.
* @param {Boolean} isLoading default value set to 'true'.
* @param {Boolean} setLoading default value set to 'true'.
* @return
* @private
*/
@ -1491,10 +1504,10 @@ return /******/ (function(modules) { // webpackBootstrap
}, {
key: '_handleLoadingState',
value: function _handleLoadingState() {
var isLoading = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
var setLoading = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
var placeholderItem = this.itemList.querySelector('.' + this.config.classNames.placeholder);
if (isLoading) {
if (setLoading) {
this.containerOuter.classList.add(this.config.classNames.loadingState);
this.containerOuter.setAttribute('aria-busy', 'true');
if (this.isSelectOneElement) {
@ -1541,6 +1554,9 @@ return /******/ (function(modules) { // webpackBootstrap
// Remove loading states/text
_this15._handleLoadingState(false);
// Add each result as a choice
_this15._setLoading(true);
parsedResults.forEach(function (result) {
if (result.choices) {
var groupId = result.id || null;
@ -1550,6 +1566,8 @@ return /******/ (function(modules) { // webpackBootstrap
}
});
_this15._setLoading(false);
if (_this15.isSelectOneElement) {
_this15._selectPlaceholderChoice();
}
@ -2689,6 +2707,11 @@ return /******/ (function(modules) { // webpackBootstrap
this.config.templates = (0, _utils.extend)(templates, userTemplates);
}
}, {
key: '_setLoading',
value: function _setLoading(isLoading) {
this.store.dispatch((0, _index3.setIsLoading)(isLoading));
}
/**
* Create DOM structure around passed select element
@ -2770,6 +2793,8 @@ return /******/ (function(modules) { // webpackBootstrap
this.highlightPosition = 0;
this.isSearching = false;
this._setLoading(true);
if (passedGroups && passedGroups.length) {
passedGroups.forEach(function (group) {
_this23._addGroup(group, group.id || null);
@ -2814,6 +2839,8 @@ return /******/ (function(modules) { // webpackBootstrap
}
});
}
this._setLoading(false);
} else if (this.isTextElement) {
// Add any preset values seperated by delimiter
this.presetItems.forEach(function (item) {
@ -3788,6 +3815,18 @@ return /******/ (function(modules) { // webpackBootstrap
this.store.subscribe(onChange);
}
/**
* Get loading state from store
* @return {Boolean} Loading State
*/
}, {
key: 'isLoading',
value: function isLoading() {
var state = this.store.getState();
return state.general.loading;
}
/**
* Get items from store
* @return {Array} Item objects
@ -4065,34 +4104,33 @@ return /******/ (function(modules) { // webpackBootstrap
*/
var ActionTypes = exports.ActionTypes = {
INIT: '@@redux/INIT'
};
/**
* Creates a Redux store that holds the state tree.
* The only way to change the data in the store is to call `dispatch()` on it.
*
* There should only be a single store in your app. To specify how different
* parts of the state tree respond to actions, you may combine several reducers
* into a single reducer function by using `combineReducers`.
*
* @param {Function} reducer A function that returns the next state tree, given
* the current state tree and the action to handle.
*
* @param {any} [preloadedState] The initial state. You may optionally specify it
* to hydrate the state from the server in universal apps, or to restore a
* previously serialized user session.
* If you use `combineReducers` to produce the root reducer function, this must be
* an object with the same shape as `combineReducers` keys.
*
* @param {Function} enhancer The store enhancer. You may optionally specify it
* to enhance the store with third-party capabilities such as middleware,
* time travel, persistence, etc. The only store enhancer that ships with Redux
* is `applyMiddleware()`.
*
* @returns {Store} A Redux store that lets you read the state, dispatch actions
* and subscribe to changes.
*/
function createStore(reducer, preloadedState, enhancer) {
/**
* Creates a Redux store that holds the state tree.
* The only way to change the data in the store is to call `dispatch()` on it.
*
* There should only be a single store in your app. To specify how different
* parts of the state tree respond to actions, you may combine several reducers
* into a single reducer function by using `combineReducers`.
*
* @param {Function} reducer A function that returns the next state tree, given
* the current state tree and the action to handle.
*
* @param {any} [preloadedState] The initial state. You may optionally specify it
* to hydrate the state from the server in universal apps, or to restore a
* previously serialized user session.
* If you use `combineReducers` to produce the root reducer function, this must be
* an object with the same shape as `combineReducers` keys.
*
* @param {Function} [enhancer] The store enhancer. You may optionally specify it
* to enhance the store with third-party capabilities such as middleware,
* time travel, persistence, etc. The only store enhancer that ships with Redux
* is `applyMiddleware()`.
*
* @returns {Store} A Redux store that lets you read the state, dispatch actions
* and subscribe to changes.
*/
};function createStore(reducer, preloadedState, enhancer) {
var _ref2;
if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
@ -4226,7 +4264,8 @@ return /******/ (function(modules) { // webpackBootstrap
var listeners = currentListeners = nextListeners;
for (var i = 0; i < listeners.length; i++) {
listeners[i]();
var listener = listeners[i];
listener();
}
return action;
@ -4255,7 +4294,7 @@ return /******/ (function(modules) { // webpackBootstrap
* Interoperability point for observable/reactive libraries.
* @returns {observable} A minimal observable of state changes.
* For more information, see the observable proposal:
* https://github.com/zenparsing/es-observable
* https://github.com/tc39/proposal-observable
*/
function observable() {
var _ref;
@ -4702,7 +4741,7 @@ return /******/ (function(modules) { // webpackBootstrap
var actionType = action && action.type;
var actionName = actionType && '"' + actionType.toString() + '"' || 'an action';
return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state.';
return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state. ' + 'If you want this reducer to hold no value, you can return null instead of undefined.';
}
function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
@ -4730,18 +4769,18 @@ return /******/ (function(modules) { // webpackBootstrap
}
}
function assertReducerSanity(reducers) {
function assertReducerShape(reducers) {
Object.keys(reducers).forEach(function (key) {
var reducer = reducers[key];
var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT });
if (typeof initialState === 'undefined') {
throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.');
throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined. If you don\'t want to set a value for this reducer, ' + 'you can use null instead of undefined.');
}
var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.');
if (typeof reducer(undefined, { type: type }) === 'undefined') {
throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.');
throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined, but can be null.');
}
});
}
@ -4780,23 +4819,24 @@ return /******/ (function(modules) { // webpackBootstrap
}
var finalReducerKeys = Object.keys(finalReducers);
var unexpectedKeyCache = void 0;
if (false) {
var unexpectedKeyCache = {};
unexpectedKeyCache = {};
}
var sanityError;
var shapeAssertionError = void 0;
try {
assertReducerSanity(finalReducers);
assertReducerShape(finalReducers);
} catch (e) {
sanityError = e;
shapeAssertionError = e;
}
return function combination() {
var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var action = arguments[1];
if (sanityError) {
throw sanityError;
if (shapeAssertionError) {
throw shapeAssertionError;
}
if (false) {
@ -4808,16 +4848,16 @@ return /******/ (function(modules) { // webpackBootstrap
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];
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') {
var errorMessage = getUndefinedStateErrorMessage(key, action);
var errorMessage = getUndefinedStateErrorMessage(_key, action);
throw new Error(errorMessage);
}
nextState[key] = nextStateForKey;
nextState[_key] = nextStateForKey;
hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
}
return hasChanged ? nextState : state;
@ -5007,13 +5047,11 @@ return /******/ (function(modules) { // webpackBootstrap
return funcs[0];
}
var last = funcs[funcs.length - 1];
var rest = funcs.slice(0, -1);
return function () {
return rest.reduceRight(function (composed, f) {
return f(composed);
}, last.apply(undefined, arguments));
};
return funcs.reduce(function (a, b) {
return function () {
return a(b.apply(undefined, arguments));
};
});
}
/***/ }),
@ -5040,12 +5078,17 @@ return /******/ (function(modules) { // webpackBootstrap
var _choices2 = _interopRequireDefault(_choices);
var _general = __webpack_require__(30);
var _general2 = _interopRequireDefault(_general);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var appReducer = (0, _redux.combineReducers)({
items: _items2.default,
groups: _groups2.default,
choices: _choices2.default
choices: _choices2.default,
general: _general2.default
});
var rootReducer = function rootReducer(passedState, action) {
@ -5305,6 +5348,36 @@ return /******/ (function(modules) { // webpackBootstrap
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var general = function general() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { loading: false };
var action = arguments[1];
switch (action.type) {
case 'LOADING':
{
return {
loading: action.isLoading
};
}
default:
{
return state;
}
}
};
exports.default = general;
/***/ }),
/* 31 */
/***/ (function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
@ -5388,11 +5461,18 @@ return /******/ (function(modules) { // webpackBootstrap
var clearAll = exports.clearAll = function clearAll() {
return {
type: 'CLEAR_ALL'
};
};
var setIsLoading = exports.setIsLoading = function setIsLoading(isLoading) {
return {
type: 'LOADING',
isLoading: isLoading
};
};
/***/ }),
/* 31 */
/* 32 */
/***/ (function(module, exports) {
'use strict';
@ -5833,14 +5913,12 @@ return /******/ (function(modules) { // webpackBootstrap
};
/**
* Remove html tags from a string
* @param {String} Initial string/html
* Escape html in a string
* @param {String} html Initial string/html
* @return {String} Sanitised string
*/
var stripHTML = exports.stripHTML = function stripHTML(html) {
var el = document.createElement("DIV");
el.innerHTML = html;
return el.textContent || el.innerText || "";
return html.replace(/&/g, '&amp;').replace(/>/g, '&rt;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
};
/**
@ -5901,7 +5979,7 @@ return /******/ (function(modules) { // webpackBootstrap
var width = input.offsetWidth;
if (value) {
var testEl = strToEl('<span>' + value + '</span>');
var testEl = strToEl('<span>' + stripHTML(value) + '</span>');
testEl.style.position = 'absolute';
testEl.style.padding = '0';
testEl.style.top = '-9999px';
@ -5984,7 +6062,7 @@ return /******/ (function(modules) { // webpackBootstrap
};
/***/ }),
/* 32 */
/* 33 */
/***/ (function(module, exports) {
'use strict';

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -78,3 +78,11 @@ export const clearAll = () => {
type: 'CLEAR_ALL',
};
};
export const setIsLoading = (isLoading) => {
return {
type: 'LOADING',
isLoading,
};
};

View file

@ -2,6 +2,7 @@ import Fuse from 'fuse.js';
import classNames from 'classnames';
import Store from './store/index.js';
import {
setIsLoading,
addItem,
removeItem,
highlightItem,
@ -21,6 +22,7 @@ import {
isType,
isElement,
strToEl,
stripHTML,
extend,
getWidthOfInput,
sortByAlpha,
@ -84,11 +86,14 @@ class Choices {
noChoicesText: 'No choices to choose from',
itemSelectText: 'Press to select',
addItemText: (value) => {
return `Press Enter to add <b>"${value}"</b>`;
return `Press Enter to add <b>"${stripHTML(value)}"</b>`;
},
maxItemText: (maxItemCount) => {
return `Only ${maxItemCount} values can be added.`;
},
itemComparer: (choice, item) => {
return choice === item;
},
uniqueItemText: 'Only unique values can be added.',
classNames: {
containerOuter: 'choices',
@ -480,6 +485,10 @@ class Choices {
* @private
*/
render() {
if(this.store.isLoading()) {
return;
}
this.currentState = this.store.getState();
// Only render if our state has actually changed
@ -942,7 +951,7 @@ class Choices {
choiceValue.forEach((val) => {
const foundChoice = choices.find((choice) => {
// Check 'value' property exists and the choice isn't already selected
return choice.value === val;
return this.config.itemComparer(choice.value, val);
});
if (foundChoice) {
@ -982,10 +991,14 @@ class Choices {
if (!isType('Array', choices) || !value) {
return this;
}
// Clear choices if needed
if (replaceChoices) {
this._clearChoices();
}
this._setLoading(true);
// Add choices if passed
if (choices && choices.length) {
this.containerOuter.classList.remove(this.config.classNames.loadingState);
@ -1010,6 +1023,9 @@ class Choices {
}
});
}
this._setLoading(false);
}
}
return this;
@ -1360,13 +1376,13 @@ class Choices {
/**
* Apply or remove a loading state to the component.
* @param {Boolean} isLoading default value set to 'true'.
* @param {Boolean} setLoading default value set to 'true'.
* @return
* @private
*/
_handleLoadingState(isLoading = true) {
_handleLoadingState(setLoading = true) {
let placeholderItem = this.itemList.querySelector(`.${this.config.classNames.placeholder}`);
if (isLoading) {
if (setLoading) {
this.containerOuter.classList.add(this.config.classNames.loadingState);
this.containerOuter.setAttribute('aria-busy', 'true');
if (this.isSelectOneElement) {
@ -1408,6 +1424,9 @@ class Choices {
// Remove loading states/text
this._handleLoadingState(false);
// Add each result as a choice
this._setLoading(true);
parsedResults.forEach((result) => {
if (result.choices) {
const groupId = (result.id || null);
@ -1430,6 +1449,8 @@ class Choices {
}
});
this._setLoading(false);
if (this.isSelectOneElement) {
this._selectPlaceholderChoice();
}
@ -2689,6 +2710,12 @@ class Choices {
this.config.templates = extend(templates, userTemplates);
}
_setLoading(isLoading) {
this.store.dispatch(
setIsLoading(isLoading)
);
}
/**
* Create DOM structure around passed select element
* @return
@ -2767,6 +2794,8 @@ class Choices {
this.highlightPosition = 0;
this.isSearching = false;
this._setLoading(true);
if (passedGroups && passedGroups.length) {
passedGroups.forEach((group) => {
this._addGroup(group, (group.id || null));
@ -2825,6 +2854,9 @@ class Choices {
}
});
}
this._setLoading(false);
} else if (this.isTextElement) {
// Add any preset values seperated by delimiter
this.presetItems.forEach((item) => {

View file

@ -432,15 +432,15 @@ export const isScrolledIntoView = (el, parent, direction = 1) => {
};
/**
* Remove html tags from a string
* @param {String} Initial string/html
* Escape html in a string
* @param {String} html Initial string/html
* @return {String} Sanitised string
*/
export const stripHTML = function(html) {
let el = document.createElement("DIV");
el.innerHTML = html;
return el.textContent || el.innerText || "";
};
export const stripHTML = html =>
html.replace(/&/g, '&amp;')
.replace(/>/g, '&rt;')
.replace(/</g, '&lt;')
.replace(/"/g, '&quot;');
/**
* Adds animation to an element and removes it upon animation completion
@ -501,7 +501,7 @@ export const getWidthOfInput = (input) => {
let width = input.offsetWidth;
if (value) {
const testEl = strToEl(`<span>${ value }</span>`);
const testEl = strToEl(`<span>${ stripHTML(value) }</span>`);
testEl.style.position = 'absolute';
testEl.style.padding = '0';
testEl.style.top = '-9999px';

View file

@ -0,0 +1,15 @@
const general = (state = { loading: false }, action) => {
switch (action.type) {
case 'LOADING': {
return {
loading: action.isLoading
};
}
default: {
return state;
}
}
};
export default general;

View file

@ -2,11 +2,13 @@ import { combineReducers } from 'redux';
import items from './items';
import groups from './groups';
import choices from './choices';
import general from './general';
const appReducer = combineReducers({
items,
groups,
choices,
general
});
const rootReducer = (passedState, action) => {

View file

@ -35,6 +35,15 @@ export default class Store {
this.store.subscribe(onChange);
}
/**
* Get loading state from store
* @return {Boolean} Loading State
*/
isLoading() {
const state = this.store.getState();
return state.general.loading;
}
/**
* Get items from store
* @return {Array} Item objects

View file

@ -1,6 +1,6 @@
{
"name": "choices.js",
"version": "3.0.2",
"version": "3.0.4",
"description": "A vanilla JS customisable text input/select box plugin",
"main": [
"./assets/scripts/dist/choices.js",

View file

@ -16,7 +16,7 @@
<meta name="theme-color" content="#ffffff">
<!-- Ignore these -->
<link rel="stylesheet" href="assets/styles/css/base.min.css?version=3.0.2">
<link rel="stylesheet" href="assets/styles/css/base.min.css?version=3.0.4">
<!-- End ignore these -->
<!-- Optional includes -->
@ -24,8 +24,8 @@
<!-- End optional includes -->
<!-- Choices includes -->
<link rel="stylesheet" href="assets/styles/css/choices.min.css?version=3.0.2">
<script src="assets/scripts/dist/choices.min.js?version=2.8.8"></script>
<link rel="stylesheet" href="assets/styles/css/choices.min.css?version=3.0.4">
<script src="assets/scripts/dist/choices.min.js?version=3.0.4"></script>
<!-- End Choices includes -->
<!--[if lt IE 9]>
@ -258,24 +258,26 @@
<option value="Vue">Vue</option>
</select>
<p>Below is an example of how you could have two select inputs depend on eachother. 'Boroughs' will only be enabled if
the value of 'States' is 'New York'</p>
<label for="states">States</label>
<select class="form-control" name="states" id="states" placeholder="Choose a state">
<option value="Michigan">Michigan</option>
<option value="Texas">Texas</option>
<option value="Chicago">Chicago</option>
<option value="New York">New York</option>
<option value="Washington">Washington</option>
<p>
Below is an example of how you could have two select inputs depend on eachother. 'Tube stations' will only be enabled if
the value of 'Cities' is 'London'
</p>
<label for="cities">Cities</label>
<select class="form-control" name="cities" id="cities" placeholder="Choose a city">
<option value="Leeds">Leeds</option>
<option value="Manchester">Manchester</option>
<option value="London">London</option>
<option value="Sheffield">Sheffield</option>
<option value="Newcastle">Newcastle</option>
</select>
<label for="boroughs">Boroughs</label>
<select class="form-control" name="boroughs" id="boroughs" placeholder="Choose a borough">
<option value="The Bronx">The Bronx</option>
<option value="Brooklyn">Brooklyn</option>
<option value="Manhattan">Manhattan</option>
<option value="Queens">Queens</option>
<option value="Staten Island">Staten Island</option>
<label for="tube-stations">Tube stations</label>
<select class="form-control" name="tube-stations" id="tube-stations" placeholder="Choose a tube station">
<option value="Moorgate">Moorgate</option>
<option value="St Pauls">St Pauls</option>
<option value="Old Street">Old Street</option>
<option value="Liverpool Street">Liverpool Street</option>
<option value="Kings Cross St. Pancras">Kings Cross St. Pancras</option>
</select>
</div>
</div>
@ -474,13 +476,14 @@
shouldSort: false,
});
var states = new Choices(document.getElementById('states'));
var cities = new Choices(document.getElementById('cities'));
var tubeStations = new Choices(document.getElementById('tube-stations')).disable();
states.passedElement.addEventListener('change', function(e) {
if (e.detail.value === 'New York') {
boroughs.enable();
cities.passedElement.addEventListener('change', function(e) {
if (e.detail.value === 'London') {
tubeStations.enable();
} else {
boroughs.disable();
tubeStations.disable();
}
});
@ -521,8 +524,6 @@
};
}
});
var boroughs = new Choices(document.getElementById('boroughs')).disable();
});
</script>

View file

@ -1,8 +1,9 @@
{
"name": "choices.js",
"version": "3.0.2",
"version": "3.0.4",
"description": "A vanilla JS customisable text input/select box plugin",
"main": "./assets/scripts/dist/choices.min.js",
"types": "./types/index.d.ts",
"scripts": {
"start": "node server.js",
"test": "karma start --single-run --no-auto-watch tests/karma.config.js",
@ -65,6 +66,7 @@
"dependencies": {
"classnames": "^2.2.5",
"fuse.js": "^2.2.2",
"opn": "^5.1.0",
"redux": "^3.3.1"
},
"npmName": "choices.js",

View file

@ -78,6 +78,7 @@ describe('Choices', () => {
expect(this.choices.config.noChoicesText).toEqual(jasmine.any(String));
expect(this.choices.config.itemSelectText).toEqual(jasmine.any(String));
expect(this.choices.config.classNames).toEqual(jasmine.any(Object));
expect(this.choices.config.itemComparer).toEqual(jasmine.any(Function));
expect(this.choices.config.callbackOnInit).toEqual(null);
expect(this.choices.config.callbackOnCreateTemplates).toEqual(null);
});
@ -1217,4 +1218,56 @@ describe('Choices', () => {
expect(selectedItems[0].customProperties).toBe(expectedCustomProperties);
});
});
describe('should allow to use object in value', function() {
beforeEach(function() {
this.input = document.createElement('select');
this.input.className = 'js-choices';
this.input.setAttribute('multiple', '');
document.body.appendChild(this.input);
this.choicesArray = [
{
label: 'One',
value: {
id: 1
}
},
{
label: 'Two',
value: {
id: 2
}
},
{
label: 'Three',
value: {
id: 3
}
}
];
});
afterEach(function() {
this.choices.destroy();
});
it('should allow the user to supply itemComparer via options', function() {
function comparer(choice, item) {
return choice.id === item.id;
}
this.choices = new Choices(this.input, {
itemComparer: comparer,
choices: this.choicesArray
});
this.choices.setValueByChoice({
id: 1
});
expect(this.choices.currentState.items[0].label).toBe(this.choicesArray[0].label);
});
});
});

723
types/index.d.ts vendored Normal file
View file

@ -0,0 +1,723 @@
declare module "choices.js" {
class Choices {
passedElement: Element;
constructor(element?: string | HTMLElement | HTMLCollectionOf<HTMLElement> | NodeList, userConfig?: Choices.Options);
new(element?: string | HTMLElement | HTMLCollectionOf<HTMLElement> | NodeList, userConfig?: Choices.Options): this;
/**
* Initialise Choices
* @return
* @public
*/
init(): void;
/**
* Destroy Choices and nullify values
* @return
* @public
*/
destroy(): void;
/**
* Render group choices into a DOM fragment and append to choice list
* @param {Array} groups Groups to add to list
* @param {Array} choices Choices to add to groups
* @param {DocumentFragment} fragment Fragment to add groups and options to (optional)
* @return {DocumentFragment} Populated options fragment
* @private
*/
renderGroups(groups: any[], choices: any[], fragment?: DocumentFragment): DocumentFragment;
/**
* Render choices into a DOM fragment and append to choice list
* @param {Array} choices Choices to add to list
* @param {DocumentFragment} fragment Fragment to add choices to (optional)
* @return {DocumentFragment} Populated choices fragment
* @private
*/
renderChoices(choices: any[], fragment?: DocumentFragment): DocumentFragment;
/**
* Render items into a DOM fragment and append to items list
* @param {Array} items Items to add to list
* @param {DocumentFragment} fragment Fragrment to add items to (optional)
* @return
* @private
*/
renderItems(items: any[], fragment?: DocumentFragment): void;
/**
* Render DOM with values
* @return
* @private
*/
render(): void;
/**
* Select item (a selected item can be deleted)
* @param {Element} item Element to select
* @param {boolean} runEvent Whether to highlight immediately or not. Defaults to true.
* @return {Object} Class instance
* @public
*/
highlightItem(item: Element, runEvent?: boolean): this;
/**
* Deselect item
* @param {Element} item Element to de-select
* @return {Object} Class instance
* @public
*/
unhighlightItem(item: Element): this;
/**
* Highlight items within store
* @return {Object} Class instance
* @public
*/
highlightAll(): this;
/**
* Deselect items within store
* @return {Object} Class instance
* @public
*/
unhighlightAll(): this;
/**
* Remove an item from the store by its value
* @param {String} value Value to search for
* @return {Object} Class instance
* @public
*/
removeActiveItemsByValue(value: string): this;
/**
* Remove all items from store array
* @note Removed items are soft deleted
* @param {Number} excludedId Optionally exclude item by ID
* @return {Object} Class instance
* @public
*/
removeActiveItems(excludedId?: number): this;
/**
* Remove all selected items from store
* @note Removed items are soft deleted
* @param {boolean} runEvent Whether to remove highlighted items immediately or not. Defaults to false.
* @return {Object} Class instance
* @public
*/
removeHighlightedItems(runEvent?: boolean): this;
/**
* Show dropdown to user by adding active state class
* @param {boolean} focusInput Whether to focus the input or not. Defaults to false.
* @return {Object} Class instance
* @public
*/
showDropdown(focusInput?: boolean): this;
/**
* Hide dropdown from user
* @param {boolean} focusInput Whether to blur input focus or not. Defaults to false.
* @return {Object} Class instance
* @public
*/
hideDropdown(blurInput?: boolean): this;
/**
* Determine whether to hide or show dropdown based on its current state
* @return {Object} Class instance
* @public
*/
toggleDropdown(): this;
/**
* Get value(s) of input (i.e. inputted items (text) or selected choices (select))
* @param {Boolean} valueOnly Get only values of selected items, otherwise return selected items
* @return {Array/String} selected value (select-one) or array of selected items (inputs & select-multiple)
* @public
*/
getValue(valueOnly?: boolean): string | string[];
/**
* Set value of input. If the input is a select box, a choice will be created and selected otherwise
* an item will created directly.
* @param {Array} args Array of value objects or value strings
* @return {Object} Class instance
* @public
*/
setValue(args: any[]): this;
/**
* Select value of select box via the value of an existing choice
* @param {Array/String} value An array of strings of a single string
* @return {Object} Class instance
* @public
*/
setValueByChoice(value: string | string[]): this;
/**
* Direct populate choices
* @param {Array} choices - Choices to insert
* @param {String} value - Name of 'value' property
* @param {String} label - Name of 'label' property
* @param {Boolean} replaceChoices Whether existing choices should be removed
* @return {Object} Class instance
* @public
*/
setChoices(choices: any[], value: string, label: string, replaceChoices?: boolean): this;
/**
* Clear items,choices and groups
* @note Hard delete
* @return {Object} Class instance
* @public
*/
clearStore(): this;
/**
* Set value of input to blank
* @return {Object} Class instance
* @public
*/
clearInput(): this;
/**
* Enable interaction with Choices
* @return {Object} Class instance
*/
enable(): this;
/**
* Disable interaction with Choices
* @return {Object} Class instance
* @public
*/
disable(): this;
/**
* Populate options via ajax callback
* @param {Function} fn Passed
* @return {Object} Class instance
* @public
*/
ajax(fn: (values: any) => any): this;
}
namespace Choices {
interface Options {
/**
* Optionally suppress console errors and warnings.
*
* Input types affected: text, select-single, select-multiple
* @default false
*/
silent?: boolean;
/**
* Add pre-selected items (see terminology) to text input.
*
* Pass an array of strings:
*
* ['value 1', 'value 2', 'value 3']
*
* Pass an array of objects:
*
* [{
* value: 'Value 1',
* label: 'Label 1',
* id: 1
* },
* {
* value: 'Value 2',
* label: 'Label 2',
* id: 2,
* customProperties: {
* random: 'I am a custom property'
* }
* }]
*
* Input types affected: text
* @default []
*/
items?: any[];
/**
* Add choices (see terminology) to select input.
*
* Pass an array of objects:
*
* [{
* value: 'Option 1',
* label: 'Option 1',
* selected: true,
* disabled: false,
* },
* {
* value: 'Option 2',
* label: 'Option 2',
* selected: false,
* disabled: true,
* customProperties: {
* description: 'Custom description about Option 2',
* random: 'Another random custom property'
* },
* }]
*
* Input types affected: select-one, select-multiple
* @default []
*/
choices?: any[];
/**
* The amount of choices to be rendered within the dropdown list ("-1" indicates no limit). This is useful if you have a lot of choices where it is easier for a user to use the search area to find a choice.
*
* Input types affected: select-one, select-multiple
* @default -1
*/
renderChoiceLimit?: number;
/**
* The amount of items a user can input/select ("-1" indicates no limit).
*
* Input types affected: text, select-multiple
* @default -1
*/
maxItemCount?: number;
/**
* Whether a user can add items.
*
* Input types affected: text
* @default true
*/
addItems?: boolean;
/**
* Whether a user can remove items.
*
* Input types affected: text, select-multiple
* @default true
*/
removeItems?: boolean;
/**
* Whether each item should have a remove button.
*
* Input types affected: text, select-one, select-multiple
* @default false
*/
removeItemButton?: boolean;
/**
* Whether a user can edit items. An item's value can be edited by pressing the backspace.
*
* Input types affected: text
* @default false
*/
editItems?: boolean;
/**
* Whether each inputted/chosen item should be unique.
*
* Input types affected: text, select-multiple
* @default true
*/
duplicateItems?: boolean;
/**
* What divides each value. The default delimiter seperates each value with a comma: "Value 1, Value 2, Value 3".
*
* Input types affected: text, select-multiple
* @default true
*/
delimiter?: string;
/**
* Whether a user can paste into the input.
*
* Input types affected: text, select-multiple
* @default true
*/
paste?: boolean;
/**
* Whether a search area should be shown. *Note:* Multiple select boxes will _always_ show search areas.
*
* Input types affected: select-one
* @default true
*/
searchEnabled?: boolean;
/**
* Whether choices should be filtered by input or not. If false, the search event will still emit, but choices will not be filtered.
*
* Input types affected: select-one
* @default true
*/
searchChoices?: boolean;
/**
* Specify which fields should be used when a user is searching. If you have added custom properties to your choices, you can add these values thus: ['label', 'value', 'customProperties.example'].
*
* Input types affected: select-one, select-multiple
* @default ['label', 'value']
*/
searchFields?: string[];
/**
* The minimum length a search value should be before choices are searched.
*
* Input types affected: select-one, select-multiple
* @default 1
*/
searchFloor?: number;
/**
* The maximum amount of search results to show.
*
* Input types affected: select-one, select-multiple
* @default 4
*/
searchResultLimit?: number;
/**
* Whether the dropdown should appear above (top) or below (bottom) the input. By default, if there is not enough space within the window the dropdown will appear above the input, otherwise below it.
*
* Input types affected: select-one, select-multiple
* @default 'auto'
*/
position?: string;
/**
* Whether the scroll position should reset after adding an item.
*
* Input types affected: select-multiple
* @default true
*/
resetScrollPosition?: boolean;
/**
* A filter that will need to pass for a user to successfully add an item.
*
* Input types affected: text
* @default null
*/
regexFilter?: RegExp;
/**
* Whether choices and groups should be sorted. If false, choices/groups will appear in the order they were given.
*
* Input types affected: select-one, select-multiple
* @default true
*/
shouldSort?: boolean;
/**
* Whether items should be sorted. If false, items will appear in the order they were selected.
*
* Input types affected: text, select-multiple
* @default false
*/
shouldSortItems?: boolean;
/**
* The function that will sort choices and items before they are displayed (unless a user is searching). By default choices and items are sorted by alphabetical order.
*
* Input types affected: select-one, select-multiple
*
* @example
* // Sorting via length of label from largest to smallest
* const example = new Choices(element, {
* sortFilter: function(a, b) {
* return b.label.length - a.label.length;
* },
* };
*
* @default sortByAlpha
*/
sortFilter?: (current: any, next: any) => number;
/**
* Whether the input should show a placeholder. Used in conjunction with placeholderValue. If placeholder is set to true and no value is passed to placeholderValue, the passed input's placeholder attribute will be used as the placeholder value.
*
* Note: For single select boxes, the recommended way of adding a placeholder is as follows:
* <select>
* <option placeholder>This is a placeholder</option>
* <option>...</option>
* <option>...</option>
* <option>...</option>
* </select>
*
* Input types affected: text, select-multiple
* @default true
*/
placeholder?: boolean;
/**
* The value of the inputs placeholder.
*
* Input types affected: text, select-multiple
* @default null
*/
placeholderValue?: string;
/**
* The value of the search inputs placeholder.
*
* Input types affected: select-one
* @default null
*/
searchPlaceholderValue?: string;
/**
* Prepend a value to each item added/selected.
*
* Input types affected: text, select-one, select-multiple
* @default null
*/
prependValue?: string;
/**
* Append a value to each item added/selected.
*
* Input types affected: text, select-one, select-multiple
* @default null
*/
appendValue?: string;
/**
* Whether selected choices should be removed from the list. By default choices are removed when they are selected in multiple select box. To always render choices pass always.
*
* Input types affected: select-one, select-multiple
* @default 'auto'
*/
renderSelectedChoices?: string;
/**
* The text that is shown whilst choices are being populated via AJAX.
*
* Input types affected: select-one, select-multiple
* @default 'Loading...'
*/
loadingText?: string;
/**
* The text that is shown when a user's search has returned no results. Optionally pass a function returning a string.
*
* Input types affected: select-one, select-multiple
* @default 'No results found'
*/
noResultsText?: string | (() => string);
/**
* The text that is shown when a user has selected all possible choices. Optionally pass a function returning a string.
*
* Input types affected: select-multiple
* @default 'No choices to choose from'
*/
noChoicesText?: string | (() => string);
/**
* The text that is shown when a user hovers over a selectable choice.
*
* Input types affected: select-one, select-multiple
* @default 'Press to select'
*/
itemSelectText?: string;
/**
* The text that is shown when a user has inputted a new item but has not pressed the enter key. To access the current input value, pass a function with a value argument (see the [default config](https://github.com/jshjohnson/Choices#setup) for an example), otherwise pass a string.
*
* Input types affected: text
* @default 'Press Enter to add "${value}"'
*/
addItemText?: ((value: string) => string) | string;
/**
* The text that is shown when a user has focus on the input but has already reached the max item count. To access the max item count, pass a function with a maxItemCount argument (see the [default config](https://github.com/jshjohnson/Choices#setup) for an example), otherwise pass a string.
*
* Input types affected: text
* @default 'Only ${maxItemCount} values can be added.'
*/
maxItemText?: (maxItemCount: number) => string,
/**
* The text that is shown when a user has submitted a new item that is already present in the selected list. To access the current input value, pass a function with a value argument, otherwise pass a string.
*
* @default 'Only unique values can be added.'
*/
uniqueItemText?: ((value: string) => string) | string;
/**
* Classes added to HTML generated by Choices. By default classnames follow the BEM notation.
*/
classNames?: {
/**
* @default 'choices'
*/
containerOuter?: string;
/**
* @default 'choices__inner'
*/
containerInner?: string;
/**
* @default 'choices__input'
*/
input?: string;
/**
* @default 'choices__input--cloned'
*/
inputCloned?: string;
/**
* @default 'choices__list'
*/
list?: string;
/**
* @default 'choices__list--multiple'
*/
listItems?: string;
/**
* @default 'choices__list--single'
*/
listSingle?: string;
/**
* @default 'choices__list--dropdown'
*/
listDropdown?: string;
/**
* @default 'choices__item'
*/
item?: string;
/**
* @default 'choices__item--selectable'
*/
itemSelectable?: string;
/**
* @default 'choices__item--disabled'
*/
itemDisabled?: string;
/**
* @default 'choices__item--choice'
*/
itemOption?: string;
/**
* @default 'choices__group'
*/
group?: string;
/**
* @default 'choices__heading'
*/
groupHeading?: string;
/**
* @default 'choices__placeholder'
*/
placeholder?: string;
/**
* @default 'choices__button'
*/
button?: string;
/**
* @default 'is-active'
*/
activeState?: string;
/**
* @default 'is-focused'
*/
focusState?: string;
/**
* @default 'is-open'
*/
openState?: string;
/**
* @default 'is-disabled'
*/
disabledState?: string;
/**
* @default 'is-highlighted'
*/
highlightedState?: string;
/**
* @default 'is-hidden'
*/
hiddenState?: string;
/**
* @default 'is-flipped'
*/
flippedState?: string;
/**
* @default 'is-loading'
*/
loadingState?: string;
/**
* @default 'has-no-results'
*/
noResults?: string;
/**
* @default 'has-no-choices'
*/
noChoices?: string;
};
/**
* Choices uses the great Fuse library for searching. You can find more options here: https://github.com/krisk/Fuse#options
*/
fuseOptions?: {
[index: string]: any;
/**
* @default 'score'
*/
include?: string;
};
/**
* Function to run once Choices initialises.
*
* Input types affected: text, select-one, select-multiple
*
* @default null
*/
callbackOnInit?: () => any;
/**
* Function to run on template creation. Through this callback it is possible to provide custom templates for the various components of Choices (see terminology). For Choices to work with custom templates, it is important you maintain the various data attributes defined [here](https://github.com/jshjohnson/Choices/blob/67f29c286aa21d88847adfcd6304dc7d068dc01f/assets/scripts/src/choices.js#L1993-L2067).
*
* Input types affected: text, select-one, select-multiple
*
* @default null
*/
callbackOnCreateTemplates?: (template: string) => string;
}
}
export = Choices;
}

View file

@ -1,4 +1,4 @@
// Example usage: npm --newVersion=3.0.2 run version
// Example usage: npm --newVersion=3.0.4 run version
const fs = require('fs');
const path = require('path');