Refactoring + rename selected to highlighted

This commit is contained in:
Josh Johnson 2016-06-30 13:57:56 +01:00
parent b45715c5be
commit 6a0ed866cf
10 changed files with 157 additions and 145 deletions

View file

@ -48,7 +48,7 @@ Coming soon.
item: 'choices__item', item: 'choices__item',
itemSelectable: 'choices__item--selectable', itemSelectable: 'choices__item--selectable',
itemDisabled: 'choices__item--disabled', itemDisabled: 'choices__item--disabled',
itemOption: 'choices__item--choice', itemChoice: 'choices__item--choice',
group: 'choices__group', group: 'choices__group',
groupHeading : 'choices__heading', groupHeading : 'choices__heading',
button: 'choices__button', button: 'choices__button',
@ -59,7 +59,6 @@ Coming soon.
highlightedState: 'is-highlighted', highlightedState: 'is-highlighted',
hiddenState: 'is-hidden', hiddenState: 'is-hidden',
flippedState: 'is-flipped', flippedState: 'is-flipped',
selectedState: 'is-selected',
}, },
callbackOnInit: () => {}, callbackOnInit: () => {},
callbackOnAddItem: (id, value, passedInput) => {}, callbackOnAddItem: (id, value, passedInput) => {},
@ -76,7 +75,7 @@ To install via NPM, run `npm install --save-dev choices.js`
| ------ | ---------- | | ------ | ---------- |
| Choice | A choice is a value a user can select. A choice would be equivelant to the `<option></option>` element within a select input. | | Choice | A choice is a value a user can select. A choice would be equivelant to the `<option></option>` element within a select input. |
| Group | A group is a collection of choices. A group should be seen as equivalent to a `<optgroup></optgroup>` element within a select input.| | Group | A group is a collection of choices. A group should be seen as equivalent to a `<optgroup></optgroup>` element within a select input.|
| Item | An item is an inputted value (if you are using Choices with a text input) or a selected choice (if you are using Choices with a select element). | | Item | An item is an inputted value (if you are using Choices with a text input) or a selected choice (if you are using Choices with a select element). An item is equivelent to a selected option element: `<option selected></option>`|
## Options ## Options
### items ### items
@ -135,17 +134,17 @@ Pass an array of objects:
<strong>Usage:</strong> What divides each value (only affects text input types). <strong>Usage:</strong> What divides each value (only affects text input types).
### allowDuplicates ### duplicates
<strong>Type:</strong> `Boolean` <strong>Default:</strong>`true` <strong>Type:</strong> `Boolean` <strong>Default:</strong>`true`
<strong>Usage:</strong> Whether a user can input a duplicate item (only affects text input types). <strong>Usage:</strong> Whether a user can input a duplicate item (only affects text input types).
### allowPaste ### paste
<strong>Type:</strong> `Boolean` <strong>Default:</strong>`true` <strong>Type:</strong> `Boolean` <strong>Default:</strong>`true`
<strong>Usage:</strong> Whether a user can paste into the input. <strong>Usage:</strong> Whether a user can paste into the input.
### allowSearch ### search
<strong>Type:</strong> `Boolean` <strong>Default:</strong>`true` <strong>Type:</strong> `Boolean` <strong>Default:</strong>`true`
<strong>Usage:</strong> Whether a user can filter options by searching (only affects select input types). <strong>Usage:</strong> Whether a user can filter options by searching (only affects select input types).
@ -178,7 +177,7 @@ Pass an array of objects:
### highlightAll ### highlightAll
<strong>Type:</strong> `Boolean` <strong>Default:</strong>`true` <strong>Type:</strong> `Boolean` <strong>Default:</strong>`true`
<strong>Usage:</strong> Whether a user can highlight items. <strong>Usage:</strong> Whether a user can highlight items. Highlighted items can be deleted by pressing the backspace key.
### loadingText ### loadingText
<strong>Type:</strong> `String` <strong>Default:</strong>`Loading...` <strong>Type:</strong> `String` <strong>Default:</strong>`Loading...`
@ -212,7 +211,7 @@ classNames: {
highlightedState: 'is-highlighted', highlightedState: 'is-highlighted',
hiddenState: 'is-hidden', hiddenState: 'is-hidden',
flippedState: 'is-flipped', flippedState: 'is-flipped',
selectedState: 'is-selected', selectedState: 'is-highlighted',
} }
``` ```
@ -265,7 +264,7 @@ choices.disable();
<strong>Usage:</strong> Remove each selectable item. <strong>Usage:</strong> Remove each selectable item.
### removeSelectedItems(); ### removeHighlightedItems();
<strong>Usage:</strong> Remove each item the user has selected. <strong>Usage:</strong> Remove each item the user has selected.

File diff suppressed because one or more lines are too long

View file

@ -16,11 +16,11 @@ export const removeItem = (id, choiceId) => {
} }
}; };
export const selectItem = (id, selected) => { export const highlightItem = (id, highlighted) => {
return { return {
type: 'SELECT_ITEM', type: 'HIGHLIGHT_ITEM',
id, id,
selected, highlighted,
} }
}; };

View file

@ -1,19 +1,15 @@
'use strict'; 'use strict';
import { addItem, removeItem, selectItem, addChoice, filterChoices, activateChoices, addGroup, clearAll } from './actions/index'; import { addItem, removeItem, highlightItem, addChoice, filterChoices, activateChoices, addGroup, clearAll } from './actions/index';
import { isScrolledIntoView, getAdjacentEl, findAncestor, wrap, isType, strToEl, extend, getWidthOfInput, debounce } from './lib/utils.js'; import { isScrolledIntoView, getAdjacentEl, findAncestor, wrap, isType, isElement, strToEl, extend, getWidthOfInput, debounce } from './lib/utils.js';
import Fuse from 'fuse.js'; import Fuse from 'fuse.js';
import Store from './store/index.js'; import Store from './store/index.js';
/** /**
* Choices * Choices
*
* To do:
* - Pagination
* - Single select box search in dropdown
*/ */
export class Choices { export class Choices {
constructor(element = '[data-option]', userConfig = {}) { constructor(element = '[data-choice]', userConfig = {}) {
// If there are multiple elements, create a new instance // If there are multiple elements, create a new instance
// for each element besides the first one (as that already has an instance) // for each element besides the first one (as that already has an instance)
@ -68,7 +64,7 @@ export class Choices {
highlightedState: 'is-highlighted', highlightedState: 'is-highlighted',
hiddenState: 'is-hidden', hiddenState: 'is-hidden',
flippedState: 'is-flipped', flippedState: 'is-flipped',
selectedState: 'is-selected', loadingState: 'is-loading',
}, },
callbackOnInit: () => {}, callbackOnInit: () => {},
callbackOnAddItem: (id, value, passedInput) => {}, callbackOnAddItem: (id, value, passedInput) => {},
@ -121,11 +117,11 @@ export class Choices {
if (!cuttingTheMustard) console.error('Choices: Your browser doesn\'t support Choices'); if (!cuttingTheMustard) console.error('Choices: Your browser doesn\'t support Choices');
// Input type check // Input type check
const canInit = this.passedElement && ['select-one', 'select-multiple', 'text'].includes(this.passedElement.type); const canInit = this.passedElement && isElement(this.passedElement) && ['select-one', 'select-multiple', 'text'].includes(this.passedElement.type);
if(canInit) { if(canInit) {
// If element has already been initalised with Choices // If element has already been initalised with Choices
if(this.passedElement.hasAttribute('data-choice')) return if(this.passedElement.getAttribute('data-choice') === 'active') return
// Let's go // Let's go
this.init(); this.init();
@ -196,10 +192,10 @@ export class Choices {
* @return {Object} Class instance * @return {Object} Class instance
* @public * @public
*/ */
selectItem(item) { highlightItem(item) {
if(!item) return; if(!item) return;
const id = item.id; const id = item.id;
this.store.dispatch(selectItem(id, true)); this.store.dispatch(highlightItem(id, true));
return this; return this;
} }
@ -210,10 +206,10 @@ export class Choices {
* @return {Object} Class instance * @return {Object} Class instance
* @public * @public
*/ */
deselectItem(item) { unhighlightItem(item) {
if(!item) return; if(!item) return;
const id = item.id; const id = item.id;
this.store.dispatch(selectItem(id, false)); this.store.dispatch(highlightItem(id, false));
return this; return this;
} }
@ -226,7 +222,7 @@ export class Choices {
highlightAll() { highlightAll() {
const items = this.store.getItems(); const items = this.store.getItems();
items.forEach((item) => { items.forEach((item) => {
this.selectItem(item); this.highlightItem(item);
}); });
return this; return this;
@ -237,10 +233,10 @@ export class Choices {
* @return {Object} Class instance * @return {Object} Class instance
* @public * @public
*/ */
deselectAll() { unhighlightAll() {
const items = this.store.getItems(); const items = this.store.getItems();
items.forEach((item) => { items.forEach((item) => {
this.deselectItem(item); this.unhighlightItem(item);
}); });
return this; return this;
@ -291,11 +287,11 @@ export class Choices {
* @return {Object} Class instance * @return {Object} Class instance
* @public * @public
*/ */
removeSelectedItems() { removeHighlightedItems() {
const items = this.store.getItemsFilteredByActive(); const items = this.store.getItemsFilteredByActive();
items.forEach((item) => { items.forEach((item) => {
if(item.selected && item.active) { if(item.highlighted && item.active) {
this._removeItem(item); this._removeItem(item);
} }
}); });
@ -424,8 +420,7 @@ export class Choices {
ajax(fn) { ajax(fn) {
if(this.initialised === true) { if(this.initialised === true) {
if(this.passedElement.type === 'select-one' || this.passedElement.type === 'select-multiple') { if(this.passedElement.type === 'select-one' || this.passedElement.type === 'select-multiple') {
this.containerOuter.classList.add('is-loading'); this.containerOuter.classList.add(this.config.classNames.loadingState);
// this.input.placeholder = this.config.loadingText;
const placeholderItem = this._getTemplate('item', { id: -1, value: 'Loading', label: this.config.loadingText, active: true}); const placeholderItem = this._getTemplate('item', { id: -1, value: 'Loading', label: this.config.loadingText, active: true});
this.itemList.appendChild(placeholderItem); this.itemList.appendChild(placeholderItem);
@ -434,7 +429,7 @@ export class Choices {
if(!isType('Array', results) || !value) return; if(!isType('Array', results) || !value) return;
if(results && results.length) { if(results && results.length) {
this.containerOuter.classList.remove('is-loading'); this.containerOuter.classList.remove(this.config.classNames.loadingState);
this.input.placeholder = ""; this.input.placeholder = "";
results.forEach((result, index) => { results.forEach((result, index) => {
// Select first choice in list if single select input // Select first choice in list if single select input
@ -485,7 +480,7 @@ export class Choices {
} else if(this.config.duplicateItems === false && this.passedElement.value) { } else if(this.config.duplicateItems === false && this.passedElement.value) {
// If no duplicates are allowed, and the value already exists // If no duplicates are allowed, and the value already exists
// in the array, don't update // in the array, don't update
canUpdate = !activeItems.some((item) => item.value === value ); canUpdate = !activeItems.some((item) => item.value === value);
} }
} else { } else {
canUpdate = false; canUpdate = false;
@ -519,16 +514,16 @@ export class Choices {
_handleBackspace(activeItems) { _handleBackspace(activeItems) {
if(this.config.removeItems && activeItems) { if(this.config.removeItems && activeItems) {
const lastItem = activeItems[activeItems.length - 1]; const lastItem = activeItems[activeItems.length - 1];
const hasSelectedItems = activeItems.some((item) => item.selected === true); const hasHighlightedItems = activeItems.some((item) => item.highlighted === true);
// If editing the last item is allowed and there are not other selected items, // If editing the last item is allowed and there are not other selected items,
// we can edit the item value. Otherwise if we can remove items, remove all selected items // we can edit the item value. Otherwise if we can remove items, remove all selected items
if(this.config.editItems && !hasSelectedItems && lastItem) { if(this.config.editItems && !hasHighlightedItems && lastItem) {
this.input.value = lastItem.value; this.input.value = lastItem.value;
this._removeItem(lastItem); this._removeItem(lastItem);
} else { } else {
if(!hasSelectedItems) { this.selectItem(lastItem); } if(!hasHighlightedItems) { this.highlightItem(lastItem); }
this.removeSelectedItems(); this.removeHighlightedItems();
} }
} }
}; };
@ -601,6 +596,7 @@ export class Choices {
} }
} }
} }
break; break;
case escapeKey: case escapeKey:
@ -695,12 +691,13 @@ export class Choices {
// If we have enabled text search // If we have enabled text search
if(this.canSearch) { if(this.canSearch) {
// .. and our input is in focus
if(this.input === document.activeElement) { if(this.input === document.activeElement) {
const options = this.store.getChoices(); const choices = this.store.getChoices();
const hasUnactiveChoices = options.some((option) => option.active !== true); const hasUnactiveChoices = choices.some((option) => option.active !== true);
// Check that we have a value to search and the input was an alphanumeric character // Check that we have a value to search and the input was an alphanumeric character
if(this.input.value && options.length && /[a-zA-Z0-9-_ ]/.test(keyString)) { if(this.input.value && choices.length && /[a-zA-Z0-9-_ ]/.test(keyString)) {
const handleFilter = () => { const handleFilter = () => {
const newValue = this.input.value.trim(); const newValue = this.input.value.trim();
const currentValue = this.currentValue.trim(); const currentValue = this.currentValue.trim();
@ -724,7 +721,7 @@ export class Choices {
handleFilter(); handleFilter();
} else if(hasUnactiveChoices) { } else if(hasUnactiveChoices) {
// Otherwise reset options to active // Otherwise reset choices to active
this.isSearching = false; this.isSearching = false;
this.store.dispatch(activateChoices(true)); this.store.dispatch(activateChoices(true));
} }
@ -789,21 +786,21 @@ export class Choices {
// so we deselect any items that aren't the target // so we deselect any items that aren't the target
// unless shift is being pressed // unless shift is being pressed
activeItems.forEach((item) => { activeItems.forEach((item) => {
if(item.id === parseInt(passedId) && !item.selected) { if(item.id === parseInt(passedId) && !item.highlighted) {
this.selectItem(item); this.highlightItem(item);
} else if(!hasShiftKey) { } else if(!hasShiftKey) {
this.deselectItem(item); this.unhighlightItem(item);
} }
}); });
} }
} else if(e.target.hasAttribute('data-option')) { } else if(e.target.hasAttribute('data-option')) {
// If we are clicking on an option // If we are clicking on an option
const options = this.store.getChoicesFilteredByActive();
const id = e.target.getAttribute('data-id'); const id = e.target.getAttribute('data-id');
const option = options.find((option) => option.id === parseInt(id)); const choices = this.store.getChoicesFilteredByActive();
const choice = choices.find((choice) => choice.id === parseInt(id));
if(!option.selected && !option.disabled) { if(!choice.selected && !choice.disabled) {
this._addItem(option.value, option.label, option.id); this._addItem(choice.value, choice.label, choice.id);
if(this.passedElement.type === 'select-one') { if(this.passedElement.type === 'select-one') {
this.input.value = ""; this.input.value = "";
this.isSearching = false; this.isSearching = false;
@ -816,10 +813,10 @@ export class Choices {
} else { } else {
// Click is outside of our element so close dropdown and de-select items // Click is outside of our element so close dropdown and de-select items
const hasActiveDropdown = this.dropdown.classList.contains(this.config.classNames.activeState); const hasActiveDropdown = this.dropdown.classList.contains(this.config.classNames.activeState);
const hasSelectedItems = activeItems.some((item) => item.selected === true); const hasHighlightedItems = activeItems.some((item) => item.highlighted === true);
// De-select any highlighted items // De-select any highlighted items
if(hasSelectedItems) { if(hasHighlightedItems) {
this.unhighlightAll(); this.unhighlightAll();
} }
@ -913,20 +910,20 @@ export class Choices {
* @return * @return
* @private * @private
*/ */
_scrollToChoice(option, direction) { _scrollToChoice(choice, direction) {
if(!option) return; if(!choice) return;
const dropdownHeight = this.choiceList.offsetHeight; const dropdownHeight = this.choiceList.offsetHeight;
const optionHeight = option.offsetHeight; const choiceHeight = choice.offsetHeight;
// Distance from bottom of element to top of parent // Distance from bottom of element to top of parent
const choicePos = option.offsetTop + optionHeight; const choicePos = choice.offsetTop + choiceHeight;
// Scroll position of dropdown // Scroll position of dropdown
const containerScrollPos = this.choiceList.scrollTop + dropdownHeight; const containerScrollPos = this.choiceList.scrollTop + dropdownHeight;
// Difference between the option and scroll position // Difference between the choice and scroll position
let endPoint = direction > 0 ? ((this.choiceList.scrollTop + choicePos) - containerScrollPos) : option.offsetTop; let endPoint = direction > 0 ? ((this.choiceList.scrollTop + choicePos) - containerScrollPos) : choice.offsetTop;
const animateScroll = (time, endPoint, direction) => { const animateScroll = (time, endPoint, direction) => {
let continueAnimation = false; let continueAnimation = false;
@ -964,40 +961,40 @@ export class Choices {
} }
/** /**
* Highlight option element * Highlight choice
* @param {HTMLElement} el Element to highlight * @param {HTMLElement} el Element to highlight
* @return * @return
* @private * @private
*/ */
_highlightChoice(el) { _highlightChoice(el) {
// Highlight first element in dropdown // Highlight first element in dropdown
const options = Array.from(this.dropdown.querySelectorAll('[data-option-selectable]')); const choices = Array.from(this.dropdown.querySelectorAll('[data-option-selectable]'));
if(options && options.length) { if(choices && choices.length) {
const highlightedOptions = Array.from(this.dropdown.querySelectorAll(`.${this.config.classNames.highlightedState}`)); const highlightedChoices = Array.from(this.dropdown.querySelectorAll(`.${this.config.classNames.highlightedState}`));
// Remove any highlighted options // Remove any highlighted choices
highlightedOptions.forEach((el) => { highlightedChoices.forEach((el) => {
el.classList.remove(this.config.classNames.highlightedState); el.classList.remove(this.config.classNames.highlightedState);
}); });
if(el){ if(el){
// Highlight given option // Highlight given option
el.classList.add(this.config.classNames.highlightedState); el.classList.add(this.config.classNames.highlightedState);
this.highlightPosition = options.indexOf(el); this.highlightPosition = choices.indexOf(el);
} else { } else {
// Highlight option based on last known highlight location // Highlight option based on last known highlight location
let el; let el;
if(options.length > this.highlightPosition) { if(choices.length > this.highlightPosition) {
// If we have an option to highlight // If we have an option to highlight
el = options[this.highlightPosition]; el = choices[this.highlightPosition];
} else { } else {
// Otherwise highlight the option before // Otherwise highlight the option before
el = options[options.length - 1]; el = choices[choices.length - 1];
} }
if(!el) el = options[0]; if(!el) el = choices[0];
el.classList.add(this.config.classNames.highlightedState); el.classList.add(this.config.classNames.highlightedState);
} }
} }
@ -1103,12 +1100,12 @@ export class Choices {
* @private * @private
*/ */
_addGroup(group, id, isFirst) { _addGroup(group, id, isFirst) {
const groupOptions = Array.from(group.getElementsByTagName('OPTION')); const groupChoices = Array.from(group.getElementsByTagName('OPTION'));
const groupId = id; const groupId = id;
if(groupOptions) { if(groupChoices) {
this.store.dispatch(addGroup(group.label, groupId, true, group.disabled)); this.store.dispatch(addGroup(group.label, groupId, true, group.disabled));
groupOptions.forEach((option, optionIndex) => { groupChoices.forEach((option, optionIndex) => {
const isDisabled = option.disabled || option.parentNode.disabled; const isDisabled = option.disabled || option.parentNode.disabled;
this._addChoice(option.selected, isDisabled, option.value, option.innerHTML, groupId); this._addChoice(option.selected, isDisabled, option.value, option.innerHTML, groupId);
}); });
@ -1147,9 +1144,39 @@ export class Choices {
itemList: () => { itemList: () => {
return strToEl(`<div class="${ classNames.list } ${ this.passedElement.type === 'select-one' ? classNames.listSingle : classNames.listItems }"></div>`); return strToEl(`<div class="${ classNames.list } ${ this.passedElement.type === 'select-one' ? classNames.listSingle : classNames.listItems }"></div>`);
}, },
item: (data) => {
if(this.config.removeItemButton && this.passedElement.type !== 'select-one') {
return strToEl(`
<div class="${ classNames.item } ${ data.highlighted ? classNames.highlightedState : ''} ${ !data.disabled ? classNames.itemSelectable : '' }" data-item data-id="${ data.id }" data-value="${ data.value }" data-deletable>
${ data.label }
<button class="${ classNames.button }" data-button>Remove item</button>
</div>
`);
} else {
return strToEl(`
<div class="${ classNames.item } ${ data.highlighted ? classNames.highlightedState : classNames.itemSelectable }" data-item data-id="${ data.id }" data-value="${ data.value }">
${ data.label }
</div>
`);
}
},
choiceList: () => { choiceList: () => {
return strToEl(`<div class="${ classNames.list }"></div>`); return strToEl(`<div class="${ classNames.list }"></div>`);
}, },
choiceGroup: (data) => {
return strToEl(`
<div class="${ classNames.group } ${ data.disabled ? classNames.itemDisabled : '' }" data-group data-id="${ data.id }" data-value="${ data.value }">
<div class="${ classNames.groupHeading }">${ data.value }</div>
</div>
`);
},
choice: (data) => {
return strToEl(`
<div class="${ classNames.item } ${ classNames.itemChoice } ${ data.disabled ? classNames.itemDisabled : classNames.itemSelectable }" data-option ${ data.disabled ? 'data-option-disabled' : 'data-option-selectable' } data-id="${ data.id }" data-value="${ data.value }">
${ data.label }
</div>
`);
},
input: () => { input: () => {
return strToEl(`<input type="text" class="${ classNames.input } ${ classNames.inputCloned }">`); return strToEl(`<input type="text" class="${ classNames.input } ${ classNames.inputCloned }">`);
}, },
@ -1159,38 +1186,8 @@ export class Choices {
notice: (label, clickable) => { notice: (label, clickable) => {
return strToEl(`<div class="${ classNames.item } ${ classNames.itemChoice }">${ label }</div>`); return strToEl(`<div class="${ classNames.item } ${ classNames.itemChoice }">${ label }</div>`);
}, },
selectOption: (data) => {
return strToEl(`<option value="${ data.value }" selected>${ data.label.trim() }</option>`);
},
option: (data) => { option: (data) => {
return strToEl(` return strToEl(`<option value="${ data.value }" selected>${ data.label.trim() }</option>`);
<div class="${ classNames.item } ${ classNames.itemChoice } ${ data.disabled ? classNames.itemDisabled : classNames.itemSelectable }" data-option ${ data.disabled ? 'data-option-disabled' : 'data-option-selectable' } data-id="${ data.id }" data-value="${ data.value }">
${ data.label }
</div>
`);
},
optgroup: (data) => {
return strToEl(`
<div class="${ classNames.group } ${ data.disabled ? classNames.itemDisabled : '' }" data-group data-id="${ data.id }" data-value="${ data.value }">
<div class="${ classNames.groupHeading }">${ data.value }</div>
</div>
`);
},
item: (data) => {
if(this.config.removeItemButton && this.passedElement.type !== 'select-one') {
return strToEl(`
<div class="${ classNames.item } ${ data.selected ? classNames.selectedState : ''} ${ !data.disabled ? classNames.itemSelectable : '' }" data-item data-id="${ data.id }" data-value="${ data.value }" data-deletable>
${ data.label }
<button class="${ classNames.button }" data-button>Remove item</button>
</div>
`);
} else {
return strToEl(`
<div class="${ classNames.item } ${ data.selected ? classNames.selectedState : classNames.itemSelectable }" data-item data-id="${ data.id }" data-value="${ data.value }">
${ data.label }
</div>
`);
}
}, },
}; };
@ -1222,7 +1219,7 @@ export class Choices {
this.passedElement.tabIndex = '-1'; this.passedElement.tabIndex = '-1';
this.passedElement.setAttribute('style', 'display:none;'); this.passedElement.setAttribute('style', 'display:none;');
this.passedElement.setAttribute('aria-hidden', 'true'); this.passedElement.setAttribute('aria-hidden', 'true');
this.passedElement.setAttribute('data-choice', ''); this.passedElement.setAttribute('data-choice', 'active');
// Wrap input in container preserving DOM ordering // Wrap input in container preserving DOM ordering
wrap(this.passedElement, containerInner); wrap(this.passedElement, containerInner);
@ -1286,32 +1283,32 @@ export class Choices {
} }
/** /**
* Render group options into a DOM fragment and append to options list * Render group choices into a DOM fragment and append to choice list
* @param {Array} groups Groups to add to list * @param {Array} groups Groups to add to list
* @param {Array} options Options to add to groups * @param {Array} choices Choices to add to groups
* @param {DocumentFragment} fragment Fragment to add groups and options to (optional) * @param {DocumentFragment} fragment Fragment to add groups and options to (optional)
* @return {DocumentFragment} Populated options fragment * @return {DocumentFragment} Populated options fragment
* @private * @private
*/ */
renderGroups(groups, options, fragment) { renderGroups(groups, choices, fragment) {
const groupFragment = fragment || document.createDocumentFragment(); const groupFragment = fragment || document.createDocumentFragment();
groups.forEach((group, i) => { groups.forEach((group, i) => {
// Grab options that are children of this group // Grab options that are children of this group
const groupOptions = options.filter((option) => { const groupChoices = choices.filter((choice) => {
if(this.passedElement.type === 'select-one') { if(this.passedElement.type === 'select-one') {
return option.groupId === group.id return choice.groupId === group.id
} else { } else {
return option.groupId === group.id && !option.selected; return choice.groupId === group.id && !choice.selected;
} }
}); });
if(groupOptions.length >= 1) { if(groupChoices.length >= 1) {
const dropdownGroup = this._getTemplate('optgroup', group); const dropdownGroup = this._getTemplate('choiceGroup', group);
groupFragment.appendChild(dropdownGroup); groupFragment.appendChild(dropdownGroup);
this.renderChoices(groupOptions, groupFragment); this.renderChoices(groupChoices, groupFragment);
} }
}); });
@ -1319,10 +1316,10 @@ export class Choices {
} }
/** /**
* Render options into a DOM fragment and append to options list * Render choices into a DOM fragment and append to choice list
* @param {Array} choices Options to add to list * @param {Array} choices Choices to add to list
* @param {DocumentFragment} fragment Fragment to add options to (optional) * @param {DocumentFragment} fragment Fragment to add choices to (optional)
* @return {DocumentFragment} Populated options fragment * @return {DocumentFragment} Populated choices fragment
* @private * @private
*/ */
renderChoices(choices, fragment) { renderChoices(choices, fragment) {
@ -1330,7 +1327,7 @@ export class Choices {
const choicesFragment = fragment || document.createDocumentFragment(); const choicesFragment = fragment || document.createDocumentFragment();
choices.forEach((choice, i) => { choices.forEach((choice, i) => {
const dropdownItem = this._getTemplate('option', choice); const dropdownItem = this._getTemplate('choice', choice);
if(this.passedElement.type === 'select-one') { if(this.passedElement.type === 'select-one') {
choicesFragment.appendChild(dropdownItem); choicesFragment.appendChild(dropdownItem);
@ -1364,13 +1361,13 @@ export class Choices {
// Add each list item to list // Add each list item to list
items.forEach((item) => { items.forEach((item) => {
// Create a standard select option // Create a standard select option
const option = this._getTemplate('selectOption', item); const option = this._getTemplate('option', item);
// Append it to fragment // Append it to fragment
selectedOptionsFragment.appendChild(option); selectedOptionsFragment.appendChild(option);
}); });
// Update selected options // Update selected choices
this.passedElement.innerHTML = ""; this.passedElement.innerHTML = "";
this.passedElement.appendChild(selectedOptionsFragment); this.passedElement.appendChild(selectedOptionsFragment);
} }
@ -1395,19 +1392,18 @@ export class Choices {
render() { render() {
this.currentState = this.store.getState(); this.currentState = this.store.getState();
// Only render if our state has actually changed // Only render if our state has actually changed
if(this.currentState !== this.prevState) { if(this.currentState !== this.prevState) {
// Options // Options
if((this.currentState.choices !== this.prevState.choices || this.currentState.groups !== this.prevState.groups)) { if((this.currentState.choices !== this.prevState.choices || this.currentState.groups !== this.prevState.groups)) {
if(this.passedElement.type === 'select-multiple' || this.passedElement.type === 'select-one') { if(this.passedElement.type === 'select-multiple' || this.passedElement.type === 'select-one') {
// Get active groups/options // Get active groups/choices
const activeGroups = this.store.getGroupsFilteredByActive(); const activeGroups = this.store.getGroupsFilteredByActive();
const activeChoices = this.store.getChoicesFilteredByActive(); const activeChoices = this.store.getChoicesFilteredByActive();
let choiceListFragment = document.createDocumentFragment(); let choiceListFragment = document.createDocumentFragment();
// Clear options // Clear choices
this.choiceList.innerHTML = ''; this.choiceList.innerHTML = '';
// If we have grouped options // If we have grouped options
@ -1419,7 +1415,7 @@ export class Choices {
if(choiceListFragment.children.length) { if(choiceListFragment.children.length) {
// If we actually have anything to add to our dropdown // If we actually have anything to add to our dropdown
// append it and highlight the first option // append it and highlight the first choice
this.choiceList.appendChild(choiceListFragment); this.choiceList.appendChild(choiceListFragment);
this._highlightChoice(); this._highlightChoice();
} else { } else {

View file

@ -24,6 +24,30 @@ export const isType = function(type, obj) {
return obj !== undefined && obj !== null && clas === type; return obj !== undefined && obj !== null && clas === type;
}; };
/**
* Tests to see if a passed object is a node
* @param {Object} obj Object to be tested
* @return {Boolean}
*/
export const isNode = (o) => {
return (
typeof Node === "object" ? o instanceof Node :
o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
);
};
/**
* Tests to see if a passed object is an element
* @param {Object} obj Object to be tested
* @return {Boolean}
*/
export const isElement = (o) => {
return (
typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName==="string"
);
}
/** /**
* Merges unspecified amount of objects into new object * Merges unspecified amount of objects into new object
* @private * @private

View file

@ -8,9 +8,9 @@ const choices = (state = [], action) => {
groupId: action.groupId, groupId: action.groupId,
value: action.value, value: action.value,
label: action.label, label: action.label,
disabled: action.disabled, disabled: action.disabled, // A disabled choice appears in the choice dropdown but cannot be selected
selected: false, selected: false, // A selected choice has been added to the passed input's value (added as an item)
active: true, active: true, // An active choice appears within the choice dropdown
score: 9999, score: 9999,
}].sort(sortByAlpha); }].sort(sortByAlpha);

View file

@ -8,12 +8,12 @@ const items = (state = [], action) => {
value: action.value, value: action.value,
label: action.label, label: action.label,
active: true, active: true,
selected: false highlighted: false
}]; }];
return newState.map((item) => { return newState.map((item) => {
if(item.selected) { if(item.highlighted) {
item.selected = false; item.highlighted = false;
} }
return item; return item;
}); });
@ -27,10 +27,10 @@ const items = (state = [], action) => {
return item; return item;
}); });
case 'SELECT_ITEM': case 'HIGHLIGHT_ITEM':
return state.map((item) => { return state.map((item) => {
if(item.id === action.id) { if(item.id === action.id) {
item.selected = action.selected; item.highlighted = action.highlighted;
} }
return item; return item;

View file

@ -133,7 +133,7 @@ h1, h2, h3, h4, h5, h6 {
word-break: break-all; } word-break: break-all; }
.choices__list--multiple .choices__item[data-deletable] { .choices__list--multiple .choices__item[data-deletable] {
padding-right: .5rem; } padding-right: .5rem; }
.choices__list--multiple .choices__item.is-selected { .choices__list--multiple .choices__item.is-highlighted {
background-color: #00a5bb; background-color: #00a5bb;
border: 1px solid #007888; } border: 1px solid #007888; }
.is-disabled .choices__list--multiple .choices__item { .is-disabled .choices__list--multiple .choices__item {
@ -162,10 +162,6 @@ h1, h2, h3, h4, h5, h6 {
.choices__list--dropdown .choices__item { .choices__list--dropdown .choices__item {
padding: 1rem; padding: 1rem;
font-size: 1.4rem; } font-size: 1.4rem; }
.choices__list--dropdown .choices__item.is-selected {
opacity: .5; }
.choices__list--dropdown .choices__item.is-selected:hover {
background-color: #FFFFFF; }
.choices__list--dropdown .choices__item--selectable:after { .choices__list--dropdown .choices__item--selectable:after {
content: "Press to select"; content: "Press to select";
font-size: 12px; font-size: 12px;

View file

@ -1 +1 @@
*,:after,:before{box-sizing:border-box}body,html{margin:0;height:100%;widows:100%}html{font-size:62.5%}body{background-color:#333;font-family:"Helvetica Neue",Helvetica,Arial,"Lucida Grande",sans-serif;font-size:1.6rem;color:#fff}hr,label{display:block}label{margin-bottom:.8rem;font-size:1.4rem;font-weight:500}hr{margin:3.6rem 0;border:0;border-bottom:1px solid #eaeaea;height:1px}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:1.2rem;font-weight:400}.container{display:block;margin:auto;max-width:35em;padding:2.4rem}.section{background-color:#fff;padding:2.4rem;color:#333}.choices{margin-bottom:2.4rem;position:relative}.choices.is-disabled .choices__inner,.choices.is-disabled .choices__input{background-color:#eaeaea;cursor:not-allowed;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.choices.is-disabled .choices__item{cursor:not-allowed}.choices[data-type*=select-one] .choices__inner{cursor:pointer;padding-bottom:.75rem}.choices[data-type*=select-one] .choices__input{display:block;width:100%;padding:1rem;border-bottom:1px solid #ddd;background-color:#fff;margin:0}.choices[data-type*=select-one].is-open:after{border-color:transparent transparent #333 transparent;margin-top:-7.5px}.choices[data-type*=select-one]:after{content:"";height:0;width:0;border-style:solid;border-color:#333 transparent transparent transparent;border-width:5px;position:absolute;right:1.15rem;top:50%;margin-top:-2.5px}.choices[data-type*=select-multiple] .choices__inner,.choices[data-type*=text] .choices__inner{cursor:text}.choices__inner{background-color:#f9f9f9;padding:.75rem .75rem .375rem;border:1px solid #ddd;border-radius:.25rem;font-size:1.4rem;overflow:hidden}.is-focused .choices__inner,.is-open .choices__inner{border-color:#b7b7b7}.is-open .choices__inner{border-radius:.25rem .25rem 0 0}.is-flipped.is-open .choices__inner{border-radius:0 0 .25rem .25rem}.choices__list{margin:0;padding-left:0;list-style-type:none}.choices__list--single{display:inline-block;padding:.4rem}.choices__list--multiple{display:inline}.choices__list--multiple .choices__item{display:inline-block;border-radius:2rem;padding:.4rem 1rem;font-size:1.2rem;margin-right:.375rem;margin-bottom:.375rem;background-color:#00bcd4;border:1px solid #008fa1;color:#fff;word-break:break-all}.choices__list--multiple .choices__item[data-deletable]{padding-right:.5rem}.choices__list--multiple .choices__item.is-selected{background-color:#00a5bb;border:1px solid #007888}.is-disabled .choices__list--multiple .choices__item{background-color:#aaa;border:1px solid #919191}.choices__list--dropdown{display:none;z-index:1;position:absolute;width:100%;background-color:#fff;border:1px solid #ddd;top:100%;margin-top:-1px;border-bottom-left-radius:.25rem;border-bottom-right-radius:.25rem;overflow:hidden}.choices__list--dropdown.is-active{display:block}.choices__list--dropdown .choices__list{position:relative;max-height:300px;overflow:auto;will-change:scroll-position}.choices__list--dropdown .choices__item{padding:1rem;font-size:1.4rem}.choices__list--dropdown .choices__item--selectable.is-highlighted:after,.choices__list--dropdown .choices__item.is-selected{opacity:.5}.choices__list--dropdown .choices__item.is-selected:hover{background-color:#fff}.choices__list--dropdown .choices__item--selectable:after{content:"Press to select";font-size:12px;opacity:0;float:right}.choices__list--dropdown .choices__item--selectable.is-highlighted{background-color:#f2f2f2}.is-open .choices__list--dropdown{border-color:#b7b7b7}.is-flipped .choices__list--dropdown{top:auto;bottom:100%;margin-top:0;margin-bottom:-1px;border-radius:.25rem .25rem 0 0}.choices__item{cursor:default}.choices__item--selectable{cursor:pointer}.choices__item--disabled{cursor:not-allowed;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;opacity:.5}.choices__group .choices__heading{font-weight:600;font-size:1.2rem;padding:1rem;border-bottom:1px solid #f7f7f7;color:gray}.choices__button{text-indent:-9999px;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:0;background-color:transparent;background-image:url(../../icons/cross.svg);background-repeat:no-repeat;background-position:center;background-size:8px;border-left:1px solid #008fa1;margin-left:4px;padding-left:6px;padding-right:6px;line-height:1;cursor:pointer}.choices__input{background-color:#f9f9f9;font-size:1.4rem;padding:0;margin-bottom:.5rem;display:inline-block;vertical-align:baseline;border:0;border-radius:0;max-width:100%;padding:.4rem 0 .4rem .2rem}.choices__input:focus{outline:0} *,:after,:before{box-sizing:border-box}body,html{margin:0;height:100%;widows:100%}html{font-size:62.5%}body{background-color:#333;font-family:"Helvetica Neue",Helvetica,Arial,"Lucida Grande",sans-serif;font-size:1.6rem;color:#fff}hr,label{display:block}label{margin-bottom:.8rem;font-size:1.4rem;font-weight:500}hr{margin:3.6rem 0;border:0;border-bottom:1px solid #eaeaea;height:1px}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:1.2rem;font-weight:400}.container{display:block;margin:auto;max-width:35em;padding:2.4rem}.section{background-color:#fff;padding:2.4rem;color:#333}.choices{margin-bottom:2.4rem;position:relative}.choices.is-disabled .choices__inner,.choices.is-disabled .choices__input{background-color:#eaeaea;cursor:not-allowed;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.choices.is-disabled .choices__item{cursor:not-allowed}.choices[data-type*=select-one] .choices__inner{cursor:pointer;padding-bottom:.75rem}.choices[data-type*=select-one] .choices__input{display:block;width:100%;padding:1rem;border-bottom:1px solid #ddd;background-color:#fff;margin:0}.choices[data-type*=select-one].is-open:after{border-color:transparent transparent #333 transparent;margin-top:-7.5px}.choices[data-type*=select-one]:after{content:"";height:0;width:0;border-style:solid;border-color:#333 transparent transparent transparent;border-width:5px;position:absolute;right:1.15rem;top:50%;margin-top:-2.5px}.choices[data-type*=select-multiple] .choices__inner,.choices[data-type*=text] .choices__inner{cursor:text}.choices__inner{background-color:#f9f9f9;padding:.75rem .75rem .375rem;border:1px solid #ddd;border-radius:.25rem;font-size:1.4rem;overflow:hidden}.is-focused .choices__inner,.is-open .choices__inner{border-color:#b7b7b7}.is-open .choices__inner{border-radius:.25rem .25rem 0 0}.is-flipped.is-open .choices__inner{border-radius:0 0 .25rem .25rem}.choices__list{margin:0;padding-left:0;list-style-type:none}.choices__list--single{display:inline-block;padding:.4rem}.choices__list--multiple{display:inline}.choices__list--multiple .choices__item{display:inline-block;border-radius:2rem;padding:.4rem 1rem;font-size:1.2rem;margin-right:.375rem;margin-bottom:.375rem;background-color:#00bcd4;border:1px solid #008fa1;color:#fff;word-break:break-all}.choices__list--multiple .choices__item[data-deletable]{padding-right:.5rem}.choices__list--multiple .choices__item.is-highlighted{background-color:#00a5bb;border:1px solid #007888}.is-disabled .choices__list--multiple .choices__item{background-color:#aaa;border:1px solid #919191}.choices__list--dropdown{display:none;z-index:1;position:absolute;width:100%;background-color:#fff;border:1px solid #ddd;top:100%;margin-top:-1px;border-bottom-left-radius:.25rem;border-bottom-right-radius:.25rem;overflow:hidden}.choices__list--dropdown.is-active{display:block}.choices__list--dropdown .choices__list{position:relative;max-height:300px;overflow:auto;will-change:scroll-position}.choices__list--dropdown .choices__item{padding:1rem;font-size:1.4rem}.choices__list--dropdown .choices__item--selectable:after{content:"Press to select";font-size:12px;opacity:0;float:right}.choices__list--dropdown .choices__item--selectable.is-highlighted{background-color:#f2f2f2}.choices__list--dropdown .choices__item--selectable.is-highlighted:after{opacity:.5}.is-open .choices__list--dropdown{border-color:#b7b7b7}.is-flipped .choices__list--dropdown{top:auto;bottom:100%;margin-top:0;margin-bottom:-1px;border-radius:.25rem .25rem 0 0}.choices__item{cursor:default}.choices__item--selectable{cursor:pointer}.choices__item--disabled{cursor:not-allowed;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;opacity:.5}.choices__group .choices__heading{font-weight:600;font-size:1.2rem;padding:1rem;border-bottom:1px solid #f7f7f7;color:gray}.choices__button{text-indent:-9999px;-webkit-appearance:none;-moz-appearance:none;appearance:none;border:0;background-color:transparent;background-image:url(../../icons/cross.svg);background-repeat:no-repeat;background-position:center;background-size:8px;border-left:1px solid #008fa1;margin-left:4px;padding-left:6px;padding-right:6px;line-height:1;cursor:pointer}.choices__input{background-color:#f9f9f9;font-size:1.4rem;padding:0;margin-bottom:.5rem;display:inline-block;vertical-align:baseline;border:0;border-radius:0;max-width:100%;padding:.4rem 0 .4rem .2rem}.choices__input:focus{outline:0}

View file

@ -161,7 +161,7 @@ $choices-button-icon-path: '../../icons/cross.svg';
color: #FFFFFF; color: #FFFFFF;
word-break: break-all; word-break: break-all;
&[data-deletable] { padding-right: .5rem; } &[data-deletable] { padding-right: .5rem; }
&.is-selected { &.is-highlighted {
background-color: darken($choices-primary-color, 5%); background-color: darken($choices-primary-color, 5%);
border: 1px solid darken($choices-primary-color, 15%); border: 1px solid darken($choices-primary-color, 15%);
} }
@ -196,11 +196,8 @@ $choices-button-icon-path: '../../icons/cross.svg';
.choices__item { .choices__item {
padding: 1rem; padding: 1rem;
font-size: 1.4rem; font-size: 1.4rem;
&.is-selected {
opacity: .5;
&:hover { background-color: $choices-bg-color-dropdown; }
}
} }
.choices__item--selectable { .choices__item--selectable {
&:after { &:after {
content: "Press to select"; content: "Press to select";