This commit is contained in:
Alexander 2023-07-25 12:00:30 +02:00 committed by GitHub
commit d67e910f04
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
19 changed files with 470 additions and 125 deletions

View file

@ -282,6 +282,41 @@ describe('Choices - select multiple', () => {
}); });
}); });
describe('unique values only', () => {
describe('unique values', () => {
beforeEach(() => {
cy.get('[data-test-hook=unique-values]')
.find('.choices__input--cloned')
.type('Choice 1')
.type('{enter}');
});
it('only allows me to input unique values', () => {
cy.get('[data-test-hook=unique-values]')
.find('.choices__list--multiple')
.first()
.children()
.should($items => {
expect($items.length).to.equal(1);
});
});
describe('inputting a non-unique value', () => {
it('displays dropdown prompt', () => {
cy.get('[data-test-hook=unique-values]')
.find('.choices__list--dropdown')
.should('be.visible')
.should($dropdown => {
const dropdownText = $dropdown.text().trim();
expect(dropdownText).to.equal(
'Only unique values can be added',
);
});
});
});
});
});
describe('disabled choice', () => { describe('disabled choice', () => {
describe('selecting a disabled choice', () => { describe('selecting a disabled choice', () => {
beforeEach(() => { beforeEach(() => {
@ -308,26 +343,56 @@ describe('Choices - select multiple', () => {
}); });
}); });
describe('adding user-created choices', () => {
it('allows the user to add choices', () => {
const newChoice = 'New Choice';
cy.get('[data-test-hook=add-items]')
.find('.choices__input--cloned')
.type(newChoice)
.type('{enter}');
cy.get('[data-test-hook=add-items]')
.find('.choices__list--multiple')
.last()
.should($el => {
expect($el).to.contain(newChoice);
});
});
});
describe('adding items disabled', () => { describe('adding items disabled', () => {
/* /*
{ {
addItems: false, addItems: false,
} }
*/ */
it('disables the search input', () => { it('disables adding new items', () => {
const newChoice = 'New Choice';
cy.get('[data-test-hook=add-items-disabled]') cy.get('[data-test-hook=add-items-disabled]')
.find('.choices__input--cloned') .find('.choices__input--cloned')
.should('be.disabled'); .type(newChoice)
.type('{enter}');
cy.get('[data-test-hook=add-items-disabled]')
.find('.choices__list--multiple')
.last()
.should($el => {
expect($el).to.not.contain(newChoice);
});
}); });
describe('on click', () => { it('allows selecting items', () => {
it('does not open choice dropdown', () => { const choice = 'Choice 2';
cy.get('[data-test-hook=add-items-disabled]') cy.get('[data-test-hook=add-items-disabled]')
.find('.choices') .find('.choices__input--cloned')
.click() .type(choice)
.find('.choices__list--dropdown') .type('{enter}');
.should('not.have.class', 'is-active'); cy.get('[data-test-hook=add-items-disabled]')
}); .find('.choices__list--multiple')
.last()
.should($el => {
expect($el).to.contain(choice);
});
}); });
}); });

View file

@ -271,28 +271,66 @@ describe('Choices - select one', () => {
}); });
}); });
describe('adding user-created choices', () => {
beforeEach(() => {
cy.get('[data-test-hook=add-items]')
.find('.choices')
.click();
});
it('allows the user to add choices', () => {
const newChoice = 'New Choice';
cy.get('[data-test-hook=add-items]')
.find('.choices__input--cloned')
.type(newChoice)
.type('{enter}');
cy.get('[data-test-hook=add-items]')
.find('.choices__list--single .choices__item')
.should($el => {
expect($el).to.contain(newChoice);
});
});
});
describe('adding items disabled', () => { describe('adding items disabled', () => {
/* /*
{ {
addItems: false, addItems: false,
} }
*/ */
it('disables the search input', () => { beforeEach(() => {
cy.get('[data-test-hook=add-items-disabled]')
.find('.choices')
.click();
});
it('disables adding new items', () => {
const newChoice = 'New Choice';
cy.get('[data-test-hook=add-items-disabled]') cy.get('[data-test-hook=add-items-disabled]')
.find('.choices__input--cloned') .find('.choices__input--cloned')
.should('be.disabled'); .type(newChoice)
.type('{enter}');
cy.get('[data-test-hook=add-items-disabled]')
.find('.choices__list--single .choices__item')
.last()
.should($el => {
expect($el).to.not.contain(newChoice);
});
}); });
describe('on click', () => { it('allows selecting items', () => {
it('does not open choice dropdown', () => { const choice = 'Choice 2';
cy.get('[data-test-hook=add-items-disabled]') cy.get('[data-test-hook=add-items-disabled]')
.find('.choices') .find('.choices__input--cloned')
.click(); .type(choice)
.type('{enter}');
cy.get('[data-test-hook=add-items-disabled]') cy.get('[data-test-hook=add-items-disabled]')
.find('.choices__list--dropdown') .find('.choices__list--single .choices__item')
.should('not.have.class', 'is-active'); .last()
}); .should($el => {
expect($el).to.contain(choice);
});
}); });
}); });

View file

@ -304,10 +304,28 @@ describe('Choices - text element', () => {
}); });
describe('adding items disabled', () => { describe('adding items disabled', () => {
it('does not allow me to input data', () => { /*
cy.get('[data-test-hook=adding-items-disabled]') {
addItems: false,
}
*/
beforeEach(() => {
cy.get('[data-test-hook=add-items-disabled]')
.find('.choices')
.click();
});
it('disables adding new items', () => {
const newChoice = 'New Choice';
cy.get('[data-test-hook=add-items-disabled]')
.find('.choices__input--cloned') .find('.choices__input--cloned')
.should('be.disabled'); .type(newChoice)
.type('{enter}');
cy.get('[data-test-hook=add-items-disabled]')
.find('.choices__list--multiple')
.last()
.should($el => {
expect($el).to.not.contain(newChoice);
});
}); });
}); });

View file

@ -1,4 +1,4 @@
/*! choices.js v10.2.0 | © 2022 Josh Johnson | https://github.com/jshjohnson/Choices#readme */ /*! choices.js v10.2.0 | © 2023 Josh Johnson | https://github.com/jshjohnson/Choices#readme */
(function webpackUniversalModuleDefinition(root, factory) { (function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object') if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(); module.exports = factory();
@ -390,7 +390,7 @@ var Choices = /** @class */function () {
this._store.subscribe(this._render); this._store.subscribe(this._render);
this._render(); this._render();
this._addEventListeners(); this._addEventListeners();
var shouldDisable = !this.config.addItems || this.passedElement.element.hasAttribute('disabled'); var shouldDisable = this.passedElement.element.hasAttribute('disabled');
if (shouldDisable) { if (shouldDisable) {
this.disable(); this.disable();
} }
@ -785,8 +785,13 @@ var Choices = /** @class */function () {
Choices.prototype._renderChoices = function () { Choices.prototype._renderChoices = function () {
var _this = this; var _this = this;
var _a = this._store, var _a = this._store,
activeItems = _a.activeItems,
disabledChoices = _a.disabledChoices,
choices = _a.choices,
activeGroups = _a.activeGroups, activeGroups = _a.activeGroups,
activeChoices = _a.activeChoices; activeChoices = _a.activeChoices;
var value = this.input.value;
var canAddItem = this._canAddItem(activeItems, value);
var choiceListFragment = document.createDocumentFragment(); var choiceListFragment = document.createDocumentFragment();
this.choiceList.clear(); this.choiceList.clear();
if (this.config.resetScrollPosition) { if (this.config.resetScrollPosition) {
@ -809,14 +814,34 @@ var Choices = /** @class */function () {
} }
// If we have choices to show // If we have choices to show
if (choiceListFragment.childNodes && choiceListFragment.childNodes.length > 0) { if (choiceListFragment.childNodes && choiceListFragment.childNodes.length > 0) {
var activeItems = this._store.activeItems; var addNotice = false;
var canAddItem = this._canAddItem(activeItems, this.input.value);
// ...and we can select them // ...and we can select them
if (canAddItem.response) { if (canAddItem.response) {
// ...append them and highlight the first choice // ...append them
this.choiceList.append(choiceListFragment); this.choiceList.append(choiceListFragment);
this._highlightChoice(); // ...handle case that items can be added
if (this.config.addItems && value) {
var isInChoices = (0, utils_1.existsInArray)(choices, value);
addNotice = true;
if (this._isSelectMultipleElement && (0, utils_1.existsInArray)(disabledChoices, value)) {
// adding disabled element is disabled here, so remove message
addNotice = false;
} else if (this._isSelectOneElement && isInChoices) {
// adding existing element is disabled here, so remove message
addNotice = false;
}
// ...highlight the first choice when element exists in choices
if (isInChoices) {
this._highlightChoice();
}
} else {
// ...highlight the first choice
this._highlightChoice();
}
} else { } else {
addNotice = true;
}
if (addNotice) {
var notice = this._getTemplate('notice', canAddItem.notice); var notice = this._getTemplate('notice', canAddItem.notice);
this.choiceList.append(notice); this.choiceList.append(notice);
} }
@ -824,7 +849,9 @@ var Choices = /** @class */function () {
// Otherwise show a notice // Otherwise show a notice
var dropdownItem = void 0; var dropdownItem = void 0;
var notice = void 0; var notice = void 0;
if (this._isSearching) { if (this.config.addItems && canAddItem.response && value) {
dropdownItem = this._getTemplate('notice', canAddItem.notice);
} else if (this._isSearching) {
notice = typeof this.config.noResultsText === 'function' ? this.config.noResultsText() : this.config.noResultsText; notice = typeof this.config.noResultsText === 'function' ? this.config.noResultsText() : this.config.noResultsText;
dropdownItem = this._getTemplate('notice', notice, 'no-results'); dropdownItem = this._getTemplate('notice', notice, 'no-results');
} else { } else {
@ -1166,10 +1193,10 @@ var Choices = /** @class */function () {
canAddItem = false; canAddItem = false;
notice = typeof this.config.uniqueItemText === 'function' ? this.config.uniqueItemText(value) : this.config.uniqueItemText; notice = typeof this.config.uniqueItemText === 'function' ? this.config.uniqueItemText(value) : this.config.uniqueItemText;
} }
if (this._isTextElement && this.config.addItems && canAddItem && typeof this.config.addItemFilter === 'function' && !this.config.addItemFilter(value)) { }
canAddItem = false; if (this.config.addItems && canAddItem && typeof this.config.addItemFilter === 'function' && !this.config.addItemFilter(value)) {
notice = typeof this.config.customAddItemText === 'function' ? this.config.customAddItemText(value) : this.config.customAddItemText; canAddItem = false;
} notice = typeof this.config.customAddItemText === 'function' ? this.config.customAddItemText(value) : this.config.customAddItemText;
} }
return { return {
response: canAddItem, response: canAddItem,
@ -1259,7 +1286,10 @@ var Choices = /** @class */function () {
}; };
Choices.prototype._onKeyDown = function (event) { Choices.prototype._onKeyDown = function (event) {
var keyCode = event.keyCode; var keyCode = event.keyCode;
var activeItems = this._store.activeItems; var _a = this._store,
activeItems = _a.activeItems,
choices = _a.choices,
disabledChoices = _a.disabledChoices;
var hasFocusedInput = this.input.isFocussed; var hasFocusedInput = this.input.isFocussed;
var hasActiveDropdown = this.dropdown.isActive; var hasActiveDropdown = this.dropdown.isActive;
var hasItems = this.itemList.hasChildren(); var hasItems = this.itemList.hasChildren();
@ -1290,14 +1320,22 @@ var Choices = /** @class */function () {
case A_KEY: case A_KEY:
return this._onSelectKey(event, hasItems); return this._onSelectKey(event, hasItems);
case ENTER_KEY: case ENTER_KEY:
return this._onEnterKey(event, activeItems, hasActiveDropdown); // existing choices are not producable
if (this._isSelectOneElement) {
return this._onEnterKey(event, activeItems, choices, hasActiveDropdown);
}
return this._onEnterKey(event, activeItems, disabledChoices, hasActiveDropdown);
case ESC_KEY: case ESC_KEY:
return this._onEscapeKey(hasActiveDropdown); return this._onEscapeKey(hasActiveDropdown);
case UP_KEY: case UP_KEY:
case PAGE_UP_KEY: case PAGE_UP_KEY:
case DOWN_KEY: case DOWN_KEY:
case PAGE_DOWN_KEY: case PAGE_DOWN_KEY:
return this._onDirectionKey(event, hasActiveDropdown); // don't activate deselect for existing choices
if (this._isSelectOneElement) {
return this._onDirectionKey(event, activeItems, choices, hasActiveDropdown);
}
return this._onDirectionKey(event, activeItems, disabledChoices, hasActiveDropdown);
case DELETE_KEY: case DELETE_KEY:
case BACK_KEY: case BACK_KEY:
return this._onDeleteKey(event, activeItems, hasFocusedInput); return this._onDeleteKey(event, activeItems, hasFocusedInput);
@ -1312,10 +1350,10 @@ var Choices = /** @class */function () {
var canAddItem = this._canAddItem(activeItems, value); var canAddItem = this._canAddItem(activeItems, value);
var backKey = constants_1.KEY_CODES.BACK_KEY, var backKey = constants_1.KEY_CODES.BACK_KEY,
deleteKey = constants_1.KEY_CODES.DELETE_KEY; deleteKey = constants_1.KEY_CODES.DELETE_KEY;
var canShowDropdownNotice = this.config.addItems && canAddItem.notice && value;
// We are typing into a text input and have a value, we want to show a dropdown // We are typing into a text input and have a value, we want to show a dropdown
// notice. Otherwise hide the dropdown // notice. Otherwise hide the dropdown
if (this._isTextElement) { if (this._isTextElement) {
var canShowDropdownNotice = canAddItem.notice && value;
if (canShowDropdownNotice) { if (canShowDropdownNotice) {
var dropdownItem = this._getTemplate('notice', canAddItem.notice); var dropdownItem = this._getTemplate('notice', canAddItem.notice);
this.dropdown.element.innerHTML = dropdownItem.outerHTML; this.dropdown.element.innerHTML = dropdownItem.outerHTML;
@ -1331,7 +1369,7 @@ var Choices = /** @class */function () {
if (userHasRemovedValue && canReactivateChoices) { if (userHasRemovedValue && canReactivateChoices) {
this._isSearching = false; this._isSearching = false;
this._store.dispatch((0, choices_1.activateChoices)(true)); this._store.dispatch((0, choices_1.activateChoices)(true));
} else if (canSearch) { } else if (canSearch || canShowDropdownNotice) {
this._handleSearch(this.input.rawValue); this._handleSearch(this.input.rawValue);
} }
} }
@ -1350,28 +1388,17 @@ var Choices = /** @class */function () {
} }
} }
}; };
Choices.prototype._onEnterKey = function (event, activeItems, hasActiveDropdown) { Choices.prototype._onEnterKey = function (event, activeItems, nonproducibleChoices, hasActiveDropdown) {
var target = event.target; var target = event.target;
var enterKey = constants_1.KEY_CODES.ENTER_KEY; var enterKey = constants_1.KEY_CODES.ENTER_KEY;
var targetWasButton = target && target.hasAttribute('data-button'); var targetWasButton = target && target.hasAttribute('data-button');
if (this._isTextElement && target && target.value) { var highlightedChoice = null;
var value = this.input.value;
var canAddItem = this._canAddItem(activeItems, value);
if (canAddItem.response) {
this.hideDropdown(true);
this._addItem({
value: value
});
this._triggerChange(value);
this.clearInput();
}
}
if (targetWasButton) { if (targetWasButton) {
this._handleButtonAction(activeItems, target); this._handleButtonAction(activeItems, target);
event.preventDefault(); event.preventDefault();
} }
if (hasActiveDropdown) { if (hasActiveDropdown) {
var highlightedChoice = this.dropdown.getChild(".".concat(this.config.classNames.highlightedState)); highlightedChoice = this.dropdown.getChild(".".concat(this.config.classNames.highlightedState));
if (highlightedChoice) { if (highlightedChoice) {
// add enter keyCode value // add enter keyCode value
if (activeItems[0]) { if (activeItems[0]) {
@ -1384,6 +1411,19 @@ var Choices = /** @class */function () {
} else if (this._isSelectOneElement) { } else if (this._isSelectOneElement) {
this.showDropdown(); this.showDropdown();
event.preventDefault(); event.preventDefault();
return;
}
if (this.config.addItems && !highlightedChoice && target && target.value) {
var value = this.input.value;
var canAddItem = this._canAddItem(activeItems, value);
if (canAddItem.response && !(0, utils_1.existsInArray)(nonproducibleChoices, value)) {
this.hideDropdown(true);
this._setChoiceOrItem({
value: value
});
this._triggerChange(value);
this.clearInput();
}
} }
}; };
Choices.prototype._onEscapeKey = function (hasActiveDropdown) { Choices.prototype._onEscapeKey = function (hasActiveDropdown) {
@ -1392,9 +1432,10 @@ var Choices = /** @class */function () {
this.containerOuter.focus(); this.containerOuter.focus();
} }
}; };
Choices.prototype._onDirectionKey = function (event, hasActiveDropdown) { Choices.prototype._onDirectionKey = function (event, activeItems, nonproducibleChoices, hasActiveDropdown) {
var keyCode = event.keyCode, var keyCode = event.keyCode,
metaKey = event.metaKey; metaKey = event.metaKey,
target = event.target;
var downKey = constants_1.KEY_CODES.DOWN_KEY, var downKey = constants_1.KEY_CODES.DOWN_KEY,
pageUpKey = constants_1.KEY_CODES.PAGE_UP_KEY, pageUpKey = constants_1.KEY_CODES.PAGE_UP_KEY,
pageDownKey = constants_1.KEY_CODES.PAGE_DOWN_KEY; pageDownKey = constants_1.KEY_CODES.PAGE_DOWN_KEY;
@ -1427,6 +1468,13 @@ var Choices = /** @class */function () {
this.choiceList.scrollToChildElement(nextEl, directionInt); this.choiceList.scrollToChildElement(nextEl, directionInt);
} }
this._highlightChoice(nextEl); this._highlightChoice(nextEl);
} else if (this.config.addItems && target && target.value) {
// can unselect all items for creating new options
var value = this.input.value;
var canAddItem = this._canAddItem(activeItems, value);
if (canAddItem.response && !(0, utils_1.existsInArray)(nonproducibleChoices, value)) {
this.unhighlightAll();
}
} }
// Prevent default to maintain cursor position whilst // Prevent default to maintain cursor position whilst
// traversing dropdown options // traversing dropdown options
@ -3759,6 +3807,18 @@ var Store = /** @class */function () {
enumerable: false, enumerable: false,
configurable: true configurable: true
}); });
Object.defineProperty(Store.prototype, "disabledChoices", {
/**
* Get disabled choices from store
*/
get: function () {
return this.choices.filter(function (choice) {
return choice.disabled === true;
});
},
enumerable: false,
configurable: true
});
Object.defineProperty(Store.prototype, "selectableChoices", { Object.defineProperty(Store.prototype, "selectableChoices", {
/** /**
* Get selectable choices from store * Get selectable choices from store

File diff suppressed because one or more lines are too long

View file

@ -1 +1 @@
/*! choices.js v10.2.0 | © 2022 Josh Johnson | https://github.com/jshjohnson/Choices#readme */ /*! choices.js v10.2.0 | © 2023 Josh Johnson | https://github.com/jshjohnson/Choices#readme */

View file

@ -88,6 +88,22 @@
</select> </select>
</div> </div>
<div data-test-hook="unique-values">
<label for="choices-unique-values">Unique values</label>
<select
class="form-control"
name="choices-unique-values"
id="choices-unique-values"
multiple
>
<option value="Choice 1" selected>Choice 1</option>
<option value="Choice 1">Choice 1</option>
<option value="Choice 2">Choice 2</option>
<option value="Choice 3">Choice 3</option>
<option value="Choice 4">Choice 4</option>
</select>
</div>
<div data-test-hook="disabled-choice"> <div data-test-hook="disabled-choice">
<label for="choices-disabled-choice">Disabled choice</label> <label for="choices-disabled-choice">Disabled choice</label>
<select <select
@ -103,6 +119,20 @@
</select> </select>
</div> </div>
<div data-test-hook="add-items">
<label for="choices-add">Add user-created choices</label>
<select
class="form-control"
name="choices-add-items"
id="choices-add-items"
multiple
>
<option value="Choice 1" selected>Choice 1</option>
<option value="Choice 2">Choice 2</option>
<option value="Choice 3">Choice 3</option>
</select>
</div>
<div data-test-hook="add-items-disabled"> <div data-test-hook="add-items-disabled">
<label for="choices-add-items-disabled">Add items disabled</label> <label for="choices-add-items-disabled">Add items disabled</label>
<select <select
@ -401,9 +431,7 @@
</div> </div>
<script> <script>
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
const choicesBasic = new Choices('#choices-basic', { const choicesBasic = new Choices('#choices-basic', { addItems: false, allowHTML: true, });
allowHTML: true,
});
document document
.querySelector('button.disable') .querySelector('button.disable')
@ -425,6 +453,13 @@
new Choices('#choices-disabled-choice', { new Choices('#choices-disabled-choice', {
allowHTML: true, allowHTML: true,
}); });
new Choices('#choices-unique-values', {
duplicateItemsAllowed: false,
});
new Choices('#choices-add-items', {
addItems: true,
});
new Choices('#choices-add-items-disabled', { new Choices('#choices-add-items-disabled', {
allowHTML: true, allowHTML: true,
@ -555,7 +590,8 @@
new Choices('#choices-search-by-label', { new Choices('#choices-search-by-label', {
allowHTML: true, allowHTML: true,
searchFields: ['label'] searchFields: ['label'],
addItems: false,
}); });
new Choices('#choices-allowhtml-undefined', { new Choices('#choices-allowhtml-undefined', {

View file

@ -108,6 +108,19 @@
</select> </select>
</div> </div>
<div data-test-hook="add-items">
<label for="choices-add-items">Add user-created choices</label>
<select
class="form-control"
name="choices-add-items"
id="choices-add-items"
>
<option value="Choice 1" selected>Choice 1</option>
<option value="Choice 2">Choice 2</option>
<option value="Choice 3">Choice 3</option>
</select>
</div>
<div data-test-hook="add-items-disabled"> <div data-test-hook="add-items-disabled">
<label for="choices-add-items-disabled">Add items disabled</label> <label for="choices-add-items-disabled">Add items disabled</label>
<select <select
@ -422,7 +435,7 @@
<script> <script>
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
const choicesBasic = new Choices('#choices-basic', { const choicesBasic = new Choices('#choices-basic', {
allowHTML: true, allowHTML: true, addItems: false
}); });
document document
@ -471,6 +484,10 @@
], ],
}); });
new Choices('#choices-add-items', {
addItems: true,
});
new Choices('#choices-add-items-disabled', { new Choices('#choices-add-items-disabled', {
allowHTML: true, allowHTML: true,
addItems: false, addItems: false,
@ -615,7 +632,8 @@
new Choices('#choices-search-by-label', { new Choices('#choices-search-by-label', {
allowHTML: true, allowHTML: true,
searchFields: ['label'] searchFields: ['label'],
addItems: false,
}); });
new Choices('#choices-allowhtml-undefined', { new Choices('#choices-allowhtml-undefined', {

View file

@ -105,11 +105,11 @@
/> />
</div> </div>
<div data-test-hook="adding-items-disabled"> <div data-test-hook="add-items-disabled">
<label for="choices-adding-items-disabled">Add items disabled</label> <label for="choices-add-items-disabled">Add items disabled</label>
<input <input
class="form-control" class="form-control"
id="choices-adding-items-disabled" id="choices-add-items-disabled"
type="text" type="text"
/> />
</div> </div>

View file

@ -157,9 +157,9 @@ declare class Choices implements Choices {
_onKeyDown(event: KeyboardEvent): void; _onKeyDown(event: KeyboardEvent): void;
_onKeyUp({ target, keyCode, }: Pick<KeyboardEvent, 'target' | 'keyCode'>): void; _onKeyUp({ target, keyCode, }: Pick<KeyboardEvent, 'target' | 'keyCode'>): void;
_onSelectKey(event: KeyboardEvent, hasItems: boolean): void; _onSelectKey(event: KeyboardEvent, hasItems: boolean): void;
_onEnterKey(event: KeyboardEvent, activeItems: Item[], hasActiveDropdown: boolean): void; _onEnterKey(event: KeyboardEvent, activeItems: Item[], nonproducibleChoices: Choice[], hasActiveDropdown: boolean): void;
_onEscapeKey(hasActiveDropdown: boolean): void; _onEscapeKey(hasActiveDropdown: boolean): void;
_onDirectionKey(event: KeyboardEvent, hasActiveDropdown: boolean): void; _onDirectionKey(event: KeyboardEvent, activeItems: Item[], nonproducibleChoices: Choice[], hasActiveDropdown: boolean): void;
_onDeleteKey(event: KeyboardEvent, activeItems: Item[], hasFocusedInput: boolean): void; _onDeleteKey(event: KeyboardEvent, activeItems: Item[], hasFocusedInput: boolean): void;
_onTouchMove(): void; _onTouchMove(): void;
_onTouchEnd(event: TouchEvent): void; _onTouchEnd(event: TouchEvent): void;

File diff suppressed because one or more lines are too long

View file

@ -97,9 +97,9 @@ export interface Options {
*/ */
maxItemCount: number; maxItemCount: number;
/** /**
* Whether a user can add items. * Whether a user can add new items.
* *
* **Input types affected:** text * **Input types affected:** text, select, select-multiple
* *
* @default true * @default true
*/ */

View file

@ -38,6 +38,10 @@ export default class Store {
* Get active choices from store * Get active choices from store
*/ */
get activeChoices(): Choice[]; get activeChoices(): Choice[];
/**
* Get disabled choices from store
*/
get disabledChoices(): Choice[];
/** /**
* Get selectable choices from store * Get selectable choices from store
*/ */

View file

@ -1 +1 @@
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../../../src/scripts/store/store.ts"],"names":[],"mappings":"AACA,OAAO,EAAe,KAAK,IAAI,MAAM,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAChE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAG5C,MAAM,CAAC,OAAO,OAAO,KAAK;IACxB,MAAM,EAAE,MAAM,CAAC;;IAUf;;OAEG;IACH,SAAS,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI;IAIrC;;OAEG;IACH,QAAQ,CAAC,MAAM,EAAE,SAAS,GAAG,IAAI;IAIjC;;OAEG;IACH,IAAI,KAAK,IAAI,KAAK,CAEjB;IAED;;OAEG;IACH,IAAI,KAAK,IAAI,IAAI,EAAE,CAElB;IAED;;OAEG;IACH,IAAI,WAAW,IAAI,IAAI,EAAE,CAExB;IAED;;OAEG;IACH,IAAI,sBAAsB,IAAI,IAAI,EAAE,CAEnC;IAED;;OAEG;IACH,IAAI,OAAO,IAAI,MAAM,EAAE,CAEtB;IAED;;OAEG;IACH,IAAI,aAAa,IAAI,MAAM,EAAE,CAE5B;IAED;;OAEG;IACH,IAAI,iBAAiB,IAAI,MAAM,EAAE,CAEhC;IAED;;OAEG;IACH,IAAI,iBAAiB,IAAI,MAAM,EAAE,CAIhC;IAED;;OAEG;IACH,IAAI,iBAAiB,IAAI,MAAM,GAAG,SAAS,CAI1C;IAED;;OAEG;IACH,IAAI,MAAM,IAAI,KAAK,EAAE,CAEpB;IAED;;OAEG;IACH,IAAI,YAAY,IAAI,KAAK,EAAE,CAW1B;IAED;;OAEG;IACH,SAAS,IAAI,OAAO;IAIpB;;OAEG;IACH,aAAa,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAI7C;;OAEG;IACH,YAAY,CAAC,EAAE,EAAE,MAAM,GAAG,KAAK,GAAG,SAAS;CAG5C"} {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../../../src/scripts/store/store.ts"],"names":[],"mappings":"AACA,OAAO,EAAe,KAAK,IAAI,MAAM,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAChE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAG5C,MAAM,CAAC,OAAO,OAAO,KAAK;IACxB,MAAM,EAAE,MAAM,CAAC;;IAUf;;OAEG;IACH,SAAS,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI;IAIrC;;OAEG;IACH,QAAQ,CAAC,MAAM,EAAE,SAAS,GAAG,IAAI;IAIjC;;OAEG;IACH,IAAI,KAAK,IAAI,KAAK,CAEjB;IAED;;OAEG;IACH,IAAI,KAAK,IAAI,IAAI,EAAE,CAElB;IAED;;OAEG;IACH,IAAI,WAAW,IAAI,IAAI,EAAE,CAExB;IAED;;OAEG;IACH,IAAI,sBAAsB,IAAI,IAAI,EAAE,CAEnC;IAED;;OAEG;IACH,IAAI,OAAO,IAAI,MAAM,EAAE,CAEtB;IAED;;OAEG;IACH,IAAI,aAAa,IAAI,MAAM,EAAE,CAE5B;IAED;;OAEG;IACH,IAAI,eAAe,IAAI,MAAM,EAAE,CAE9B;IAED;;OAEG;IACH,IAAI,iBAAiB,IAAI,MAAM,EAAE,CAEhC;IAED;;OAEG;IACH,IAAI,iBAAiB,IAAI,MAAM,EAAE,CAIhC;IAED;;OAEG;IACH,IAAI,iBAAiB,IAAI,MAAM,GAAG,SAAS,CAI1C;IAED;;OAEG;IACH,IAAI,MAAM,IAAI,KAAK,EAAE,CAEpB;IAED;;OAEG;IACH,IAAI,YAAY,IAAI,KAAK,EAAE,CAW1B;IAED;;OAEG;IACH,SAAS,IAAI,OAAO;IAIpB;;OAEG;IACH,aAAa,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAI7C;;OAEG;IACH,YAAY,CAAC,EAAE,EAAE,MAAM,GAAG,KAAK,GAAG,SAAS;CAG5C"}

View file

@ -2176,6 +2176,7 @@ describe('choices', () => {
describe('_onKeyDown', () => { describe('_onKeyDown', () => {
let activeItems; let activeItems;
let disabledChoices;
let hasItems; let hasItems;
let hasActiveDropdown; let hasActiveDropdown;
let hasFocussedInput; let hasFocussedInput;
@ -2188,7 +2189,7 @@ describe('choices', () => {
instance._onDirectionKey = stub(); instance._onDirectionKey = stub();
instance._onDeleteKey = stub(); instance._onDeleteKey = stub();
({ activeItems } = instance._store); ({ activeItems, disabledChoices } = instance._store);
hasItems = instance.itemList.hasChildren(); hasItems = instance.itemList.hasChildren();
hasActiveDropdown = instance.dropdown.isActive; hasActiveDropdown = instance.dropdown.isActive;
hasFocussedInput = instance.input.isFocussed; hasFocussedInput = instance.input.isFocussed;
@ -2212,6 +2213,8 @@ describe('choices', () => {
expect(instance._onDirectionKey).to.have.been.calledWith( expect(instance._onDirectionKey).to.have.been.calledWith(
event, event,
activeItems,
disabledChoices,
hasActiveDropdown, hasActiveDropdown,
); );
}); });
@ -2244,6 +2247,7 @@ describe('choices', () => {
expect(instance._onEnterKey).to.have.been.calledWith( expect(instance._onEnterKey).to.have.been.calledWith(
event, event,
activeItems, activeItems,
disabledChoices,
hasActiveDropdown, hasActiveDropdown,
); );
}); });

View file

@ -3,11 +3,11 @@ import merge from 'deepmerge';
import Fuse from 'fuse.js'; import Fuse from 'fuse.js';
import { import {
Result,
activateChoices, activateChoices,
addChoice, addChoice,
clearChoices, clearChoices,
filterChoices, filterChoices,
Result,
} from './actions/choices'; } from './actions/choices';
import { addGroup } from './actions/groups'; import { addGroup } from './actions/groups';
import { addItem, highlightItem, removeItem } from './actions/items'; import { addItem, highlightItem, removeItem } from './actions/items';
@ -35,7 +35,6 @@ import { Notice } from './interfaces/notice';
import { Options } from './interfaces/options'; import { Options } from './interfaces/options';
import { PassedElement } from './interfaces/passed-element'; import { PassedElement } from './interfaces/passed-element';
import { State } from './interfaces/state'; import { State } from './interfaces/state';
import { import {
diff, diff,
existsInArray, existsInArray,
@ -44,9 +43,9 @@ import {
getType, getType,
isScrolledIntoView, isScrolledIntoView,
isType, isType,
parseCustomProperties,
sortByScore, sortByScore,
strToEl, strToEl,
parseCustomProperties,
} from './lib/utils'; } from './lib/utils';
import { defaultState } from './reducers'; import { defaultState } from './reducers';
import Store from './store/store'; import Store from './store/store';
@ -347,9 +346,7 @@ class Choices implements Choices {
this._render(); this._render();
this._addEventListeners(); this._addEventListeners();
const shouldDisable = const shouldDisable = this.passedElement.element.hasAttribute('disabled');
!this.config.addItems ||
this.passedElement.element.hasAttribute('disabled');
if (shouldDisable) { if (shouldDisable) {
this.disable(); this.disable();
@ -791,7 +788,16 @@ class Choices implements Choices {
} }
_renderChoices(): void { _renderChoices(): void {
const { activeGroups, activeChoices } = this._store; const {
activeItems,
disabledChoices,
choices,
activeGroups,
activeChoices,
} = this._store;
const { value } = this.input;
const canAddItem = this._canAddItem(activeItems, value);
let choiceListFragment = document.createDocumentFragment(); let choiceListFragment = document.createDocumentFragment();
this.choiceList.clear(); this.choiceList.clear();
@ -830,15 +836,37 @@ class Choices implements Choices {
choiceListFragment.childNodes && choiceListFragment.childNodes &&
choiceListFragment.childNodes.length > 0 choiceListFragment.childNodes.length > 0
) { ) {
const { activeItems } = this._store; let addNotice = false;
const canAddItem = this._canAddItem(activeItems, this.input.value);
// ...and we can select them // ...and we can select them
if (canAddItem.response) { if (canAddItem.response) {
// ...append them and highlight the first choice // ...append them
this.choiceList.append(choiceListFragment); this.choiceList.append(choiceListFragment);
this._highlightChoice(); // ...handle case that items can be added
if (this.config.addItems && value) {
const isInChoices = existsInArray(choices, value);
addNotice = true;
if (
this._isSelectMultipleElement &&
existsInArray(disabledChoices, value)
) {
// adding disabled element is disabled here, so remove message
addNotice = false;
} else if (this._isSelectOneElement && isInChoices) {
// adding existing element is disabled here, so remove message
addNotice = false;
}
// ...highlight the first choice when element exists in choices
if (isInChoices) {
this._highlightChoice();
}
} else {
// ...highlight the first choice
this._highlightChoice();
}
} else { } else {
addNotice = true;
}
if (addNotice) {
const notice = this._getTemplate('notice', canAddItem.notice); const notice = this._getTemplate('notice', canAddItem.notice);
this.choiceList.append(notice); this.choiceList.append(notice);
} }
@ -847,7 +875,9 @@ class Choices implements Choices {
let dropdownItem; let dropdownItem;
let notice; let notice;
if (this._isSearching) { if (this.config.addItems && canAddItem.response && value) {
dropdownItem = this._getTemplate('notice', canAddItem.notice);
} else if (this._isSearching) {
notice = notice =
typeof this.config.noResultsText === 'function' typeof this.config.noResultsText === 'function'
? this.config.noResultsText() ? this.config.noResultsText()
@ -862,7 +892,6 @@ class Choices implements Choices {
dropdownItem = this._getTemplate('notice', notice, 'no-choices'); dropdownItem = this._getTemplate('notice', notice, 'no-choices');
} }
this.choiceList.append(dropdownItem); this.choiceList.append(dropdownItem);
} }
} }
@ -1294,20 +1323,19 @@ class Choices implements Choices {
? this.config.uniqueItemText(value) ? this.config.uniqueItemText(value)
: this.config.uniqueItemText; : this.config.uniqueItemText;
} }
}
if ( if (
this._isTextElement && this.config.addItems &&
this.config.addItems && canAddItem &&
canAddItem && typeof this.config.addItemFilter === 'function' &&
typeof this.config.addItemFilter === 'function' && !this.config.addItemFilter(value)
!this.config.addItemFilter(value) ) {
) { canAddItem = false;
canAddItem = false; notice =
notice = typeof this.config.customAddItemText === 'function'
typeof this.config.customAddItemText === 'function' ? this.config.customAddItemText(value)
? this.config.customAddItemText(value) : this.config.customAddItemText;
: this.config.customAddItemText;
}
} }
return { return {
@ -1436,7 +1464,7 @@ class Choices implements Choices {
_onKeyDown(event: KeyboardEvent): void { _onKeyDown(event: KeyboardEvent): void {
const { keyCode } = event; const { keyCode } = event;
const { activeItems } = this._store; const { activeItems, choices, disabledChoices } = this._store;
const hasFocusedInput = this.input.isFocussed; const hasFocusedInput = this.input.isFocussed;
const hasActiveDropdown = this.dropdown.isActive; const hasActiveDropdown = this.dropdown.isActive;
const hasItems = this.itemList.hasChildren(); const hasItems = this.itemList.hasChildren();
@ -1473,14 +1501,44 @@ class Choices implements Choices {
case A_KEY: case A_KEY:
return this._onSelectKey(event, hasItems); return this._onSelectKey(event, hasItems);
case ENTER_KEY: case ENTER_KEY:
return this._onEnterKey(event, activeItems, hasActiveDropdown); // existing choices are not producable
if (this._isSelectOneElement) {
return this._onEnterKey(
event,
activeItems,
choices,
hasActiveDropdown,
);
}
return this._onEnterKey(
event,
activeItems,
disabledChoices,
hasActiveDropdown,
);
case ESC_KEY: case ESC_KEY:
return this._onEscapeKey(hasActiveDropdown); return this._onEscapeKey(hasActiveDropdown);
case UP_KEY: case UP_KEY:
case PAGE_UP_KEY: case PAGE_UP_KEY:
case DOWN_KEY: case DOWN_KEY:
case PAGE_DOWN_KEY: case PAGE_DOWN_KEY:
return this._onDirectionKey(event, hasActiveDropdown); // don't activate deselect for existing choices
if (this._isSelectOneElement) {
return this._onDirectionKey(
event,
activeItems,
choices,
hasActiveDropdown,
);
}
return this._onDirectionKey(
event,
activeItems,
disabledChoices,
hasActiveDropdown,
);
case DELETE_KEY: case DELETE_KEY:
case BACK_KEY: case BACK_KEY:
return this._onDeleteKey(event, activeItems, hasFocusedInput); return this._onDeleteKey(event, activeItems, hasFocusedInput);
@ -1496,12 +1554,12 @@ class Choices implements Choices {
const { activeItems } = this._store; const { activeItems } = this._store;
const canAddItem = this._canAddItem(activeItems, value); const canAddItem = this._canAddItem(activeItems, value);
const { BACK_KEY: backKey, DELETE_KEY: deleteKey } = KEY_CODES; const { BACK_KEY: backKey, DELETE_KEY: deleteKey } = KEY_CODES;
const canShowDropdownNotice =
this.config.addItems && canAddItem.notice && value;
// We are typing into a text input and have a value, we want to show a dropdown // We are typing into a text input and have a value, we want to show a dropdown
// notice. Otherwise hide the dropdown // notice. Otherwise hide the dropdown
if (this._isTextElement) { if (this._isTextElement) {
const canShowDropdownNotice = canAddItem.notice && value;
if (canShowDropdownNotice) { if (canShowDropdownNotice) {
const dropdownItem = this._getTemplate('notice', canAddItem.notice); const dropdownItem = this._getTemplate('notice', canAddItem.notice);
this.dropdown.element.innerHTML = dropdownItem.outerHTML; this.dropdown.element.innerHTML = dropdownItem.outerHTML;
@ -1519,7 +1577,7 @@ class Choices implements Choices {
if (userHasRemovedValue && canReactivateChoices) { if (userHasRemovedValue && canReactivateChoices) {
this._isSearching = false; this._isSearching = false;
this._store.dispatch(activateChoices(true)); this._store.dispatch(activateChoices(true));
} else if (canSearch) { } else if (canSearch || canShowDropdownNotice) {
this._handleSearch(this.input.rawValue); this._handleSearch(this.input.rawValue);
} }
} }
@ -1549,24 +1607,14 @@ class Choices implements Choices {
_onEnterKey( _onEnterKey(
event: KeyboardEvent, event: KeyboardEvent,
activeItems: Item[], activeItems: Item[],
nonproducibleChoices: Choice[],
hasActiveDropdown: boolean, hasActiveDropdown: boolean,
): void { ): void {
const { target } = event; const { target } = event;
const { ENTER_KEY: enterKey } = KEY_CODES; const { ENTER_KEY: enterKey } = KEY_CODES;
const targetWasButton = const targetWasButton =
target && (target as HTMLElement).hasAttribute('data-button'); target && (target as HTMLElement).hasAttribute('data-button');
let highlightedChoice: null | HTMLElement = null;
if (this._isTextElement && target && (target as HTMLInputElement).value) {
const { value } = this.input;
const canAddItem = this._canAddItem(activeItems, value);
if (canAddItem.response) {
this.hideDropdown(true);
this._addItem({ value });
this._triggerChange(value);
this.clearInput();
}
}
if (targetWasButton) { if (targetWasButton) {
this._handleButtonAction(activeItems, target as HTMLElement); this._handleButtonAction(activeItems, target as HTMLElement);
@ -1574,7 +1622,7 @@ class Choices implements Choices {
} }
if (hasActiveDropdown) { if (hasActiveDropdown) {
const highlightedChoice = this.dropdown.getChild( highlightedChoice = this.dropdown.getChild(
`.${this.config.classNames.highlightedState}`, `.${this.config.classNames.highlightedState}`,
); );
@ -1590,6 +1638,25 @@ class Choices implements Choices {
} else if (this._isSelectOneElement) { } else if (this._isSelectOneElement) {
this.showDropdown(); this.showDropdown();
event.preventDefault(); event.preventDefault();
return;
}
if (
this.config.addItems &&
!highlightedChoice &&
target &&
(target as HTMLInputElement).value
) {
const { value } = this.input;
const canAddItem = this._canAddItem(activeItems, value);
if (canAddItem.response && !existsInArray(nonproducibleChoices, value)) {
this.hideDropdown(true);
this._setChoiceOrItem({ value });
this._triggerChange(value);
this.clearInput();
}
} }
} }
@ -1600,8 +1667,13 @@ class Choices implements Choices {
} }
} }
_onDirectionKey(event: KeyboardEvent, hasActiveDropdown: boolean): void { _onDirectionKey(
const { keyCode, metaKey } = event; event: KeyboardEvent,
activeItems: Item[],
nonproducibleChoices: Choice[],
hasActiveDropdown: boolean,
): void {
const { keyCode, metaKey, target } = event;
const { const {
DOWN_KEY: downKey, DOWN_KEY: downKey,
PAGE_UP_KEY: pageUpKey, PAGE_UP_KEY: pageUpKey,
@ -1656,6 +1728,20 @@ class Choices implements Choices {
this.choiceList.scrollToChildElement(nextEl, directionInt); this.choiceList.scrollToChildElement(nextEl, directionInt);
} }
this._highlightChoice(nextEl); this._highlightChoice(nextEl);
} else if (
this.config.addItems &&
target &&
(target as HTMLInputElement).value
) {
// can unselect all items for creating new options
const { value } = this.input;
const canAddItem = this._canAddItem(activeItems, value);
if (
canAddItem.response &&
!existsInArray(nonproducibleChoices, value)
) {
this.unhighlightAll();
}
} }
// Prevent default to maintain cursor position whilst // Prevent default to maintain cursor position whilst

View file

@ -103,9 +103,9 @@ export interface Options {
maxItemCount: number; maxItemCount: number;
/** /**
* Whether a user can add items. * Whether a user can add new items.
* *
* **Input types affected:** text * **Input types affected:** text, select, select-multiple
* *
* @default true * @default true
*/ */

View file

@ -191,6 +191,15 @@ describe('reducers/store', () => {
}); });
}); });
describe('disabledChoices getter', () => {
it('returns choices that are disabled', () => {
const expectedResponse = state.choices.filter(
choice => choice.disabled,
);
expect(instance.disabledChoices).to.eql(expectedResponse);
});
});
describe('selectableChoices getter', () => { describe('selectableChoices getter', () => {
it('returns choices that are not disabled', () => { it('returns choices that are not disabled', () => {
const expectedResponse = state.choices.filter( const expectedResponse = state.choices.filter(

View file

@ -73,6 +73,13 @@ export default class Store {
return this.choices.filter((choice) => choice.active === true); return this.choices.filter((choice) => choice.active === true);
} }
/**
* Get disabled choices from store
*/
get disabledChoices(): Choice[] {
return this.choices.filter(choice => choice.disabled === true);
}
/** /**
* Get selectable choices from store * Get selectable choices from store
*/ */