Semi-working filtering of options based on input value + restore ability to remove item based on back key

This commit is contained in:
Josh Johnson 2016-04-22 19:45:50 +01:00
parent c10ac458ec
commit d07517fe96
10 changed files with 174 additions and 93 deletions

File diff suppressed because one or more lines are too long

View file

@ -42,10 +42,26 @@ export const selectOption = (id, selected) => {
}
};
export const addGroup = (value, id) => {
export const filterOptions = (results) => {
return {
type: 'FILTER_OPTIONS',
results,
}
};
export const activateOptions = (active = true) => {
return {
type: 'ACTIVATE_OPTIONS',
active,
}
};
export const addGroup = (value, id, active, disabled) => {
return {
type: 'ADD_GROUP',
value,
id,
active,
disabled,
}
};

View file

@ -2,9 +2,9 @@
import { createStore } from 'redux';
import rootReducer from './reducers/index.js';
import { addItem, removeItem, selectItem, addOption, selectOption, addGroup } from './actions/index';
import { hasClass, wrap, getSiblings, isType, strToEl, extend, getWidthOfInput } from './lib/utils.js';
import { addItem, removeItem, selectItem, addOption, selectOption, filterOptions, activateOptions, addGroup } from './actions/index';
import { hasClass, wrap, getSiblings, isType, strToEl, extend, getWidthOfInput, debounce } from './lib/utils.js';
import Sifter from 'sifter';
/**
* Choices
@ -111,6 +111,7 @@ export class Choices {
this.onFocus = this.onFocus.bind(this);
this.onBlur = this.onBlur.bind(this);
this.onKeyUp = this.onKeyUp.bind(this);
this.onKeyDown = this.onKeyDown.bind(this);
this.onClick = this.onClick.bind(this);
this.onPaste = this.onPaste.bind(this);
@ -204,6 +205,7 @@ export class Choices {
this.input.value = lastItem.value;
this.removeItem(lastItem);
} else {
this.selectItem(lastItem);
this.removeAllSelectedItems();
}
}
@ -253,10 +255,6 @@ export class Choices {
const value = this.input.value;
this.handleEnter(activeItems, value);
}
if(this.inputType === 'multipleSelect' && this.options.allowSearch) {
// Do search
}
}
if(inputIsFocussed) {
@ -268,6 +266,32 @@ export class Choices {
}
}
onKeyUp(e) {
if(e.target === this.input) {
if(this.inputType === 'multipleSelect' && this.options.allowSearch) {
if(this.input.value) {
// If we have a value, filter options based on it
const handleFilter = debounce(() => {
const options = this.getOptionsFiltedBySelectable();
const sifter = new Sifter(options);
const results = sifter.search(this.input.value, {
fields: ['label', 'value'],
sort: [{field: 'value', direction: 'asc'}],
limit: 10
});
this.store.dispatch(filterOptions(results));
}, 100)
handleFilter();
} else {
// Otherwise reset options to active
this.store.dispatch(activateOptions());
}
}
}
}
/**
* Handle click event
@ -277,7 +301,7 @@ export class Choices {
onClick(e) {
const shiftKey = e.shiftKey;
if(this.dropdown) {
if(this.inputType === 'multipleSelect') {
this.toggleDropdown();
}
@ -296,7 +320,7 @@ export class Choices {
} else if(e.target.hasAttribute('data-choice-option')) {
// If we are clicking on an option
const options = this.getOptions();
const options = this.getOptionsFilteredByActive();
const id = e.target.getAttribute('data-choice-id');
const option = options.find((option) => {
return option.id === parseInt(id);
@ -314,7 +338,7 @@ export class Choices {
this.deselectAll();
}
// If there is a dropdown and it is active
if(this.dropdown && this.dropdown.classList.contains(this.options.classNames.activeState)) {
if(this.inputType === 'multipleSelect' && this.dropdown.classList.contains(this.options.classNames.activeState)) {
this.toggleDropdown();
}
}
@ -421,6 +445,7 @@ export class Choices {
selectOption(id, value = true) {
if(!id) return;
this.input.value = '';
this.store.dispatch(selectOption(id, value));
}
@ -449,7 +474,7 @@ export class Choices {
const id = this.store.getState().items.length + 1;
// Close dropdown
if(this.dropdown && this.dropdown.classList.contains(this.options.classNames.activeState)) {
if(this.inputType === 'multipleSelect' && this.dropdown.classList.contains(this.options.classNames.activeState)) {
this.toggleDropdown();
}
@ -579,8 +604,8 @@ export class Choices {
}
}
addGroup(value, id) {
this.store.dispatch(addGroup(value, id));
addGroup(value, id, active, disabled) {
this.store.dispatch(addGroup(value, id, active, disabled));
}
/* Getters */
@ -632,10 +657,39 @@ export class Choices {
return state.options;
}
getOptionsFilteredByActive() {
const options = this.getOptions();
const valueArray = options.filter((option) => {
return option.active === true;
},[]);
return valueArray;
}
getOptionsFiltedBySelectable() {
const options = this.getOptions();
const valueArray = options.filter((option) => {
return option.disabled === false;
},[]);
return valueArray;
}
getGroups() {
const state = this.store.getState();
return state.groups;
}
getGroupsFilteredByActive() {
const groups = this.getGroups();
const valueArray = groups.filter((group) => {
return group.active === true;
},[]);
console.log(groups);
return valueArray;
}
/* Rendering */
@ -745,13 +799,16 @@ export class Choices {
passedGroups.forEach((group, index) => {
const groupOptions = Array.from(group.getElementsByTagName('OPTION'));
const groupId = index;
this.addGroup(group.label, groupId);
groupOptions.forEach((option) => {
this.addOption(option, groupId);
});
if(groupOptions) {
this.addGroup(group.label, groupId, true, group.disabled);
groupOptions.forEach((option) => {
this.addOption(option, groupId);
});
} else {
this.addGroup(group.label, groupId, false, group.disabled);
}
});
} else {
const passedOptions = Array.from(this.passedElement.options);
@ -766,6 +823,7 @@ export class Choices {
* Trigger event listeners
*/
addEventListeners() {
document.addEventListener('keyup', this.onKeyUp);
document.addEventListener('keydown', this.onKeyDown);
document.addEventListener('click', this.onClick);
document.addEventListener('paste', this.onPaste);
@ -778,6 +836,7 @@ export class Choices {
* Destroy event listeners
*/
removeEventListeners() {
document.removeEventListener('keyup', this.onKeyUp);
document.removeEventListener('keydown', this.onKeyDown);
document.removeEventListener('click', this.onClick);
document.removeEventListener('paste', this.onPaste);
@ -793,11 +852,11 @@ export class Choices {
render(callback = this.options.callbackOnRender) {
const classNames = this.options.classNames;
const activeItems = this.getItemsFilteredByActive();
const options = this.getOptions();
const groups = this.getGroups();
const activeOptions = this.getOptionsFilteredByActive();
const activeGroups = this.getGroupsFilteredByActive();
// OPTIONS
if(this.dropdown) {
if(this.inputType === 'multipleSelect') {
// Clear options
this.dropdown.innerHTML = '';
@ -805,21 +864,21 @@ export class Choices {
const optionListFragment = document.createDocumentFragment();
// If we have grouped options
if(groups.length) {
groups.forEach((group) => {
const dropdownGroup = strToEl(`
<div class="${ classNames.group } ${ group.disabled ? classNames.itemDisabled : '' }" data-choice-value="${ group.value }" data-choice-group-id="${ group.id }">
<div class="${ classNames.groupHeading }">${ group.value }</div>
</div>
`);
const childOptions = options.filter((option) => {
if(activeGroups.length >= 1) {
activeGroups.forEach((group) => {
const groupOptions = activeOptions.filter((option) => {
return option.groupId === group.id;
});
if(childOptions) {
childOptions.forEach((option) => {
// IF group actually has options within it
if(groupOptions.length >= 1) {
const dropdownGroup = strToEl(`
<div class="${ classNames.group } ${ group.disabled ? classNames.itemDisabled : '' }" data-choice-value="${ group.value }" data-choice-group-id="${ group.id }">
<div class="${ classNames.groupHeading }">${ group.value }</div>
</div>
`);
groupOptions.forEach((option) => {
const dropdownItem = strToEl(`
<div class="${ classNames.item } ${ classNames.itemOption } ${ option.selected ? classNames.selectedState + ' ' + classNames.itemDisabled : classNames.itemSelectable }" data-choice-option data-choice-id="${ option.id }" data-choice-value="${ option.value }">
${ option.label }
@ -828,28 +887,23 @@ export class Choices {
dropdownGroup.appendChild(dropdownItem);
});
} else {
const dropdownItem = strToEl(`<div class="${ classNames.item }">No options to select</div>`);
dropdownGroup.appendChild(dropdownItem);
}
optionListFragment.appendChild(dropdownGroup);
optionListFragment.appendChild(dropdownGroup);
}
});
} else if(activeOptions.length >= 1) {
activeOptions.forEach((option) => {
const dropdownItem = strToEl(`
<div class="${ classNames.item } ${ classNames.itemOption } ${ option.selected ? classNames.selectedState + ' ' + classNames.itemDisabled : classNames.itemSelectable }" data-choice-option data-choice-id="${ option.id }" data-choice-value="${ option.value }">
${ option.label }
</div>
`);
optionListFragment.appendChild(dropdownItem);
});
} else {
if(options) {
options.forEach((option) => {
const dropdownItem = strToEl(`
<div class="${ classNames.item } ${ classNames.itemOption } ${ option.selected ? classNames.selectedState + ' ' + classNames.itemDisabled : classNames.itemSelectable }" data-choice-option data-choice-id="${ option.id }" data-choice-value="${ option.value }">
${ option.label }
</div>
`);
optionListFragment.appendChild(dropdownItem);
});
} else {
const dropdownItem = strToEl(`<div class="${ classNames.item }">No options to select</div>`);
optionListFragment.appendChild(dropdownItem);
}
const dropdownItem = strToEl(`<div class="${ classNames.item }">No options to select</div>`);
optionListFragment.appendChild(dropdownItem);
}
@ -889,7 +943,7 @@ export class Choices {
// Run callback if it is a function
if(callback){
if(isType('Function', callback)) {
callback(activeItems, options, groups);
callback(activeItems, activeOptions, activeGroups);
} else {
console.error('callbackOnRender: Callback is not a function');
}
@ -1004,9 +1058,9 @@ document.addEventListener('DOMContentLoaded', () => {
const choices6 = new Choices('#choices-6', {
items: ['josh@joshuajohnson.co.uk', 'joe@bloggs.co.uk'],
callbackOnRender: function(items, options, groups) {
console.log(items);
},
// callbackOnRender: function(items, options, groups) {
// console.log(items);
// },
});
const choices7 = new Choices('#choices-7', {
@ -1022,7 +1076,7 @@ document.addEventListener('DOMContentLoaded', () => {
// },
});
choices6.addItem('josh2@joshuajohnson.co.uk', null, null, () => { console.log('Custom add item callback')});
choices6.removeItemsByValue('josh@joshuajohnson.co.uk');
console.log(choices6.getItemById(3));
// choices6.addItem('josh2@joshuajohnson.co.uk', null, null, () => { console.log('Custom add item callback')});
// choices6.removeItemsByValue('josh@joshuajohnson.co.uk');
// console.log(choices6.getItemById(3));
});

View file

@ -4,7 +4,8 @@ const groups = (state = [], action) => {
return [...state, {
id: action.id,
value: action.value,
disabled: false,
active: action.active,
disabled: action.disabled,
}];
default:

View file

@ -8,7 +8,8 @@ const options = (state = [], action) => {
label: action.label,
disabled: false,
selected: false,
}];;
active: true,
}];
case 'SELECT_OPTION':
return state.map((option) => {
@ -19,19 +20,26 @@ const options = (state = [], action) => {
return option;
});
case 'REMOVE_ITEM':
// When an item is removed and it has an associated option,
// we want to re-enable it so it can be chosen again
if(action.optionId > -1) {
return state.map((option) => {
if(option.id === parseInt(action.optionId)) {
option.selected = action.selected;
}
return option;
case 'FILTER_OPTIONS':
const filteredResults = action.results.items;
const newState = state.map((option, index) => {
// Set active state based on whether option is
// within filtered results
option.active = filteredResults.some((result) => {
return result.id === index;
});
} else {
return state;
}
return option;
});
return newState;
case 'ACTIVATE_OPTIONS':
return state.map((option) => {
option.active = action.active;
return option;
});
default:

View file

@ -49,7 +49,7 @@ h1, h2, h3, h4, h5, h6 {
font-size: 1.4rem;
cursor: text; }
.is-active .choices__inner {
border-color: #c4c4c4; }
border-color: #b7b7b7; }
.choices__inner:focus {
outline: 1px solid #00BCD4;
outline-offset: -1px; }
@ -89,7 +89,7 @@ h1, h2, h3, h4, h5, h6 {
max-height: 300px;
overflow: auto; }
.is-active .choices__list--dropdown {
border-color: #c4c4c4; }
border-color: #b7b7b7; }
.choices__list--dropdown .choices__item {
padding: 1rem;
font-size: 1.4rem; }

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}label{display:block;margin-bottom:.8rem;font-size:1.4rem;font-weight:500}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:1.2rem;font-weight:500}.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__inner{background-color:#f9f9f9;padding:.75rem .75rem .375rem;border:1px solid #ddd;border-radius:.25rem;font-size:1.4rem;cursor:text}.is-active .choices__inner{border-color:#c4c4c4}.choices__inner:focus{outline:1px solid #00bcd4;outline-offset:-1px}.choices__list{margin:0;padding-left:0;list-style-type:none}.choices__list--items{display:inline}.choices__list--items .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 #00b1c7;color:#fff;word-break:break-all}.choices__list--items .choices__item.is-selected{background-color:#00a5bb}.choices__list--dropdown{z-index:1;position:absolute;width:100%;background-color:#fff;border:1px solid #ddd;top:100%;margin-top:-1px;display:none;border-bottom-left-radius:.25rem;border-bottom-right-radius:.25rem;max-height:300px;overflow:auto}.is-active .choices__list--dropdown{border-color:#c4c4c4}.choices__list--dropdown .choices__item{padding:1rem;font-size:1.4rem}.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:hover{background-color:#f9f9f9}.choices__list--dropdown.is-active{display:block}.choices__list--dropdown.is-flipped{top:auto;bottom:100%;margin-top:0;margin-bottom:-1px;border-bottom-left-radius:0;border-bottom-right-radius:0;border-top-left-radius:.25rem;border-top-right-radius:.25rem}.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}.choices__group .choices__heading{font-size:1.2rem;padding:1rem;border-bottom:1px solid #eaeaea;color:gray}.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}label{display:block;margin-bottom:.8rem;font-size:1.4rem;font-weight:500}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:1.2rem;font-weight:500}.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__inner{background-color:#f9f9f9;padding:.75rem .75rem .375rem;border:1px solid #ddd;border-radius:.25rem;font-size:1.4rem;cursor:text}.is-active .choices__inner{border-color:#b7b7b7}.choices__inner:focus{outline:1px solid #00bcd4;outline-offset:-1px}.choices__list{margin:0;padding-left:0;list-style-type:none}.choices__list--items{display:inline}.choices__list--items .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 #00b1c7;color:#fff;word-break:break-all}.choices__list--items .choices__item.is-selected{background-color:#00a5bb}.choices__list--dropdown{z-index:1;position:absolute;width:100%;background-color:#fff;border:1px solid #ddd;top:100%;margin-top:-1px;display:none;border-bottom-left-radius:.25rem;border-bottom-right-radius:.25rem;max-height:300px;overflow:auto}.is-active .choices__list--dropdown{border-color:#b7b7b7}.choices__list--dropdown .choices__item{padding:1rem;font-size:1.4rem}.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:hover{background-color:#f9f9f9}.choices__list--dropdown.is-active{display:block}.choices__list--dropdown.is-flipped{top:auto;bottom:100%;margin-top:0;margin-bottom:-1px;border-bottom-left-radius:0;border-bottom-right-radius:0;border-top-left-radius:.25rem;border-top-right-radius:.25rem}.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}.choices__group .choices__heading{font-size:1.2rem;padding:1rem;border-bottom:1px solid #eaeaea;color:gray}.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

@ -59,7 +59,7 @@ h1, h2, h3, h4, h5, h6 {
border-radius: .25rem;
font-size: 1.4rem;
cursor: text;
.is-active & { border-color: darken(#DDDDDD, 10%); }
.is-active & { border-color: darken(#DDDDDD, 15%); }
&:focus {
outline: 1px solid #00BCD4;
outline-offset: -1px;
@ -104,7 +104,7 @@ h1, h2, h3, h4, h5, h6 {
border-bottom-right-radius: .25rem;
max-height: 300px;
overflow: auto;
.is-active & { border-color: darken(#DDDDDD, 10%); }
.is-active & { border-color: darken(#DDDDDD, 15%); }
.choices__item {
padding: 1rem;
font-size: 1.4rem;

View file

@ -52,20 +52,20 @@
<label for="choices-10">Select box with option groups</label>
<select id="choices-10" name="choices-10" data-choice placeholder="This is a placeholder" multiple>
<optgroup label="Group 1">
<option value="Value 1">Dropdown item 1</option>
<option value="Value 2">Dropdown item 2</option>
<option value="Value 3">Dropdown item 3</option>
<optgroup label="UK">
<option value="London">London</option>
<option value="Manchester">Manchester</option>
<option value="Liverpool">Liverpool</option>
</optgroup>
<optgroup label="Group 2">
<option value="Value 4">Dropdown item 4</option>
<option value="Value 5">Dropdown item 5</option>
<option value="Value 6">Dropdown item 6</option>
<optgroup label="FR">
<option value="Paris">Paris</option>
<option value="Lyon">Lyon</option>
<option value="Marseille">Marseille</option>
</optgroup>
<optgroup label="Group 3" disabled>
<option value="Value 7">Dropdown item 7</option>
<option value="Value 8">Dropdown item 8</option>
<option value="Value 9">Dropdown item 9</option>
<optgroup label="DL" disabled>
<option value="Hamburg">Hamburg</option>
<option value="Munich">Munich</option>
<option value="Berlin">Berlin</option>
</optgroup>
</select>
</div>

View file

@ -38,6 +38,7 @@
"nodemon": "^1.9.1",
"opn-cli": "^3.1.0",
"postcss-cli": "^2.5.1",
"sifter": "^0.4.5",
"webpack": "^1.12.14",
"webpack-dev-server": "^1.14.1"
},