From 9679a429669950e398b79ffabfc968ad1ee15b5b Mon Sep 17 00:00:00 2001 From: Josh Johnson Date: Thu, 14 Apr 2016 14:43:36 +0100 Subject: [PATCH] Associate options and items --- assets/scripts/dist/bundle.js | 2 +- assets/scripts/src/actions/index.js | 16 +++--- assets/scripts/src/choices.js | 68 ++++++++++++++------------ assets/scripts/src/reducers/items.js | 7 +-- assets/scripts/src/reducers/options.js | 22 +++++++-- 5 files changed, 69 insertions(+), 46 deletions(-) diff --git a/assets/scripts/dist/bundle.js b/assets/scripts/dist/bundle.js index 619a7be..f68018e 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:"generateMultipleSelectInput",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.getItems(),o=this.getOptions();this.dropdown&&!function(){e.dropdown.innerHTML="";var t=document.createDocumentFragment();if(o)o.forEach(function(e){var i=(0,u.strToEl)('
    • '+e.value+"
    • ");t.appendChild(i)});else{var i=(0,u.strToEl)('
    • No options to select
    • ');t.appendChild(i)}e.dropdown.appendChild(t)}();var s=this.getItemsReducedToValues();this.passedElement.value=s.join(this.options.delimiter),this.list.innerHTML="";var r=document.createDocumentFragment();i.forEach(function(t){if(t.active){var i=(0,u.strToEl)('
    • '+t.value+"
    • ");r.appendChild(i)}}),this.list.appendChild(r),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.generateTextInput();break;case"select-one":break;case"select-multiple":this.generateMultipleSelectInput();break;default:this.generateMultipleSelectInput()}}},{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=document.getElementById("choices-1"),t=(new d(e,{delimiter:" ",editItems:!0,maxItems:5,callbackOnRemoveItem:function(e){console.log(e)},callbackOnAddItem:function(e,t){console.log(e,t)},callbackOnRender:function(e){console.log(e)}}),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()}));t.removeAllItems();var n=new d("#choices-6",{items:["josh@joshuajohnson.co.uk","joe@bloggs.co.uk"]});new d("#choices-7",{callbackOnRender:function(e,t){console.log(e)}}),new d;n.addItem("josh2@joshuajohnson.co.uk",function(){console.log("Custom add item callback")}),n.removeItem("josh@joshuajohnson.co.uk"),console.log(n.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(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,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(13),r=i(s),a=n(14),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:"generateMultipleSelectInput",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;var r=Array.prototype.slice.call(this.passedElement.options);r.forEach(function(t){e.addOptionToDropdown(t)}),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.getItems(),o=this.getOptions();this.dropdown&&!function(){e.dropdown.innerHTML="";var t=document.createDocumentFragment();if(o)o.forEach(function(e){var i=(0,u.strToEl)('
        • '+e.value+"
        • ");t.appendChild(i)});else{var i=(0,u.strToEl)('
        • No options to select
        • ');t.appendChild(i)}e.dropdown.appendChild(t)}();var s=this.getItemsReducedToValues();this.passedElement.value=s.join(this.options.delimiter),this.list.innerHTML="";var r=document.createDocumentFragment();i.forEach(function(t){if(t.active){var i=(0,u.strToEl)('
        • '+t.value+"
        • ");r.appendChild(i)}}),this.list.appendChild(r),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.generateTextInput();break;case"select-one":break;case"select-multiple":this.generateMultipleSelectInput();break;default:this.generateMultipleSelectInput()}}},{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=document.getElementById("choices-1"),t=(new d(e,{delimiter:" ",editItems:!0,maxItems:5}),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()}));t.removeAllItems();new d("#choices-6",{items:["josh@joshuajohnson.co.uk","joe@bloggs.co.uk"]}),new d("#choices-7",{}),new d("[data-choice]",{callbackOnRender:function(e,t){console.log(e)}})})},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,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(13),r=i(s),a=n(14),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);t-1?e.map(function(e){return e.id===parseInt(t.optionId)&&(e.selected=t.selected),e}):e;default:return e}};t.default=i},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.addItem=function(e,t,n){return{type:"ADD_ITEM",value:e,id:parseInt(t),optionId:parseInt(n)}},t.removeItem=function(e,t){return{type:"REMOVE_ITEM",id:parseInt(e),optionId:parseInt(t)}},t.selectItem=function(e,t){return{type:"SELECT_ITEM",id:parseInt(e),selected:t}},t.addOption=function(e,t){return{type:"ADD_OPTION",value:e,id:parseInt(t)}},t.selectOption=function(e,t){return{type:"SELECT_OPTION",id:parseInt(e),selected:t}}},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=(t.hasClass=function(e,t){return new RegExp(" "+t+" ").test(" "+e.className+" ")},t.capitalise=function(e){return e.replace(/\w\S*/g,function(e){return e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()})},t.isType=function(e,t){var n=Object.prototype.toString.call(t).slice(8,-1);return void 0!==t&&null!==t&&n===e}),i=(t.extend=function o(){for(var e={},t=!1,i=arguments.length,s=function(i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(t&&n("Object",i[s])?e[s]=o(!0,e[s],i[s]):e[s]=i[s])},r=0;i>r;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/actions/index.js b/assets/scripts/src/actions/index.js index df35280..530d49e 100644 --- a/assets/scripts/src/actions/index.js +++ b/assets/scripts/src/actions/index.js @@ -1,22 +1,24 @@ -export const addItem = (value, id) => { +export const addItem = (value, id, optionId) => { return { type: 'ADD_ITEM', value: value, - id: id, + id: parseInt(id), + optionId: parseInt(optionId) } }; -export const removeItem = (id) => { +export const removeItem = (id, optionId) => { return { type: 'REMOVE_ITEM', - id: id, + id: parseInt(id), + optionId: parseInt(optionId) } }; export const selectItem = (id, selected) => { return { type: 'SELECT_ITEM', - id: id, + id: parseInt(id), selected: selected, } }; @@ -25,14 +27,14 @@ export const addOption = (value, id) => { return { type: 'ADD_OPTION', value: value, - id: id, + id: parseInt(id), } }; export const selectOption = (id, selected) => { return { type: 'SELECT_OPTION', - id: id, + id: parseInt(id), selected: selected, } }; \ No newline at end of file diff --git a/assets/scripts/src/choices.js b/assets/scripts/src/choices.js index 6321a34..493235d 100644 --- a/assets/scripts/src/choices.js +++ b/assets/scripts/src/choices.js @@ -278,7 +278,7 @@ export class Choices { if(!option.selected) { this.selectOption(id, true); - this.addItem(option.value); + this.addItem(option.value, option.id); } } @@ -376,7 +376,7 @@ export class Choices { }); } - selectOption(id, value) { + selectOption(id, value = true) { if(!id) return; this.store.dispatch(selectOption(id, value)); } @@ -385,7 +385,7 @@ export class Choices { * Add item to store with correct value * @param {String} value Value to add to store */ - addItem(value, callback = this.options.callbackOnAddItem) { + addItem(value, optionId = -1, callback = this.options.callbackOnAddItem) { if (this.options.debug) console.debug('Add item'); let passedValue = value; @@ -417,7 +417,7 @@ export class Choices { } } - this.store.dispatch(addItem(passedValue, id)); + this.store.dispatch(addItem(passedValue, id, optionId)); } /** @@ -432,6 +432,7 @@ export class Choices { let id = item.id; let value = item.value; + let optionId = item.optionId; // Run callback if(callback){ @@ -442,7 +443,7 @@ export class Choices { } } - this.store.dispatch(removeItem(id)); + this.store.dispatch(removeItem(id, optionId)); } /** @@ -477,11 +478,19 @@ export class Choices { this.dropdown.classList[isActive ? 'remove' : 'add']('is-active'); } - addOptionToDropdown(value) { + addOptionToDropdown(option) { // Generate unique id - let state = this.store.getState(); - let id = state.options.length + 1; + const state = this.store.getState(); + const id = state.options.length + 1; + const value = option.value; + const isSelected = option.selected; + this.store.dispatch(addOption(value, id)); + + if(isSelected) { + this.selectOption(id); + this.addItem(option.value, id); + } } /* Getters */ @@ -645,15 +654,10 @@ export class Choices { this.input = input; this.list = list; this.dropdown = dropdown; - - // Add any preset values seperated by delimiter - this.presetItems.forEach((value) => { - this.addItem(value); - }); const passedOptions = Array.prototype.slice.call(this.passedElement.options); passedOptions.forEach((option) => { - this.addOptionToDropdown(option.value); + this.addOptionToDropdown(option); }); // Subscribe to store @@ -807,15 +811,15 @@ document.addEventListener('DOMContentLoaded', () => { delimiter: ' ', editItems: true, maxItems: 5, - callbackOnRemoveItem: function(value) { - console.log(value); - }, - callbackOnAddItem: function(id, value) { - console.log(id, value); - }, - callbackOnRender: function(items) { - console.log(items); - } + // callbackOnRemoveItem: function(value) { + // console.log(value); + // }, + // callbackOnAddItem: function(id, value) { + // console.log(id, value); + // }, + // callbackOnRender: function(items) { + // console.log(items); + // } }); const choices2 = new Choices('#choices-2', { @@ -846,14 +850,18 @@ document.addEventListener('DOMContentLoaded', () => { }); const choices7 = new Choices('#choices-7', { - callbackOnRender: function(items, options) { - console.log(items); - } + // callbackOnRender: function(items, options) { + // console.log(items); + // }, }); - const choicesMultiple = new Choices(); + const choicesMultiple = new Choices('[data-choice]', { + callbackOnRender: function(items, options) { + console.log(items); + }, + }); - choices6.addItem('josh2@joshuajohnson.co.uk', () => { console.log('Custom add item callback')}); - choices6.removeItem('josh@joshuajohnson.co.uk'); - console.log(choices6.getItemById(1)); + // choices6.addItem('josh2@joshuajohnson.co.uk', () => { console.log('Custom add item callback')}); + // choices6.removeItem('josh@joshuajohnson.co.uk'); + // console.log(choices6.getItemById(1)); }); \ No newline at end of file diff --git a/assets/scripts/src/reducers/items.js b/assets/scripts/src/reducers/items.js index 95ff40a..b3b8615 100644 --- a/assets/scripts/src/reducers/items.js +++ b/assets/scripts/src/reducers/items.js @@ -3,7 +3,8 @@ const items = (state = [], action) => { case 'ADD_ITEM': // Add object to items array let newState = [...state, { - id: parseInt(action.id), + id: action.id, + optionId: action.optionId, value: action.value, active: true, selected: false @@ -19,7 +20,7 @@ const items = (state = [], action) => { case 'REMOVE_ITEM': // Set item to inactive return state.map((item) => { - if(item.id === parseInt(action.id)) { + if(item.id === action.id) { item.active = false; } return item; @@ -27,7 +28,7 @@ const items = (state = [], action) => { case 'SELECT_ITEM': return state.map((item) => { - if(item.id === parseInt(action.id)) { + if(item.id === action.id) { item.selected = action.selected; } diff --git a/assets/scripts/src/reducers/options.js b/assets/scripts/src/reducers/options.js index 044feb1..7b58020 100644 --- a/assets/scripts/src/reducers/options.js +++ b/assets/scripts/src/reducers/options.js @@ -1,15 +1,12 @@ const options = (state = [], action) => { switch (action.type) { case 'ADD_OPTION': - // Add object to items array - let newState = [...state, { + return [...state, { id: parseInt(action.id), value: action.value, disabled: false, selected: false - }]; - - return newState; + }];; case 'SELECT_OPTION': return state.map((option) => { @@ -20,6 +17,21 @@ 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; + }); + } else { + return state; + } + + default: return state; }