Test next state to previous state to avoid needless rendering

This commit is contained in:
Josh Johnson 2016-05-04 14:31:29 +01:00
parent b34db1920a
commit 5cf4368ad4
6 changed files with 202 additions and 192 deletions

File diff suppressed because one or more lines are too long

View file

@ -77,14 +77,15 @@ export class Choices {
callbackOnAddItem: function() {}
};
// Initial instance state
this.initialised = false;
// Merge options with user options
this.options = extend(defaultOptions, userOptions);
// Create data store
this.store = new Store();
this.store = new Store(this.render);
// State tracking
this.currentState = {};
this.prevState = {};
// Retrieve triggering element (i.e. element with 'data-choice' trigger)
this.passedElement = isType('String', element) ? document.querySelector(element) : element;
@ -331,17 +332,21 @@ export class Choices {
});
// Check that have a value to search
if(this.input.value) {
if(this.input.value && options.length) {
const handleFilter = debounce(() => {
// Ensure value *still* has a value after 500 delay
if(this.input.value && this.input.value.length >= 1) {
const options = this.store.getOptionsFiltedBySelectable();
const fuse = new Fuse(options, {
const haystack = this.store.getOptionsFiltedBySelectable();
const needle = this.input.value;
const fuse = new Fuse(haystack, {
keys: ['label', 'value'],
shouldSort: true,
include: 'score',
});
const results = fuse.search(this.input.value);
const results = fuse.search(needle);
this.isSearching = true;
this.store.dispatch(filterOptions(results));
}
@ -593,6 +598,7 @@ export class Choices {
* @param {String} value Value to add to store
*/
addItem(value, label, optionId = -1, callback = this.options.callbackOnAddItem) {
const items = this.store.getItems();
let passedValue = value.trim();
let passedLabel = label || passedValue;
let passedOptionId = optionId || -1;
@ -608,7 +614,7 @@ export class Choices {
}
// Generate unique id
const id = this.store.getState().items.length + 1;
const id = items ? items.length + 1 : 1;
this.store.dispatch(addItem(passedValue, passedLabel, id, passedOptionId));
@ -640,11 +646,8 @@ export class Choices {
// Run callback
if(callback){
if(isType('Function', callback)) {
callback(value);
} else {
console.error('callbackOnRemoveItem: Callback is not a function');
}
if(!isType('Function', callback)) console.error('callbackOnRemoveItem: Callback is not a function'); return;
callback(value);
}
}
@ -654,9 +657,7 @@ export class Choices {
* @return
*/
removeItemsByValue(value) {
if(!value || !isType('String', value)) {
console.error('removeItemsByValue: No value was passed to be removed');
}
if(!value || !isType('String', value)) console.error('removeItemsByValue: No value was passed to be removed'); return;
const items = this.store.getItemsFilteredByActive();
@ -753,8 +754,8 @@ export class Choices {
*/
addOption(option, groupId = -1) {
// Generate unique id
const state = this.store.getState();
const id = state.options.length + 1;
const options = this.store.getOptions();
const id = options.length + 1;
const value = option.value;
const label = option.innerHTML;
const isDisabled = option.disabled || option.parentNode.disabled;
@ -788,6 +789,64 @@ export class Choices {
}
}
getTemplate(template, ...args) {
if(!template) return;
const templates = this.options.templates;
return templates[template](...args);
}
/**
* Create HTML element based on type and arguments
* @param {String} template Template to create
* @param {...} args Data
* @return {HTMLElement}
*/
createTemplates() {
const classNames = this.options.classNames;
const templates = {
containerOuter: () => {
return strToEl(`<div class="${ classNames.containerOuter }"></div>`);
},
containerInner: () => {
return strToEl(`<div class="${ classNames.containerInner }"></div>`);
},
list: () => {
return strToEl(`<ul class="${ classNames.list } ${ classNames.listItems }"></ul>`);
},
input: () => {
return strToEl(`<input type="text" class="${ classNames.input } ${ classNames.inputCloned }">`);
},
dropdown: () => {
return strToEl(`<div class="${ classNames.list } ${ classNames.listDropdown }"></div>`);
},
notice: (label) => {
return strToEl(`<div class="${ classNames.item } ${ classNames.itemOption }">${ label }</div>`);
},
option: (data) => {
return strToEl(`
<div class="${ classNames.item } ${ classNames.itemOption } ${ 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) => {
return strToEl(`
<div class="${ classNames.item } ${ classNames.itemOption } ${ data.selected ? classNames.selectedState : classNames.itemSelectable }" data-item data-id="${ data.id }" data-value="${ data.value }">
${ data.label }
</div>
`);
},
};
this.options.templates = extend(this.options.templates, templates);
}
/**
* Create DOM structure around passed select element
@ -860,156 +919,107 @@ export class Choices {
this.list = list;
}
renderGroups(groups, options, fragment) {
groups.forEach((group, i) => {
// Grab options that are children of this group
const groupOptions = options.filter((option) => {
return option.groupId === group.id;
});
if(groupOptions.length >= 1) {
const dropdownGroup = this.getTemplate('optgroup', group);
groupOptions.forEach((option, j) => {
const dropdownItem = this.getTemplate('option', option);
dropdownGroup.appendChild(dropdownItem);
});
fragment.appendChild(dropdownGroup);
}
});
}
renderOptions(options, fragment) {
options.forEach((option, i) => {
const dropdownItem = this.getTemplate('option', option);
fragment.appendChild(dropdownItem);
});
}
renderItems(items, fragment) {
// Simplify store data to just values
const itemsFiltered = this.store.getItemsReducedToValues();
// Assign hidden input array of values
this.passedElement.value = itemsFiltered.join(this.options.delimiter);
// Clear list
this.list.innerHTML = '';
// Add each list item to list
items.forEach((item) => {
// Create new list element
const listItem = this.getTemplate('item', item);
// Append it to list
fragment.appendChild(listItem);
});
this.list.appendChild(fragment);
}
/**
* Render DOM with values
* @return
*/
render(callback = this.options.callbackOnRender) {
const classNames = this.options.classNames;
const activeItems = this.store.getItemsFilteredByActive();
render() {
this.currentState = this.store.getState();
if(this.currentState !== this.prevState) {
// OPTIONS
if((this.currentState.options !== this.prevState.options || this.currentState.groups !== this.prevState.groups) && this.passedElement.type === 'select-multiple') {
// Get active groups/options
const activeGroups = this.store.getGroupsFilteredByActive();
const activeOptions = this.store.getOptionsFilteredByActive();
// OPTIONS
if(this.passedElement.type === 'select-multiple') {
const activeOptions = this.store.getOptionsFilteredByActive();
const activeGroups = this.store.getGroupsFilteredByActive();
// Create a fragment to store our list items (so we don't have to update the DOM for each item)
const optionListFragment = document.createDocumentFragment();
// Create a fragment to store our list items (so we don't have to update the DOM for each item)
const optionListFragment = document.createDocumentFragment();
// Clear options
this.dropdown.innerHTML = '';
// If we have grouped options
if(activeGroups.length >= 1 && this.isSearching !== true) {
activeGroups.forEach((group, i) => {
// Grab options that are children of this group
const groupOptions = activeOptions.filter((option) => {
return option.groupId === group.id;
});
// If we have grouped options
if(activeGroups.length >= 1 && this.isSearching !== true) {
this.renderGroups(activeGroups, activeOptions, optionListFragment);
} else if(activeOptions.length >= 1) {
this.renderOptions(activeOptions, optionListFragment);
}
if(groupOptions.length >= 1) {
const dropdownGroup = this.getTemplate('optgroup', group);
groupOptions.forEach((option, j) => {
const dropdownItem = this.getTemplate('option', option);
dropdownGroup.appendChild(dropdownItem);
});
optionListFragment.appendChild(dropdownGroup);
}
});
} else if(activeOptions.length >= 1) {
activeOptions.forEach((option, i) => {
const dropdownItem = this.getTemplate('option', option);
optionListFragment.appendChild(dropdownItem);
});
// If we actually have anything to add to our dropdown
if(optionListFragment.children.length) {
this.dropdown.appendChild(optionListFragment);
this.highlightOption();
} else {
// If dropdown is empty, show a no content notice
const dropdownItem = this.getTemplate('notice', 'No options to select');
this.dropdown.appendChild(dropdownItem);
}
}
// Clear options
this.dropdown.innerHTML = '';
if(optionListFragment.children.length) {
this.dropdown.appendChild(optionListFragment);
this.highlightOption();
} else {
// If dropdown is empty, show a no content notice
const dropdownItem = this.getTemplate('notice', 'No options to select');
this.dropdown.appendChild(dropdownItem);
}
}
// ITEMS
if(activeItems) {
// Simplify store data to just values
const itemsFiltered = this.store.getItemsReducedToValues();
// Assign hidden input array of values
this.passedElement.value = itemsFiltered.join(this.options.delimiter);
// Clear list
this.list.innerHTML = '';
// Create a fragment to store our list items (so we don't have to update the DOM for each item)
const itemListFragment = document.createDocumentFragment();
// Add each list item to list
activeItems.forEach((item) => {
// Create new list element
const listItem = this.getTemplate('item', item);
// Append it to list
itemListFragment.appendChild(listItem);
});
this.list.appendChild(itemListFragment);
}
// Run callback if it is a function
if(callback){
if(isType('Function', callback)) {
callback(activeItems);
} else {
console.error('callbackOnRender: Callback is not a function');
// ITEMS
if(this.currentState.items !== this.prevState.items) {
const activeItems = this.store.getItemsFilteredByActive();
if(activeItems) {
// Create a fragment to store our list items (so we don't have to update the DOM for each item)
const itemListFragment = document.createDocumentFragment();
this.renderItems(activeItems, itemListFragment);
}
}
this.prevState = this.currentState;
}
}
getTemplate(template, ...args) {
if(!template) return;
const templates = this.options.templates;
return templates[template](...args);
}
/**
* Create HTML element based on type and arguments
* @param {String} template Template to create
* @param {...} args Data
* @return {HTMLElement}
*/
createTemplates() {
const classNames = this.options.classNames;
const templates = {
containerOuter: () => {
return strToEl(`<div class="${ classNames.containerOuter }"></div>`);
},
containerInner: () => {
return strToEl(`<div class="${ classNames.containerInner }"></div>`);
},
list: () => {
return strToEl(`<ul class="${ classNames.list } ${ classNames.listItems }"></ul>`);
},
input: () => {
return strToEl(`<input type="text" class="${ classNames.input } ${ classNames.inputCloned }">`);
},
dropdown: () => {
return strToEl(`<div class="${ classNames.list } ${ classNames.listDropdown }"></div>`);
},
notice: (label) => {
return strToEl(`<div class="${ classNames.item } ${ classNames.itemOption }">${ label }</div>`);
},
option: (data) => {
return strToEl(`
<div class="${ classNames.item } ${ classNames.itemOption } ${ 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) => {
return strToEl(`
<div class="${ classNames.item } ${ classNames.itemOption } ${ data.selected ? classNames.selectedState : classNames.itemSelectable }" data-item data-id="${ data.id }" data-value="${ data.value }">
${ data.label }
</div>
`);
},
};
this.options.templates = extend(this.options.templates, templates);
}
/**
* Trigger event listeners
* @return
@ -1045,15 +1055,12 @@ export class Choices {
* @return
*/
init(callback = this.options.callbackOnInit) {
this.initialised = true;
// Create required elements
this.createTemplates();
// Generate input markup
this.generateInput();
// Subscribe to store
this.store.subscribe(this.render);
// Render any items

View file

@ -3,21 +3,39 @@
import { createStore } from 'redux';
import rootReducer from './reducers/index.js';
export class Store {
constructor() {
this.store = createStore(rootReducer);
this.store = createStore(
rootReducer,
window.devToolsExtension ? window.devToolsExtension() : undefined
);
}
/**
* Get store object (wrapping Redux method)
* @return {Object} State
*/
getState() {
return this.store.getState();
}
dispatch(callback) {
this.store.dispatch(callback);
/**
* Dispatch event to store (wrapped Redux method)
* @param {Function} action Action function to trigger
* @return
*/
dispatch(action) {
this.store.dispatch(action);
}
subscribe(callback) {
this.store.subscribe(callback);
/**
* Subscribe store to function call (wrapped Redux method)
* @param {Function} onChange Function to trigger when state changes
* @return
*/
subscribe(onChange) {
this.store.subscribe(onChange);
}
/**
@ -122,4 +140,4 @@ export class Store {
}
};
window.Store = module.exports = Store;
module.exports = Store;

View file

@ -97,24 +97,15 @@ h1, h2, h3, h4, h5, h6 {
opacity: .5; }
.choices__list--dropdown .choices__item.is-selected:hover {
background-color: #FFFFFF; }
.choices__list--dropdown .choices__item--selectable {
-webkit-transition: background-color .15s ease-in-out;
transition: background-color .15s ease-in-out; }
.choices__list--dropdown .choices__item--selectable:after {
content: "Press to select";
font-size: 12px;
opacity: 0;
float: right;
-webkit-transition: opacity .15s ease-in-out;
transition: opacity .15s ease-in-out; }
.choices__list--dropdown .choices__item--selectable.is-highlighted {
background-color: #f2f2f2;
-webkit-transition: background-color .15s ease-in-out;
transition: background-color .15s ease-in-out; }
.choices__list--dropdown .choices__item--selectable.is-highlighted:after {
opacity: .5;
-webkit-transition: opacity .15s ease-in-out;
transition: opacity .15s ease-in-out; }
.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; }
.choices__list--dropdown.is-active {
display: block; }
.choices__list--dropdown.is-flipped {

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:#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,.choices__list--dropdown .choices__item--selectable.is-highlighted{-webkit-transition:background-color .15s ease-in-out;transition:background-color .15s ease-in-out}.choices__list--dropdown .choices__item--selectable:after{content:"Press to select";font-size:12px;opacity:0;float:right;-webkit-transition:opacity .15s ease-in-out;transition:opacity .15s ease-in-out}.choices__list--dropdown .choices__item--selectable.is-highlighted{background-color:#f2f2f2}.choices__list--dropdown .choices__item--selectable.is-highlighted:after{opacity:.5;-webkit-transition:opacity .15s ease-in-out;transition:opacity .15s ease-in-out}.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;opacity:.5}.choices__group .choices__heading{font-weight:600;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--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}.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;opacity:.5}.choices__group .choices__heading{font-weight:600;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

@ -114,21 +114,15 @@ h1, h2, h3, h4, h5, h6 {
}
}
.choices__item--selectable {
transition: background-color .15s ease-in-out;
&:after {
content: "Press to select";
font-size: 12px;
opacity: 0;
float: right;
transition: opacity .15s ease-in-out;
}
&.is-highlighted {
background-color: mix(#000000, #FFFFFF, 5%);
transition: background-color .15s ease-in-out;
&:after {
opacity: .5;
transition: opacity .15s ease-in-out;
}
&:after { opacity: .5; }
}
}