From 6ac55c9e37cbd69ddf4360588334689d623c24d1 Mon Sep 17 00:00:00 2001 From: Josh Johnson Date: Tue, 12 Apr 2016 22:42:56 +0100 Subject: [PATCH] Use const instead of let where possible + selecting options --- assets/scripts/dist/bundle.js | 2 +- assets/scripts/src/choices.js | 131 ++++++++++++------------- assets/scripts/src/reducers/options.js | 2 +- assets/styles/css/choices.css | 21 ++++ assets/styles/css/choices.min.css | 2 +- assets/styles/scss/choices.scss | 21 +++- index.html | 23 +---- 7 files changed, 108 insertions(+), 94 deletions(-) diff --git a/assets/scripts/dist/bundle.js b/assets/scripts/dist/bundle.js index 0013dca..f233b46 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 s=function(){function e(e,t){for(var n=0;n1)for(var l=1;l'),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.dropdown.appendChild(n)}));var s=i.reduce(function(e,t){return e.push(t.value),e},[]);this.passedElement.value=s.join(this.options.delimiter),this.list.innerHTML="",i.forEach(function(t){if(t.active){var n=(0,u.strToEl)('
    • '+t.value+"
    • ");e.list.appendChild(n)}}),t&&((0,u.isType)("Function",t)?t(i,o):console.error("callbackOnRender: Callback is not a function"))}},{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(){var e=arguments.length<=0||void 0===arguments[0]?this.options.callbackOnInit:arguments[0];this.supports||console.error("init: Your browser doesn'nt support shit"),this.initialised=!0,this.renderInput(this.passedElement),e&&((0,u.isType)("Function",e)?e():console.error("callbackOnInit: Callback is not a function"))}},{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}),new d("#choices-2",{allowDuplicates:!1,editItems:!0,callbackOnRender:function(e){console.log(e)}}),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,}))$/,callbackOnRender:function(e){console.log(e)}}),new d("#choices-4",{addItems:!1,removeItems:!1,callbackOnRender:function(e){console.log(e)}}),new d("#choices-5",{prependValue:"item-",appendValue:"-"+Date.now(),callbackOnRender:function(e){console.log(e)}}));e.removeAllItems();var t=new d("#choices-6",{items:["josh@joshuajohnson.co.uk","joe@bloggs.co.uk"],callbackOnRender:function(e){console.log(e)}});new d("#choices-7",{callbackOnRender:function(e,t){console.log(t)}}),new d;t.addItem("josh2@joshuajohnson.co.uk",function(){console.log("Custom add item callback")}),t.removeItem("josh@joshuajohnson.co.uk"),console.log(t.getItemById(1))})},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(8),a=i(r),c=n(10),l=i(c),u=n(11),d=i(u),p=n(12),h=i(p),f=n(9);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,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),s=n(14),r=i(s),a=n(15),c=i(a),l=(0,o.combineReducers)({items:r.default,options:c.default});t.default=l},function(e,t){"use strict";function n(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);tr;r++){var a=arguments[r];n("Object",a)?s(a):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 +!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'),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)});var r=Array.prototype.slice.call(this.passedElement.options);r.forEach(function(t){e.addOptionToDropdown(t.value)}),this.store.subscribe(this.render),this.render(),this.addEventListeners()}},{key:"addEventListeners",value:function(){document.addEventListener("keydown",this.onKeyDown),document.addEventListener("click",this.onClick)}},{key:"removeEventListeners",value:function(){document.removeEventListener("keydown",this.onKeyDown),document.removeEventListener("click",this.onClick)}},{key:"render",value:function(){var e=this,t=arguments.length<=0||void 0===arguments[0]?this.options.callbackOnRender:arguments[0],n=this.options.classNames,i=this.store.getState(),o=i.items,s=i.options;if(this.dropdown)if(this.dropdown.innerHTML="",s)s.forEach(function(t){var i=(0,u.strToEl)('
        • '+t.value+"
        • ");e.dropdown.appendChild(i)});else{var r=(0,u.strToEl)('
        • No options to select
        • ');this.dropdown.appendChild(r)}var a=o.reduce(function(e,t){return e.push(t.value),e},[]);this.passedElement.value=a.join(this.options.delimiter),this.list.innerHTML="",o.forEach(function(t){if(t.active){var i=(0,u.strToEl)('
        • '+t.value+"
        • ");e.list.appendChild(i)}}),t&&((0,u.isType)("Function",t)?t(o,s):console.error("callbackOnRender: Callback is not a function"))}},{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(){var e=arguments.length<=0||void 0===arguments[0]?this.options.callbackOnInit:arguments[0];this.supports||console.error("init: Your browser doesn'nt support shit"),this.initialised=!0,this.renderInput(this.passedElement),e&&((0,u.isType)("Function",e)?e():console.error("callbackOnInit: Callback is not a function"))}},{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}),new d("#choices-2",{allowDuplicates:!1,editItems:!0,callbackOnRender:function(e){console.log(e)}}),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,}))$/,callbackOnRender:function(e){console.log(e)}}),new d("#choices-4",{addItems:!1,removeItems:!1,callbackOnRender:function(e){console.log(e)}}),new d("#choices-5",{prependValue:"item-",appendValue:"-"+Date.now(),callbackOnRender:function(e){console.log(e)}}));e.removeAllItems();var t=new d("#choices-6",{items:["josh@joshuajohnson.co.uk","joe@bloggs.co.uk"],callbackOnRender:function(e){console.log(e)}});new d("#choices-7",{callbackOnRender:function(e,t){console.log(e)}}),new d;t.addItem("josh2@joshuajohnson.co.uk",function(){console.log("Custom add item callback")}),t.removeItem("josh@joshuajohnson.co.uk"),console.log(t.getItemById(1))})},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(8),a=i(r),c=n(10),l=i(c),u=n(11),d=i(u),p=n(12),h=i(p),f=n(9);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,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),s=n(14),r=i(s),a=n(15),c=i(a),l=(0,o.combineReducers)({items:r.default,options:c.default});t.default=l},function(e,t){"use strict";function n(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);tr;r++){var a=arguments[r];n("Object",a)?s(a):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 48f6bc3..00ca9f1 100644 --- a/assets/scripts/src/choices.js +++ b/assets/scripts/src/choices.js @@ -13,7 +13,7 @@ export class Choices { // If there are multiple elements, create a new instance // for each element besides the first one (as that already has an instance) if(isType('String', element)) { - let elements = document.querySelectorAll(element); + const elements = document.querySelectorAll(element); if(elements.length > 1) { for (let i = 1; i < elements.length; i++) { let el = elements[i]; @@ -46,6 +46,8 @@ export class Choices { listDropdown: 'choices__list--dropdown', item: 'choices__item', itemSelectable: 'choices__item--selectable', + itemDisabled: 'choices__item--disabled', + itemOption: 'choices__item--option', activeState: 'is-active', disabledState: 'is-disabled', hiddenState: 'is-hidden', @@ -86,7 +88,6 @@ export class Choices { this.destroy = this.destroy.bind(this); this.onKeyDown = this.onKeyDown.bind(this); this.onClick = this.onClick.bind(this); - this.onFocus = this.onFocus.bind(this); // Let's have it large this.init(); @@ -107,7 +108,7 @@ export class Choices { * @return {Boolean} */ isEmpty() { - return (this.store.getState().length === 0) ? true : false; + return (this.store.getState().items.length === 0) ? true : false; } /* Event handling */ @@ -130,7 +131,7 @@ export class Choices { // If CTRL + A or CMD + A have been pressed and there are items to select if (ctrlDownKey && e.keyCode === aKey && this.list && this.list.children) { - let handleSelectAll = () => { + const handleSelectAll = () => { if(this.options.removeItems && !this.input.value && this.options.selectAll && this.input === document.activeElement) { this.selectAll(this.list.children); } @@ -143,7 +144,7 @@ export class Choices { if (e.keyCode === enterKey && e.target.value) { let value = this.input.value; - let handleEnter = () => { + const handleEnter = () => { let canUpdate = true; // If there is a max entry limit and we have reached that limit @@ -188,7 +189,7 @@ export class Choices { // If backspace or delete key is pressed and the input has no value if (e.keyCode === deleteKey && !e.target.value) { - let handleBackspaceKey = () => { + const handleBackspaceKey = () => { if(this.options.removeItems) { let inputIsFocussed = this.input === document.activeElement; @@ -226,12 +227,18 @@ export class Choices { * @return */ onClick(e) { + if(this.dropdown) { + this.toggleDropdown(); + } + // If click is affecting a child node of our element if(this.containerOuter.contains(e.target)) { const state = this.store.getState(); const items = state.items; const options = state.options; + + if(this.input !== document.activeElement) { this.input.focus(); } @@ -239,7 +246,7 @@ export class Choices { if(e.target.hasAttribute('data-choice-item')) { let item = e.target; - let handleClick = (item) => { + const handleClick = (item) => { if(this.options.removeItems) { let passedId = item.getAttribute('data-choice-id'); @@ -256,17 +263,16 @@ export class Choices { } handleClick(item); - } - if(e.target.hasAttribute('data-choice-selectable')) { + } else if(e.target.hasAttribute('data-choice-selectable')) { let id = e.target.getAttribute('data-choice-id'); let option = options.find((option) => { return option.id === parseInt(id); }); - if(option) { - this.selectOption(id); + if(!option.selected) { + this.selectOption(id, true); this.addItem(option.value); } } @@ -281,12 +287,6 @@ export class Choices { } - onFocus(e) { - if(this.dropdown) { - this.toggleDropdown(); - } - } - /* Methods */ /** @@ -303,8 +303,8 @@ export class Choices { * @return {Boolean} Whether test passed/failed */ regexFilter(value) { - let expression = new RegExp(this.options.regexFilter, 'i'); - let passesTest = expression.test(value); + const expression = new RegExp(this.options.regexFilter, 'i'); + const passesTest = expression.test(value); return passesTest; } @@ -320,14 +320,14 @@ export class Choices { return; } - let state = this.store.getState(); - let items = state.items; + const state = this.store.getState(); + const items = state.items; - let itemObject = items.find((item) => { + const itemObject = items.find((item) => { return item.id === parseInt(id); }); - let item = this.list.querySelector(`[data-choice-id='${ itemObject.id }']`); + const item = this.list.querySelector(`[data-choice-id='${ itemObject.id }']`); return item; } @@ -339,7 +339,7 @@ export class Choices { */ selectItem(item) { if(!item) return; - let id = item.id; + const id = item.id; this.store.dispatch(selectItem(id, true)); } @@ -350,7 +350,7 @@ export class Choices { */ deselectItem(item) { if(!item) return; - let id = item.id; + const id = item.id; this.store.dispatch(selectItem(id, false)); } @@ -375,9 +375,9 @@ export class Choices { }); } - selectOption(id) { + selectOption(id, value) { if(!id) return; - this.store.dispatch(selectOption(id)); + this.store.dispatch(selectOption(id, value)); } /** @@ -480,7 +480,8 @@ export class Choices { addOptionToDropdown(value) { // Generate unique id - let id = this.store.getState().items.length + 1; + let state = this.store.getState(); + let id = state.options.length + 1; this.store.dispatch(addOption(value, id)); } @@ -559,20 +560,8 @@ export class Choices { * @return */ renderMultipleSelectInput() { - /* - Template: - -
          -
          - -
            - -
            -
            - */ - - let containerOuter = strToEl(`
            `); - let containerInner = strToEl(`
            `); + const containerOuter = strToEl(`
            `); + const containerInner = strToEl(`
            `); // Hide passed input this.passedElement.classList.add(this.options.classNames.input, this.options.classNames.hiddenState); @@ -586,9 +575,9 @@ export class Choices { // Wrapper inner container with outer container wrap(containerInner, containerOuter); - let list = strToEl(`
              `); - let input = strToEl(``); - let dropdown = strToEl(`
              `); + const list = strToEl(`
                `); + const input = strToEl(``); + const dropdown = strToEl(`
                `); if (input.placeholder) { input.placeholder = this.passedElement.placeholder; @@ -613,12 +602,11 @@ export class Choices { this.presetItems.forEach((value) => { this.addItem(value); }); - - const unselectedOptions = this.passedElement.options; - for (var i = 0; i < unselectedOptions.length; i++) { - let option = unselectedOptions[i]; + + const passedOptions = Array.prototype.slice.call(this.passedElement.options); + passedOptions.forEach((option) => { this.addOptionToDropdown(option.value); - } + }); // Subscribe to store this.store.subscribe(this.render); @@ -633,13 +621,11 @@ export class Choices { addEventListeners() { document.addEventListener('keydown', this.onKeyDown); document.addEventListener('click', this.onClick); - this.input.addEventListener('focus', this.onFocus); } removeEventListeners() { document.removeEventListener('keydown', this.onKeyDown); document.removeEventListener('click', this.onClick); - this.input.removeEventListener('focus', this.onFocus); } /** @@ -647,9 +633,10 @@ export class Choices { * @return */ render(callback = this.options.callbackOnRender) { - let state = this.store.getState(); - let items = state.items; - let options = state.options; + const classNames = this.options.classNames; + const state = this.store.getState(); + const items = state.items; + const options = state.options; // OPTIONS if(this.dropdown) { @@ -657,16 +644,22 @@ export class Choices { this.dropdown.innerHTML = ''; // Add each option to dropdown - options.forEach((option) => { - const dropdownItem = strToEl(`
              • ${ option.value }
              • `); + if(options) { + options.forEach((option) => { + const dropdownItem = strToEl(`
              • ${ option.value }
              • `); + this.dropdown.appendChild(dropdownItem); + }); + } else { + const dropdownItem = strToEl(`
              • No options to select
              • `); this.dropdown.appendChild(dropdownItem); - }); + } + } // ITEMS // Simplify store data to just values - let valueArray = items.reduce((prev, current) => { + const valueArray = items.reduce((prev, current) => { prev.push(current.value); return prev; }, []); @@ -681,7 +674,7 @@ export class Choices { items.forEach((item) => { if(item.active) { // Create new list element - const listItem = strToEl(`
              • ${ item.value }
              • `); + const listItem = strToEl(`
              • ${ item.value }
              • `); // Append it to list this.list.appendChild(listItem); @@ -751,7 +744,7 @@ export class Choices { }; document.addEventListener('DOMContentLoaded', () => { - let choices1 = new Choices('#choices-1', { + const choices1 = new Choices('#choices-1', { delimiter: ' ', editItems: true, maxItems: 5, @@ -766,7 +759,7 @@ document.addEventListener('DOMContentLoaded', () => { // } }); - let choices2 = new Choices('#choices-2', { + const choices2 = new Choices('#choices-2', { allowDuplicates: false, editItems: true, callbackOnRender: function(items) { @@ -774,7 +767,7 @@ document.addEventListener('DOMContentLoaded', () => { } }); - let choices3 = new Choices('#choices-3', { + const choices3 = new Choices('#choices-3', { allowDuplicates: false, editItems: true, 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,}))$/, @@ -783,7 +776,7 @@ document.addEventListener('DOMContentLoaded', () => { } }); - let choices4 = new Choices('#choices-4', { + const choices4 = new Choices('#choices-4', { addItems: false, removeItems: false, callbackOnRender: function(items) { @@ -791,7 +784,7 @@ document.addEventListener('DOMContentLoaded', () => { } }); - let choices5 = new Choices('#choices-5', { + const choices5 = new Choices('#choices-5', { prependValue: 'item-', appendValue: `-${Date.now()}`, callbackOnRender: function(items) { @@ -801,20 +794,20 @@ document.addEventListener('DOMContentLoaded', () => { choices5.removeAllItems(); - let choices6 = new Choices('#choices-6', { + const choices6 = new Choices('#choices-6', { items: ['josh@joshuajohnson.co.uk', 'joe@bloggs.co.uk'], callbackOnRender: function(items) { console.log(items); } }); - let choices7 = new Choices('#choices-7', { + const choices7 = new Choices('#choices-7', { callbackOnRender: function(items, options) { - console.log(options); + console.log(items); } }); - let choicesMultiple = new Choices(); + const choicesMultiple = new Choices(); choices6.addItem('josh2@joshuajohnson.co.uk', () => { console.log('Custom add item callback')}); choices6.removeItem('josh@joshuajohnson.co.uk'); diff --git a/assets/scripts/src/reducers/options.js b/assets/scripts/src/reducers/options.js index 16e6b49..044feb1 100644 --- a/assets/scripts/src/reducers/options.js +++ b/assets/scripts/src/reducers/options.js @@ -14,7 +14,7 @@ const options = (state = [], action) => { case 'SELECT_OPTION': return state.map((option) => { if(option.id === parseInt(action.id)) { - option.selected = action.value; + option.selected = action.selected; } return option; diff --git a/assets/styles/css/choices.css b/assets/styles/css/choices.css index 7d8e66e..09a5bd4 100644 --- a/assets/styles/css/choices.css +++ b/assets/styles/css/choices.css @@ -77,6 +77,7 @@ h1, h2, h3, h4, h5, h6 { width: 100%; background-color: #FFFFFF; border: 1px solid #DDDDDD; + top: 100%; margin-top: -1px; display: none; border-bottom-left-radius: .25rem; @@ -86,8 +87,21 @@ h1, h2, h3, h4, h5, h6 { font-size: 1.4rem; } .choices__list--dropdown .choices__item:hover { background-color: #f9f9f9; } + .choices__list--dropdown .choices__item.is-selected { + opacity: .5; } + .choices__list--dropdown .choices__item.is-selected:hover { + background-color: #FFFFFF; } .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; } @@ -95,6 +109,13 @@ h1, h2, h3, h4, h5, h6 { .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__input { background-color: #f9f9f9; font-size: 1.4rem; diff --git a/assets/styles/css/choices.min.css b/assets/styles/css/choices.min.css index d00b796..21b305e 100644 --- a/assets/styles/css/choices.min.css +++ b/assets/styles/css/choices.min.css @@ -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}.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}.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;margin-top:-1px;display:none;border-bottom-left-radius:.25rem;border-bottom-right-radius:.25rem}.choices__list--dropdown .choices__item{padding:1rem;font-size:1.4rem}.choices__list--dropdown .choices__item:hover{background-color:#f9f9f9}.choices__list--dropdown.is-active{display:block}.choices__item{cursor:default}.choices__item--selectable{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} \ No newline at end of file +*,: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}.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}.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}.choices__list--dropdown .choices__item{padding:1rem;font-size:1.4rem}.choices__list--dropdown .choices__item:hover{background-color:#f9f9f9}.choices__list--dropdown .choices__item.is-selected{opacity:.5}.choices__list--dropdown .choices__item.is-selected:hover{background-color:#fff}.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__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} \ No newline at end of file diff --git a/assets/styles/scss/choices.scss b/assets/styles/scss/choices.scss index b47453d..7239ccf 100644 --- a/assets/styles/scss/choices.scss +++ b/assets/styles/scss/choices.scss @@ -94,6 +94,7 @@ h1, h2, h3, h4, h5, h6 { width: 100%; background-color: #FFFFFF; border: 1px solid #DDDDDD; + top: 100%; margin-top: -1px; display: none; border-bottom-left-radius: .25rem; @@ -101,15 +102,31 @@ h1, h2, h3, h4, h5, h6 { .choices__item { padding: 1rem; font-size: 1.4rem; - &:hover { - background-color: mix(#000000, #FFFFFF, 2.5%); + &:hover { background-color: mix(#000000, #FFFFFF, 2.5%); } + &.is-selected { + opacity: .5; + &:hover { background-color: #FFFFFF; } } } &.is-active { display: block; } + &.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; + user-select: none; +} .choices__input { background-color: mix(#000000, #FFFFFF, 2.5%); diff --git a/index.html b/index.html index 3e91359..5921399 100644 --- a/index.html +++ b/index.html @@ -31,14 +31,15 @@ @@ -48,24 +49,6 @@ - - -