From 7dc30abff730cd3847bcbacdb162b8c6be98da7c Mon Sep 17 00:00:00 2001 From: Josh Johnson Date: Mon, 11 Apr 2016 14:13:50 +0100 Subject: [PATCH] Configurable class names --- assets/scripts/dist/bundle.js | 2 +- assets/scripts/src/choices.js | 121 +++++++++++++++++++--------------- 2 files changed, 68 insertions(+), 55 deletions(-) diff --git a/assets/scripts/dist/bundle.js b/assets/scripts/dist/bundle.js index e129611..186c959 100644 --- a/assets/scripts/dist/bundle.js +++ b/assets/scripts/dist/bundle.js @@ -1 +1 @@ -!function(e){function t(i){if(n[i])return n[i].exports;var o=n[i]={exports:{},id:i,loaded:!1};return e[i].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="/assets/scripts/dist/",t(0)}([function(e,t,n){e.exports=n(1)},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0}),t.Choices=void 0;var r=function(){function e(e,t){for(var n=0;n1)for(var u=1;u=0;n--){var i=this.list.children[n];if(i.innerHTML===e.toString()){t=i;break}}if(t){var o=t.getAttribute("data-choice-id"),r=t.innerHTML;this.options.callbackOnRemoveItem&&((0,l.isType)("Function",this.options.callbackOnRemoveItem)?this.options.callbackOnRemoveItem(r):console.error("callbackOnRemoveItem: Callback is not a function")),this.store.dispatch((0,u.removeItemFromStore)(o))}else console.error("Item not found")}},{key:"removeAll",value:function(e){for(var t=0;t'+e+"");this.dropdown.appendChild(t)}},{key:"renderTextInput",value:function(){var e=this,t=(0,l.strToEl)('
'),n=(0,l.strToEl)('
');this.passedElement.classList.add("choices__input","choices__input--hidden"),this.passedElement.tabIndex="-1",this.passedElement.setAttribute("style","display:none;"),this.passedElement.setAttribute("aria-hidden","true"),(0,l.wrap)(this.passedElement,n),(0,l.wrap)(n,t);var i=(0,l.strToEl)('
'),o=(0,l.strToEl)('');this.passedElement.placeholder&&(o.placeholder=this.passedElement.placeholder),this.options.addItems||(o.disabled=!0,t.classList.add("is-disabled")),t.appendChild(n),n.appendChild(i),n.appendChild(o),this.containerOuter=t,this.containerInner=n,this.input=o,this.list=i,this.presetItems.forEach(function(t){e.addItem(t)}),this.store.subscribe(this.render),this.render(),this.addEventListeners()}},{key:"renderMultipleSelectInput",value:function(){var e=this,t=(0,l.strToEl)('
'),n=(0,l.strToEl)('
');this.passedElement.classList.add("choices__input","choices__input--hidden"),this.passedElement.tabIndex="-1",this.passedElement.setAttribute("style","display:none;"),this.passedElement.setAttribute("aria-hidden","true"),(0,l.wrap)(this.passedElement,n),(0,l.wrap)(n,t);var i=(0,l.strToEl)('
'),o=(0,l.strToEl)(''),r=(0,l.strToEl)('
');o.placeholder&&(o.placeholder=this.passedElement.placeholder),this.options.addItems||(o.disabled=!0),t.appendChild(n),t.appendChild(r),n.appendChild(i),n.appendChild(o),this.containerOuter=t,this.containerInner=n,this.input=o,this.list=i,this.dropdown=r,this.presetItems.forEach(function(t){e.addItem(t)});for(var s=this.passedElement.options,a=0;a'+t.value+"");e.list.appendChild(n)}}),console.debug(t)}},{key:"renderInput",value:function(e){switch(this.options.debug&&console.debug("Render"),e.type){case"text":this.renderTextInput();break;case"select-one":break;case"select-multiple":this.renderMultipleSelectInput();break;default:this.renderTextInput()}}},{key:"init",value:function(){this.supports||console.error("init: Your browser doesn'nt support shit"),this.initialised=!0,this.renderInput(this.passedElement)}},{key:"destroy",value:function(){this.options=null,this.passedElement=null,this.initialised=null}}]),e}();document.addEventListener("DOMContentLoaded",function(){var e=(new d("#choices-1",{delimiter:" ",editItems:!0,maxItems:5,callbackOnRemoveItem:function(e){console.log(e)},callbackOnAddItem:function(e,t){console.log(e,t)}}),new d("#choices-2",{allowDuplicates:!1,editItems:!0}),new d("#choices-3",{allowDuplicates:!1,editItems:!0,regexFilter:/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/}),new d("#choices-4",{addItems:!1,removeItems:!1}),new d("#choices-5",{prependValue:"item-",appendValue:"-"+Date.now()}),new d("#choices-6",{items:["josh@joshuajohnson.co.uk","joe@bloggs.co.uk"]}));new d("#choices-7"),new d;e.addItem("josh2@joshuajohnson.co.uk"),e.removeItem("josh@joshuajohnson.co.uk"),console.log(e.getItemByValue("josh2@joshuajohnson.co.uk"))})},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0,t.compose=t.applyMiddleware=t.bindActionCreators=t.combineReducers=t.createStore=void 0;var o=n(3),r=i(o),s=n(8),a=i(s),c=n(10),u=i(c),l=n(11),d=i(l),h=n(12),p=i(h),f=n(9);i(f);t.createStore=r.default,t.combineReducers=a.default,t.bindActionCreators=u.default,t.applyMiddleware=d.default,t.compose=p.default},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){function i(){f===p&&(f=p.slice())}function r(){return h}function c(e){if("function"!=typeof e)throw new Error("Expected listener to be a function.");var t=!0;return i(),f.push(e),function(){if(t){t=!1,i();var n=f.indexOf(e);f.splice(n,1)}}}function u(e){if(!(0,s.default)(e))throw new Error("Actions must be plain objects. Use custom middleware for async actions.");if("undefined"==typeof e.type)throw new Error('Actions may not have an undefined "type" property. Have you misspelled a constant?');if(v)throw new Error("Reducers may not dispatch actions.");try{v=!0,h=d(h,e)}finally{v=!1}for(var t=p=f,n=0;nn;n++)t[n]=arguments[n];return function(e){return function(n,i,o){var s=e(n,i,o),c=s.dispatch,u=[],l={getState:s.getState,dispatch:function(e){return c(e)}};return u=t.map(function(e){return e(l)}),c=a.default.apply(void 0,u)(s.dispatch),r({},s,{dispatch:c})}}}var r=Object.assign||function(e){for(var t=1;tn;n++)t[n]=arguments[n];return function(){if(0===t.length)return arguments.length<=0?void 0:arguments[0];var e=t[t.length-1],n=t.slice(0,-1);return n.reduceRight(function(e,t){return t(e)},e.apply(void 0,arguments))}}t.__esModule=!0,t.default=n},function(e,t){"use strict";function n(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);to;o++){var r=arguments[o];n("Object",r)?i(r):console.error("Custom options must be an object")}return e},t.whichTransitionEvent=function(){var e,t=document.createElement("fakeelement"),n={transition:"transitionend",OTransition:"oTransitionEnd",MozTransition:"transitionend",WebkitTransition:"webkitTransitionEnd"};for(e in n)if(void 0!==t.style[e])return n[e]},t.whichAnimationEvent=function(){var e,t=document.createElement("fakeelement"),n={animation:"animationend",OAnimation:"oAnimationEnd",MozAnimation:"animationend",WebkitAnimation:"webkitAnimationEnd"};for(e in n)if(void 0!==t.style[e])return n[e]});t.getParentsUntil=function(e,t,n){for(var i=[];e&&e!==document;e=e.parentNode){if(t){var o=t.charAt(0);if("."===o&&e.classList.contains(t.substr(1)))break;if("#"===o&&e.id===t.substr(1))break;if("["===o&&e.hasAttribute(t.substr(1,t.length-1)))break;if(e.tagName.toLowerCase()===t)break}if(n){var r=n.charAt(0);"."===r&&e.classList.contains(n.substr(1))&&i.push(e),"#"===r&&e.id===n.substr(1)&&i.push(e),"["===r&&e.hasAttribute(n.substr(1,n.length-1))&&i.push(e),e.tagName.toLowerCase()===n&&i.push(e)}else i.push(e)}return 0===i.length?null:i},t.wrap=function(e,t){return t=t||document.createElement("div"),e.nextSibling?e.parentNode.insertBefore(t,e.nextSibling):e.parentNode.appendChild(t),t.appendChild(e)},t.getSiblings=function(e){for(var t=[],n=e.parentNode.firstChild;n;n=n.nextSibling)1===n.nodeType&&n!==e&&t.push(n);return t},t.findAncestor=function(e,t){for(;(e=e.parentElement)&&!e.classList.contains(t););return e},t.debounce=function(e,t,n){var i;return function(){var o=this,r=arguments,s=function(){i=null,n||e.apply(o,r)},a=n&&!i;clearTimeout(i),i=setTimeout(s,t),a&&e.apply(o,r)}},t.getElemDistance=function(e){var t=0;if(e.offsetParent)do t+=e.offsetTop,e=e.offsetParent;while(e);return t>=0?t:0},t.getElementOffset=function(e,t){var n=t;return n>1&&(n=1),n>0&&(n=0),Math.max(e.offsetHeight*n)},t.getScrollPosition=function(e){return"bottom"===e?Math.max((window.scrollY||window.pageYOffset)+(window.innerHeight||document.documentElement.clientHeight)):window.scrollY||window.pageYOffset},t.isInView=function(e,t,n){return this.getScrollPosition(t)>this.getElemDistance(e)+this.getElementOffset(e,n)},t.stripHTML=function(e){var t=document.createElement("DIV");return t.innerHTML=e,t.textContent||t.innerText||""},t.addAnimation=function(e,t){var n=i(),o=function r(){e.classList.remove(t),e.removeEventListener(n,r,!1)};e.classList.add(t),e.addEventListener(n,o,!1)},t.getRandomNumber=function(e,t){return Math.floor(Math.random()*(t-e)+e)},t.strToEl=function(){var e=document.createElement("div");return function(t){var n;for(e.innerHTML=t,n=e.children[0];e.firstChild;)e.removeChild(e.firstChild);return n}}(),t.getWidthOfInput=function(){var e=document.createElement("span");e.className="tmp-element",e.innerHTML=inputEl.value.replace(/&/g,"&").replace(//g,">"),document.body.appendChild(e);var t=e.getBoundingClientRect().width;return document.body.removeChild(e),t}}]); \ No newline at end of file +!function(e){function t(i){if(n[i])return n[i].exports;var o=n[i]={exports:{},id:i,loaded:!1};return e[i].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="/assets/scripts/dist/",t(0)}([function(e,t,n){e.exports=n(1)},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0}),t.Choices=void 0;var s=function(){function e(e,t){for(var n=0;n1)for(var l=1;l=0;n--){var i=this.list.children[n];if(i.innerHTML===e.toString()){t=i;break}}if(t){var o=t.getAttribute("data-choice-id"),s=t.innerHTML;this.options.callbackOnRemoveItem&&((0,u.isType)("Function",this.options.callbackOnRemoveItem)?this.options.callbackOnRemoveItem(s):console.error("callbackOnRemoveItem: Callback is not a function")),this.store.dispatch((0,l.removeItemFromStore)(o))}else console.error("Item not found")}},{key:"removeAll",value:function(e){for(var t=0;t'+e+"");this.dropdown.appendChild(t)}},{key:"renderTextInput",value:function(){var e=this,t=(0,u.strToEl)('
'),n=(0,u.strToEl)('
');this.passedElement.classList.add(this.options.classNames.input,this.options.classNames.hiddenState),this.passedElement.tabIndex="-1",this.passedElement.setAttribute("style","display:none;"),this.passedElement.setAttribute("aria-hidden","true"),(0,u.wrap)(this.passedElement,n),(0,u.wrap)(n,t);var i=(0,u.strToEl)('
    '),o=(0,u.strToEl)('');this.passedElement.placeholder&&(o.placeholder=this.passedElement.placeholder),this.options.addItems||(o.disabled=!0,t.classList.add(this.options.classNames.disabledState)),t.appendChild(n),n.appendChild(i),n.appendChild(o),this.containerOuter=t,this.containerInner=n,this.input=o,this.list=i,this.presetItems.forEach(function(t){e.addItem(t)}),this.store.subscribe(this.render),this.render(),this.addEventListeners()}},{key:"renderMultipleSelectInput",value:function(){var e=this,t=(0,u.strToEl)('
    '),n=(0,u.strToEl)('
    ');this.passedElement.classList.add(this.options.classNames.input,this.options.classNames.hiddenState),this.passedElement.tabIndex="-1",this.passedElement.setAttribute("style","display:none;"),this.passedElement.setAttribute("aria-hidden","true"),(0,u.wrap)(this.passedElement,n),(0,u.wrap)(n,t);var i=(0,u.strToEl)('
      '),o=(0,u.strToEl)(''),s=(0,u.strToEl)('
      ');o.placeholder&&(o.placeholder=this.passedElement.placeholder),this.options.addItems||(o.disabled=!0),t.appendChild(n),t.appendChild(s),n.appendChild(i),n.appendChild(o),this.containerOuter=t,this.containerInner=n,this.input=o,this.list=i,this.dropdown=s,this.presetItems.forEach(function(t){e.addItem(t)});for(var r=this.passedElement.options,a=0;a'+t.value+"");e.list.appendChild(n)}}),console.debug(t)}},{key:"renderInput",value:function(e){switch(this.options.debug&&console.debug("Render"),e.type){case"text":this.renderTextInput();break;case"select-one":break;case"select-multiple":this.renderMultipleSelectInput();break;default:this.renderTextInput()}}},{key:"init",value:function(){this.supports||console.error("init: Your browser doesn'nt support shit"),this.initialised=!0,this.renderInput(this.passedElement)}},{key:"destroy",value:function(){this.options=null,this.passedElement=null,this.initialised=null}}]),e}();document.addEventListener("DOMContentLoaded",function(){var e=(new d("#choices-1",{delimiter:" ",editItems:!0,maxItems:5,callbackOnRemoveItem:function(e){console.log(e)},callbackOnAddItem:function(e,t){console.log(e,t)}}),new d("#choices-2",{allowDuplicates:!1,editItems:!0}),new d("#choices-3",{allowDuplicates:!1,editItems:!0,regexFilter:/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/}),new d("#choices-4",{addItems:!1,removeItems:!1}),new d("#choices-5",{prependValue:"item-",appendValue:"-"+Date.now()}),new d("#choices-6",{items:["josh@joshuajohnson.co.uk","joe@bloggs.co.uk"]}));new d("#choices-7"),new d;e.addItem("josh2@joshuajohnson.co.uk"),e.removeItem("josh@joshuajohnson.co.uk"),console.log(e.getItemByValue("josh2@joshuajohnson.co.uk"))})},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0,t.compose=t.applyMiddleware=t.bindActionCreators=t.combineReducers=t.createStore=void 0;var o=n(3),s=i(o),r=n(7),a=i(r),c=n(9),l=i(c),u=n(10),d=i(u),p=n(11),h=i(p),f=n(8);i(f);t.createStore=s.default,t.combineReducers=a.default,t.bindActionCreators=l.default,t.applyMiddleware=d.default,t.compose=h.default},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){function i(){f===h&&(f=h.slice())}function s(){return p}function c(e){if("function"!=typeof e)throw new Error("Expected listener to be a function.");var t=!0;return i(),f.push(e),function(){if(t){t=!1,i();var n=f.indexOf(e);f.splice(n,1)}}}function l(e){if(!(0,r.default)(e))throw new Error("Actions must be plain objects. Use custom middleware for async actions.");if("undefined"==typeof e.type)throw new Error('Actions may not have an undefined "type" property. Have you misspelled a constant?');if(m)throw new Error("Reducers may not dispatch actions.");try{m=!0,p=d(p,e)}finally{m=!1}for(var t=h=f,n=0;nn;n++)t[n]=arguments[n];return function(e){return function(n,i,o){var r=e(n,i,o),c=r.dispatch,l=[],u={getState:r.getState,dispatch:function(e){return c(e)}};return l=t.map(function(e){return e(u)}),c=a.default.apply(void 0,l)(r.dispatch),s({},r,{dispatch:c})}}}var s=Object.assign||function(e){for(var t=1;tn;n++)t[n]=arguments[n];return function(){if(0===t.length)return arguments.length<=0?void 0:arguments[0];var e=t[t.length-1],n=t.slice(0,-1);return n.reduceRight(function(e,t){return t(e)},e.apply(void 0,arguments))}}t.__esModule=!0,t.default=n},function(e,t){"use strict";function n(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);to;o++){var s=arguments[o];n("Object",s)?i(s):console.error("Custom options must be an object")}return e},t.whichTransitionEvent=function(){var e,t=document.createElement("fakeelement"),n={transition:"transitionend",OTransition:"oTransitionEnd",MozTransition:"transitionend",WebkitTransition:"webkitTransitionEnd"};for(e in n)if(void 0!==t.style[e])return n[e]},t.whichAnimationEvent=function(){var e,t=document.createElement("fakeelement"),n={animation:"animationend",OAnimation:"oAnimationEnd",MozAnimation:"animationend",WebkitAnimation:"webkitAnimationEnd"};for(e in n)if(void 0!==t.style[e])return n[e]});t.getParentsUntil=function(e,t,n){for(var i=[];e&&e!==document;e=e.parentNode){if(t){var o=t.charAt(0);if("."===o&&e.classList.contains(t.substr(1)))break;if("#"===o&&e.id===t.substr(1))break;if("["===o&&e.hasAttribute(t.substr(1,t.length-1)))break;if(e.tagName.toLowerCase()===t)break}if(n){var s=n.charAt(0);"."===s&&e.classList.contains(n.substr(1))&&i.push(e),"#"===s&&e.id===n.substr(1)&&i.push(e),"["===s&&e.hasAttribute(n.substr(1,n.length-1))&&i.push(e),e.tagName.toLowerCase()===n&&i.push(e)}else i.push(e)}return 0===i.length?null:i},t.wrap=function(e,t){return t=t||document.createElement("div"),e.nextSibling?e.parentNode.insertBefore(t,e.nextSibling):e.parentNode.appendChild(t),t.appendChild(e)},t.getSiblings=function(e){for(var t=[],n=e.parentNode.firstChild;n;n=n.nextSibling)1===n.nodeType&&n!==e&&t.push(n);return t},t.findAncestor=function(e,t){for(;(e=e.parentElement)&&!e.classList.contains(t););return e},t.debounce=function(e,t,n){var i;return function(){var o=this,s=arguments,r=function(){i=null,n||e.apply(o,s)},a=n&&!i;clearTimeout(i),i=setTimeout(r,t),a&&e.apply(o,s)}},t.getElemDistance=function(e){var t=0;if(e.offsetParent)do t+=e.offsetTop,e=e.offsetParent;while(e);return t>=0?t:0},t.getElementOffset=function(e,t){var n=t;return n>1&&(n=1),n>0&&(n=0),Math.max(e.offsetHeight*n)},t.getScrollPosition=function(e){return"bottom"===e?Math.max((window.scrollY||window.pageYOffset)+(window.innerHeight||document.documentElement.clientHeight)):window.scrollY||window.pageYOffset},t.isInView=function(e,t,n){return this.getScrollPosition(t)>this.getElemDistance(e)+this.getElementOffset(e,n)},t.stripHTML=function(e){var t=document.createElement("DIV");return t.innerHTML=e,t.textContent||t.innerText||""},t.addAnimation=function(e,t){var n=i(),o=function s(){e.classList.remove(t),e.removeEventListener(n,s,!1)};e.classList.add(t),e.addEventListener(n,o,!1)},t.getRandomNumber=function(e,t){return Math.floor(Math.random()*(t-e)+e)},t.strToEl=function(){var e=document.createElement("div");return function(t){var n;for(e.innerHTML=t,n=e.children[0];e.firstChild;)e.removeChild(e.firstChild);return n}}(),t.getWidthOfInput=function(){var e=document.createElement("span");e.className="tmp-element",e.innerHTML=inputEl.value.replace(/&/g,"&").replace(//g,">"),document.body.appendChild(e);var t=e.getBoundingClientRect().width;return document.body.removeChild(e),t}}]); \ No newline at end of file diff --git a/assets/scripts/src/choices.js b/assets/scripts/src/choices.js index 20e5520..3bd7c74 100644 --- a/assets/scripts/src/choices.js +++ b/assets/scripts/src/choices.js @@ -37,9 +37,19 @@ export class Choices { appendValue: false, selectAll: true, classNames: { - input: '', - container: '', - + containerOuter: 'choices', + containerInner: 'choices__inner', + input: 'choices__input', + inputCloned: 'choices__input--cloned', + list: 'choices__list', + listItems: 'choices__list--items', + listDropdown: 'choices__list--dropdown', + item: 'choices__item', + itemSelectable: 'choices__item--selectable', + activeState: 'is-active', + disabledState: 'is-disabled', + hiddenState: 'is-hidden', + selectedState: 'is-selected' }, callbackOnInit: function() {}, callbackOnRender: function() {}, @@ -77,7 +87,6 @@ export class Choices { this.onKeyDown = this.onKeyDown.bind(this); this.onClick = this.onClick.bind(this); this.onFocus = this.onFocus.bind(this); - this.onBlur = this.onBlur.bind(this); // Let's have it large this.init(); @@ -181,7 +190,7 @@ export class Choices { let handleBackspaceKey = () => { if(this.options.removeItems) { let currentListItems = this.list.querySelectorAll('[data-choice-item]'); - let selectedItems = this.list.querySelectorAll('.is-selected'); + let selectedItems = this.list.querySelectorAll(this.options.classNames.selectedState); let lastItem = currentListItems[currentListItems.length - 1]; let inputIsFocussed = this.input === document.activeElement; @@ -214,38 +223,44 @@ export class Choices { * @return */ onClick(e) { - // I don't like the look of this - if(e.target.hasAttribute('data-choice-item')) { - let item = e.target; + // If click is affecting a child node of our element + if(this.containerOuter.contains(e.target)) { + if(e.target.hasAttribute('data-choice-item')) { + let item = e.target; - let handleClick = (item) => { - if(this.options.removeItems) { - let passedId = item.getAttribute('data-choice-id'); - let items = this.list.children; + let handleClick = (item) => { + if(this.options.removeItems) { + let passedId = item.getAttribute('data-choice-id'); + let items = this.list.children; - // We only want to select one item with a click - // so we deselect any items that aren't the target - for (var i = 0; i < items.length; i++) { - let singleItem = items[i]; - let id = singleItem.getAttribute('data-choice-id');; + // We only want to select one item with a click + // so we deselect any items that aren't the target + for (var i = 0; i < items.length; i++) { + let singleItem = items[i]; + let id = singleItem.getAttribute('data-choice-id');; - if(id === passedId && !singleItem.classList.contains('is-selected')) { - this.selectItem(singleItem); - } else { - this.deselectItem(singleItem); - } - } + if(id === passedId && !singleItem.classList.contains(this.options.classNames.selectedState)) { + this.selectItem(singleItem); + } else { + this.deselectItem(singleItem); + } + } + } } + + handleClick(item); } - - handleClick(item); - } - if(e.target.hasAttribute('data-choice-selectable')) { - let item = e.target; - let value = e.target.getAttribute('data-choice-value'); - this.addItem(value); + + if(e.target.hasAttribute('data-choice-selectable')) { + let item = e.target; + let value = e.target.getAttribute('data-choice-value'); + this.addItem(value); + } + } else if(this.dropdown && this.dropdown.classList.contains(this.options.classNames.activeState)) { + this.toggleDropdown(); } + } onFocus(e) { @@ -254,12 +269,6 @@ export class Choices { } } - onBlur(e) { - if(this.dropdown) { - this.toggleDropdown(); - } - } - /* Methods */ /** @@ -353,6 +362,11 @@ export class Choices { // Generate unique id let id = this.store.getState().length + 1; + // Close dropdown + if(this.dropdown && this.dropdown.classList.contains('is-active')) { + this.toggleDropdown(); + } + // Run callback if it is a function if(this.options.callbackOnAddItem){ if(isType('Function', this.options.callbackOnAddItem)) { @@ -377,6 +391,7 @@ export class Choices { // We are re-assigning a variable here. Probably shouldn't be doing that... let item; + if(itemOrValue.nodeType) { item = itemOrValue; } else { @@ -436,7 +451,7 @@ export class Choices { } addItemToDropdown(value) { - const dropdownItem = strToEl(`
    • ${value}
    • `); + const dropdownItem = strToEl(`
    • ${value}
    • `); this.dropdown.appendChild(dropdownItem); } @@ -459,11 +474,11 @@ export class Choices { */ - let containerOuter = strToEl(`
      `); - let containerInner = strToEl(`
      `); + let containerOuter = strToEl(`
      `); + let containerInner = strToEl(`
      `); // Hide passed input - this.passedElement.classList.add('choices__input', 'choices__input--hidden'); + this.passedElement.classList.add(this.options.classNames.input, this.options.classNames.hiddenState); this.passedElement.tabIndex = '-1'; this.passedElement.setAttribute('style', 'display:none;'); this.passedElement.setAttribute('aria-hidden', 'true'); @@ -474,8 +489,8 @@ export class Choices { // Wrapper inner container with outer container wrap(containerInner, containerOuter); - let list = strToEl(`
      `); - let input = strToEl(``); + let list = strToEl(`
        `); + let input = strToEl(``); if (this.passedElement.placeholder) { input.placeholder = this.passedElement.placeholder; @@ -483,7 +498,7 @@ export class Choices { if(!this.options.addItems) { input.disabled = true; - containerOuter.classList.add('is-disabled'); + containerOuter.classList.add(this.options.classNames.disabledState); } containerOuter.appendChild(containerInner); @@ -527,11 +542,11 @@ export class Choices { */ - let containerOuter = strToEl('
        '); - let containerInner = strToEl('
        '); + let containerOuter = strToEl(`
        `); + let containerInner = strToEl(`
        `); // Hide passed input - this.passedElement.classList.add('choices__input', 'choices__input--hidden'); + this.passedElement.classList.add(this.options.classNames.input, this.options.classNames.hiddenState); this.passedElement.tabIndex = '-1'; this.passedElement.setAttribute('style', 'display:none;'); this.passedElement.setAttribute('aria-hidden', 'true'); @@ -542,9 +557,9 @@ export class Choices { // Wrapper inner container with outer container wrap(containerInner, containerOuter); - let list = strToEl('
        '); - let input = strToEl(''); - let dropdown = strToEl('
        '); + let list = strToEl(`
          `); + let input = strToEl(``); + let dropdown = strToEl(`
          `); if (input.placeholder) { input.placeholder = this.passedElement.placeholder; @@ -588,16 +603,14 @@ export class Choices { addEventListeners() { document.addEventListener('keydown', this.onKeyDown); - this.containerOuter.addEventListener('click', this.onClick); + document.addEventListener('click', this.onClick); this.input.addEventListener('focus', this.onFocus); - this.input.addEventListener('blur', this.onBlur); } removeEventListeners() { document.removeEventListener('keydown', this.onKeyDown); - this.containerOuter.removeEventListener('click', this.onClick); + document.removeEventListener('click', this.onClick); this.input.removeEventListener('focus', this.onFocus); - this.input.removeEventListener('blur', this.onBlur); } /** @@ -623,7 +636,7 @@ export class Choices { state.forEach((item) => { if(item.active) { // Create new list element - let listItem = strToEl(`
          ${ item.value }
          `); + let listItem = strToEl(`
        • ${ item.value }
        • `); // Append it to list this.list.appendChild(listItem);