mobile-select
Version:
A multi-function mobile phone scrolling selector, support single to multi-select, support multi-level cascade, provide custom callback function, provide update function redraw, relocation function, compatible pc drag and so on.
7 lines • 20.5 kB
JavaScript
/*
* mobile-select v1.4.0
* Homepage: https://github.com/onlyhom/mobile-select
* Released under the MIT License.
* (c) 2017-present
*/
"use strict";function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function _toConsumableArray(arr){return _arrayWithoutHoles(arr)||_iterableToArray(arr)||_unsupportedIterableToArray(arr)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArray(iter){if("undefined"!=typeof Symbol&&null!=iter[Symbol.iterator]||null!=iter["@@iterator"])return Array.from(iter)}function _arrayWithoutHoles(arr){if(Array.isArray(arr))return _arrayLikeToArray(arr)}function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(o,minLen){if(o){if("string"==typeof o)return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);return"Map"===(n="Object"===n&&o.constructor?o.constructor.name:n)||"Set"===n?Array.from(o):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(o,minLen):void 0}}function _arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function _iterableToArrayLimit(arr,i){var _i=null==arr?null:"undefined"!=typeof Symbol&&arr[Symbol.iterator]||arr["@@iterator"];if(null!=_i){var _s,_e,_arr=[],_n=!0,_d=!1;try{for(_i=_i.call(arr);!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{_n||null==_i.return||_i.return()}finally{if(_d)throw _e}}return _arr}}function _arrayWithHoles(arr){if(Array.isArray(arr))return arr}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){return protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Object.defineProperty(Constructor,"prototype",{writable:!1}),Constructor}function _typeof(obj){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj})(obj)}var MobileSelect=function(){function h(g,c,l){D(g,"symbol"!=_typeof(c)?c+"":c,l)}var S=Object.defineProperty,D=function(g,c,l){return c in g?S(g,c,{enumerable:!0,configurable:!0,writable:!0,value:l}):g[c]=l};var c=function(){function l(t){_classCallCheck(this,l),h(this,"mobileSelect"),h(this,"trigger"),h(this,"wheelList"),h(this,"sliderList"),h(this,"wheelsContain"),h(this,"panel"),h(this,"ensureBtn"),h(this,"cancelBtn"),h(this,"grayLayer"),h(this,"popUp"),h(this,"initPosition"),h(this,"initColWidth"),h(this,"wheelsData"),h(this,"displayJson"),h(this,"curValue"),h(this,"curIndexArr"),h(this,"isCascade"),h(this,"isJsonType"),h(this,"startY"),h(this,"moveEndY"),h(this,"moveY"),h(this,"preMoveY"),h(this,"offsetY"),h(this,"offsetSum"),h(this,"oversizeBorder"),h(this,"enableClickStatus"),h(this,"optionHeight"),h(this,"curDistance"),h(this,"cascadeJsonData"),h(this,"eventHandleMap"),h(this,"initDeepCount"),h(this,"config"),l.checkRequiredConfig(t)&&(this.config=Object.assign({},l.defaultConfig,t),this.wheelsData=t.wheels,this.isJsonType=!1,this.cascadeJsonData=[],this.displayJson=[],this.curValue=[],this.curIndexArr=[],this.isCascade=!1,this.startY,this.moveEndY,this.moveY,this.preMoveY,this.offsetY=0,this.offsetSum=0,this.oversizeBorder,this.curDistance=[],this.enableClickStatus=!1,this.optionHeight=0,this.initPosition=t.position||[],this.initColWidth=t.colWidth||[],this.init())}return _createClass(l,[{key:"init",value:function(){var _this=this;if(this.checkTriggerAvailable()){var t=this.config;if(this.isJsonType=l.checkDataType(this.wheelsData),this.renderComponent(this.wheelsData),this.wheelList=this.mobileSelect.getElementsByClassName("ms-wheel"),this.sliderList=this.mobileSelect.getElementsByClassName("ms-select-container"),this.panel=this.mobileSelect.querySelector(".ms-panel"),this.wheelsContain=this.mobileSelect.querySelector(".ms-wheels"),this.ensureBtn=this.mobileSelect.querySelector(".ms-ensure"),this.cancelBtn=this.mobileSelect.querySelector(".ms-cancel"),this.grayLayer=this.mobileSelect.querySelector(".ms-gray-layer"),this.popUp=this.mobileSelect.querySelector(".ms-content"),this.optionHeight=this.mobileSelect.querySelector("li").offsetHeight,t.initValue&&this.setTriggerInnerText(t.initValue),this.setStyle(t),this.isCascade=this.checkCascade(),this.isCascade&&this.initCascade(),t.initValue&&(this.initPosition=this.getPositionByInitValue()),this.initPosition.length<this.sliderList.length)for(var e=this.sliderList.length-this.initPosition.length,i=0;i<e;i++)this.initPosition.push(0);this.isCascade?this.initPosition.forEach(function(e,i){_this.checkRange(i,_this.initPosition)}):this.setCurDistance(this.initPosition),this.eventHandleMap={cancelBtn:{event:"click",fn:function(){var i,e;_this.hide(),null!=(i=(e=_this.config).cancel)&&i.call(e,_this.curIndexArr,_this.curValue,_this),null!=(e=(i=_this.config).onCancel)&&e.call(i,_this.curValue,_this.curIndexArr,_this)}},ensureBtn:{event:"click",fn:function(){var i,e;_this.hide(),_this.optionHeight||(_this.optionHeight=_this.mobileSelect.querySelector("li").offsetHeight),_this.setTriggerInnerText(_this.getConnectedString()),_this.curIndexArr=_this.getIndexArr(),_this.curValue=_this.getCurValue(),null!=(i=(e=_this.config).callback)&&i.call(e,_this.curIndexArr,_this.curValue,_this),null!=(e=(i=_this.config).onChange)&&e.call(i,_this.curValue,_this.curIndexArr,_this)}},trigger:{event:"click",fn:function(){_this.show()}},grayLayer:{event:"click",fn:function(){return _this.hide()}},popUp:{event:"click",fn:function(e){return e.stopPropagation()}},panel:{event:["touchstart","touchend","touchmove"],fn:function(e){return _this.touch(e)}}},navigator.userAgent.toLowerCase().match(/ipad|iphone os|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/)||(this.eventHandleMap.panel.event=["mousedown","mousemove","mouseup"]),this.registerEvents("add"),this.fixRowStyle(),t.autoFocus&&this.show()}}},{key:"checkTriggerAvailable",value:function(){var t=this.config;return this.trigger=t.trigger instanceof HTMLElement?t.trigger:document.querySelector(t.trigger),!!this.trigger||(l.log("error","trigger HTMLElement does not found on your document."),!1)}},{key:"getPositionByInitValue",value:function(){var o,_this2=this,_this$config=this.config,t=_this$config.keyMap,e=_this$config.connector,_this$config=_this$config.initValue,_this$config=(null==_this$config?void 0:_this$config.split(e))||[];return this.isJsonType?(o=null==(e=this.wheelsData[0])?void 0:e.data,_this$config.reduce(function(r,a){var u=null==o?void 0:o.findIndex(function(f){return f[t.value]==a});return r.push(u<0?0:u),o=null==(u=o[u])?void 0:u[t.childs],r},[])):_this$config.reduce(function(o,r,a){a=null==(a=null==(a=_this2.wheelsData[a])?void 0:a.data)?void 0:a.findIndex(function(m){return m==r});return o.push(a<0?0:a),o},[])}},{key:"getConnectedString",value:function(){for(var t="",e=0;e<this.wheelList.length;e++)e==this.wheelList.length-1?t+=this.getInnerText(e):t+=this.getInnerText(e)+this.config.connector;return t}},{key:"setTriggerInnerText",value:function(t){this.config.triggerDisplayValue&&(this.trigger.textContent=t)}},{key:"setValue",value:function(t){var e,_this3=this;t&&t.length&&(this.isJsonType&&"object"!=_typeof(t[0])||!this.isJsonType&&"object"==_typeof(t[0])?l.log("error","The setValue() input format should be same with getValue(), like: ".concat(JSON.stringify(this.getValue()))):(e=this.config.keyMap,t.forEach(function(i,s){var r=_this3.isCascade?_this3.displayJson[s]:null==(r=_this3.wheelsData[s])?void 0:r.data,r=null==r?void 0:r.findIndex(function(a){return _this3.isJsonType?i[e.id]==a[e.id]||i[e.value]==a[e.value]:i==a});_this3.locatePosition(s,r)}),this.setTriggerInnerText(this.getConnectedString())))}},{key:"setTitle",value:function(t){this.mobileSelect.querySelector(".ms-title").innerHTML=t}},{key:"setStyle",value:function(t){var _e2;t.ensureBtnColor&&(this.ensureBtn.style.color=t.ensureBtnColor),t.cancelBtnColor&&(this.cancelBtn.style.color=t.cancelBtnColor),t.titleColor&&(this.mobileSelect.querySelector(".ms-title").style.color=t.titleColor),t.textColor&&(this.panel=this.mobileSelect.querySelector(".ms-panel"),this.panel.style.color=t.textColor),t.titleBgColor&&(this.mobileSelect.querySelector(".ms-btn-bar").style.backgroundColor=t.titleBgColor),t.bgColor&&(this.panel=this.mobileSelect.querySelector(".ms-panel"),_e2=this.mobileSelect.querySelector(".ms-shadow-mask"),this.panel.style.backgroundColor=t.bgColor,_e2.style.background="linear-gradient(to bottom, "+t.bgColor+", rgba(255, 255, 255, 0), "+t.bgColor+")"),"number"==typeof t.maskOpacity&&(this.mobileSelect.querySelector(".ms-gray-layer").style.background="rgba(0, 0, 0, "+t.maskOpacity+")")}},{key:"show",value:function(){var t,i;this.mobileSelect.classList.add("ms-show"),null!=(t=document.querySelector("body"))&&t.classList.add("ms-show"),"function"==typeof this.config.onShow&&null!=(i=(t=this.config).onShow)&&i.call(t,this.curValue,this.curIndexArr,this)}},{key:"hide",value:function(){var t,i;this.mobileSelect.classList.remove("ms-show"),null!=(t=document.querySelector("body"))&&t.classList.remove("ms-show"),"function"==typeof this.config.onHide&&null!=(i=(t=this.config).onHide)&&i.call(t,this.curValue,this.curIndexArr,this)}},{key:"registerEvents",value:function(t){for(var _this4=this,_i=0,_Object$entries=Object.entries(this.eventHandleMap);_i<_Object$entries.length;_i++)!function(){var _Object$entries$_i=_slicedToArray(_Object$entries[_i],2),e=_Object$entries$_i[0],i=_Object$entries$_i[1];"string"==typeof i.event?_this4[e]["".concat(t,"EventListener")](i.event,i.fn,{passive:!1}):i.event.forEach(function(s){_this4[e]["".concat(t,"EventListener")](s,i.fn,{passive:!1})})}()}},{key:"destroy",value:function(){var t;this.registerEvents("remove"),null!=(t=null==(t=this.mobileSelect)?void 0:t.parentNode)&&t.removeChild(this.mobileSelect)}},{key:"getOptionsHtmlStr",value:function(t){var e=this.config.keyMap,i="";if(this.isJsonType)for(var s=0;s<t.length;s++){var n=t[s][e.id],o=t[s][e.value];i+='<li data-id="'.concat(n,'">').concat(o,"</li>")}else for(var _s2=0;_s2<t.length;_s2++)i+="<li>"+t[_s2]+"</li>";return i}},{key:"renderComponent",value:function(t){this.mobileSelect=document.createElement("div"),this.mobileSelect.className="ms-mobile-select",this.mobileSelect.innerHTML='<div class="ms-gray-layer"></div>\n <div class="ms-content">\n <div class="ms-btn-bar">\n <div class="ms-fix-width">\n <div class="ms-cancel">'.concat(this.config.cancelBtnText,'</div> \n <div class="ms-title">').concat(this.config.title||"",'</div>\n <div class="ms-ensure">').concat(this.config.ensureBtnText,'</div>\n </div>\n </div>\n <div class="ms-panel">\n <div class="ms-fix-width">\n <div class="ms-wheels"></div>\n <div class="ms-select-line"></div>\n <div class="ms-shadow-mask"></div>\n </div>\n </div>'),document.body.appendChild(this.mobileSelect);for(var e="",i=0;i<t.length;i++)e=(e+='<div class="ms-wheel" data-index="'.concat(i,'"><ul class="ms-select-container">'))+this.getOptionsHtmlStr(t[i].data)+"</ul></div>";this.mobileSelect.querySelector(".ms-wheels").innerHTML=e}},{key:"reRenderWheels",value:function(){var t=this.wheelList.length-this.displayJson.length;if(0<t)for(var e=0;e<t;e++)this.wheelsContain.removeChild(this.wheelList[this.wheelList.length-1]);for(var i,_e4=0;_e4<this.displayJson.length;_e4++)this.wheelList[_e4]?this.sliderList[_e4].innerHTML=this.getOptionsHtmlStr(this.displayJson[_e4]):((i=document.createElement("div")).className="ms-wheel",i.innerHTML='<ul class="ms-select-container">'.concat(this.getOptionsHtmlStr(this.displayJson[_e4]),"</ul>"),i.setAttribute("data-index",_e4.toString()),this.wheelsContain.appendChild(i))}},{key:"checkCascade",value:function(){var e,t=this.config.keyMap;if(this.isJsonType)for(var i=this.wheelsData[0].data,s=0;s<i.length;s++)if(t.childs in i[s]&&0<(null==(e=i[s][t.childs])?void 0:e.length))return this.cascadeJsonData=this.wheelsData[0].data,!0;return!1}},{key:"initCascade",value:function(){this.displayJson.push(this.cascadeJsonData),0<this.initPosition.length?(this.initDeepCount=0,this.initCheckArrDeep(this.cascadeJsonData[this.initPosition[0]])):this.checkArrDeep(this.cascadeJsonData[0]),this.reRenderWheels()}},{key:"initCheckArrDeep",value:function(t){var e,i;t&&(e=this.config.keyMap).childs in t&&0<t[e.childs].length&&(this.displayJson.push(t[e.childs]),this.initDeepCount++,(i=t[e.childs][this.initPosition[this.initDeepCount]])?this.initCheckArrDeep(i):this.checkArrDeep(t[e.childs][0]))}},{key:"checkArrDeep",value:function(t){var e;!t||(e=this.config.keyMap).childs in t&&0<t[e.childs].length&&(this.displayJson.push(t[e.childs]),this.checkArrDeep(t[e.childs][0]))}},{key:"checkRange",value:function(t,e){for(var o,n,i=this.displayJson.length-1-t,s=this.config.keyMap,r=0;r<i;r++)this.displayJson.pop();for(var _r=0;_r<=t;_r++)n=0==_r?this.cascadeJsonData[e[0]]:null==(o=null==n?void 0:n[s.childs])?void 0:o[e[_r]];this.checkArrDeep(n),this.reRenderWheels(),this.fixRowStyle(),this.setCurDistance(this.resetPosition(t,e))}},{key:"resetPosition",value:function(t,e){var i=_toConsumableArray(e);if(this.sliderList.length>e.length)for(var s=this.sliderList.length-e.length,n=0;n<s;n++)i.push(0);else if(this.sliderList.length<e.length){s=e.length-this.sliderList.length;for(var _n2=0;_n2<s;_n2++)i.pop()}for(var _n3=t+1;_n3<i.length;_n3++)i[_n3]=0;return i}},{key:"updateWheels",value:function(t){if(this.isCascade){if(this.cascadeJsonData=t,this.displayJson=[],this.initCascade(),this.initPosition.length<this.sliderList.length)for(var e=this.sliderList.length-this.initPosition.length,i=0;i<e;i++)this.initPosition.push(0);this.setCurDistance(this.initPosition),this.fixRowStyle()}}},{key:"updateWheel",value:function(t,e){var i;this.isCascade?l.log("error","'updateWheel()' not support cascade json data, please use 'updateWheels()' instead to update the whole data source"):(i="",i+=this.getOptionsHtmlStr(e),this.wheelsData[t]=this.isJsonType?{data:e}:e,this.sliderList[t].innerHTML=i)}},{key:"fixRowStyle",value:function(){var e,_this5=this;if(this.initColWidth.length&&this.initColWidth.length===this.wheelList.length)e=this.initColWidth.reduce(function(i,s){return i+s},0),this.initColWidth.forEach(function(i,s){_this5.wheelList[s].style.width=(i/e*100).toFixed(2)+"%"});else for(var t=(100/this.wheelList.length).toFixed(2),_e5=0;_e5<this.wheelList.length;_e5++)this.wheelList[_e5].style.width=t+"%"}},{key:"getIndex",value:function(t){return Math.round((2*this.optionHeight-t)/this.optionHeight)}},{key:"getIndexArr",value:function(){for(var t=[],e=0;e<this.curDistance.length;e++)t.push(this.getIndex(this.curDistance[e]));return t}},{key:"getCurValue",value:function(){var t=[],e=this.getIndexArr(),i=this.config.keyMap;if(this.isCascade)for(var s=0;s<this.wheelList.length;s++){var _t$push,n=this.displayJson[s][e[s]];n&&t.push((_defineProperty(_t$push={},i.id,n[i.id]),_defineProperty(_t$push,i.value,n[i.value]),_t$push))}else if(this.isJsonType)for(var _s3=0;_s3<this.curDistance.length;_s3++)t.push(this.wheelsData[_s3].data[this.getIndex(this.curDistance[_s3])]);else for(var _s4=0;_s4<this.curDistance.length;_s4++)t.push(this.getInnerText(_s4));return t}},{key:"getValue",value:function(){return this.getCurValue()}},{key:"calcDistance",value:function(t){return 2*this.optionHeight-t*this.optionHeight}},{key:"setCurDistance",value:function(t){for(var e=[],i=0;i<this.sliderList.length;i++)e.push(this.calcDistance(t[i])),this.movePosition(this.sliderList[i],e[i]);this.curDistance=e}},{key:"fixPosition",value:function(t){return-(this.getIndex(t)-2)*this.optionHeight}},{key:"movePosition",value:function(t,e){t.style.transform="translate3d(0,"+e+"px, 0)"}},{key:"locatePosition",value:function(t,e){void 0===t||void 0===e||e<0||(this.curDistance[t]=this.calcDistance(e),this.movePosition(this.sliderList[t],this.curDistance[t]),this.isCascade&&this.checkRange(t,this.getIndexArr()))}},{key:"updateCurDistance",value:function(t,e){this.curDistance[e]=parseInt(t.style.transform.split(",")[1])}},{key:"getInnerText",value:function(t){var e=this.sliderList[t].getElementsByTagName("li").length,i=this.getIndex(this.curDistance[t]);return e<=i?i=e-1:i<0&&(i=0),(null==(e=this.sliderList[t].getElementsByTagName("li")[i])?void 0:e.textContent)||""}},{key:"touch",value:function(t){var r,i=(t.composedPath&&t.composedPath()).find(function(p){return null==(p=p.classList)?void 0:p.contains("ms-wheel")});if(i){var p,s=i.firstChild,n=parseInt(i.getAttribute("data-index")||"0");switch(t.type){case"touchstart":case"mousedown":s.style.transition="none 0s ease-out",this.startY=Math.floor((t instanceof TouchEvent?t.touches[0]:t).clientY),this.preMoveY=this.startY,"mousedown"===t.type&&(this.enableClickStatus=!0);break;case"touchmove":case"mousemove":if(t.preventDefault(),"mousemove"===t.type&&!this.enableClickStatus)break;this.moveY=Math.floor((t instanceof TouchEvent?t.touches[0]:t).clientY),this.offsetY=(this.moveY-this.preMoveY)*this.config.scrollSpeed,this.updateCurDistance(s,n),this.curDistance[n]=this.curDistance[n]+this.offsetY,this.movePosition(s,this.curDistance[n]),this.preMoveY=this.moveY;break;case"touchend":case"mouseup":s.style.transition="transform 0.18s ease-out",this.moveEndY=Math.floor((t instanceof TouchEvent?t.changedTouches[0]:t).clientY),this.offsetSum=this.moveEndY-this.startY,this.oversizeBorder=-(s.getElementsByTagName("li").length-3)*this.optionHeight,0==this.offsetSum?2!=(p=Math.floor((window.innerHeight-this.moveEndY)/40))&&(p=this.curDistance[n]+(p-2)*this.optionHeight)<=2*this.optionHeight&&p>=this.oversizeBorder&&(this.curDistance[n]=p,this.movePosition(s,this.curDistance[n]),null!=(r=(p=this.config).transitionEnd)&&r.call(p,this.getIndexArr(),this.getCurValue(),this),null!=(p=(r=this.config).onTransitionEnd)&&p.call(r,this.getCurValue(),this.getIndexArr(),this)):(this.updateCurDistance(s,n),this.curDistance[n]=this.fixPosition(this.curDistance[n]),this.curDistance[n]>2*this.optionHeight?this.curDistance[n]=2*this.optionHeight:this.curDistance[n]<this.oversizeBorder&&(this.curDistance[n]=this.oversizeBorder),this.movePosition(s,this.curDistance[n]),null!=(r=(p=this.config).transitionEnd)&&r.call(p,this.getIndexArr(),this.getCurValue(),this),null!=(p=(r=this.config).onTransitionEnd)&&p.call(r,this.getCurValue(),this.getIndexArr(),this)),"mouseup"===t.type&&(this.enableClickStatus=!1),this.isCascade&&this.checkRange(n,this.getIndexArr())}}}}],[{key:"checkDataType",value:function(t){return"object"==_typeof(null==(t=null==(t=t[0])?void 0:t.data)?void 0:t[0])}},{key:"checkRequiredConfig",value:function(t){var i,e=l.REQUIRED_PARAMS;if(!t)return i=e.map(function(s){return"'".concat(s,"'")}),l.log("error","missing required param ".concat(i.join(" and "),".")),!1;for(var _i2=0;_i2<e.length;_i2++){var s=e[_i2];if(!t[s])return l.log("error","missing required param '".concat(s,"'.")),!1}return!0}},{key:"log",value:function(t,e){null!=(t=console[t])&&t.call(console,"[mobile-select]: ".concat(e))}}]),l}();return h(c,"defaultConfig",{keyMap:{id:"id",value:"value",childs:"childs"},position:[],colWidth:[],title:"",connector:" ",ensureBtnText:"确认",cancelBtnText:"取消",triggerDisplayValue:!0,scrollSpeed:1}),h(c,"REQUIRED_PARAMS",["trigger","wheels"]),c}();