UNPKG

uicore-web

Version:

web ui core

525 lines (512 loc) 18.1 kB
import pako from 'pako'; const core= { isDebug: false, debug() { let time = new Date().format('[yyyy-MM-dd HH:mm:ss,SSS]'); let methods = ['log', 'error', 'info', 'warn']; for (let i in methods) { //因控制台本身打印可以定位代码位置,所以我们要应bind来告诉调用的方法,本身就是控制台的实现,以去掉因多个方法造成的调用堆栈深度而引发的代码位置错误问题 this[methods[i]] = (this.isDebug && console[methods[i]]) ? console[methods[i]].bind(console, time) : function () { }; } methods = ['time', 'timeEnd']; for (let i in methods) { //因控制台本身打印可以定位代码位置,所以我们要应bind来告诉调用的方法,本身就是控制台的实现,以去掉因多个方法造成的调用堆栈深度而引发的代码位置错误问题 this[methods[i]] = (this.isDebug && console[methods[i]]) ? console[methods[i]].bind(console) : function () { }; } return this; }, /** * 适配数据 * @param source 原始数据 */ adapterData(source){ if(typeof source=="string"){ try{ //return JSON.parse(source);//需要字段名也必须引号 return eval("("+source+")"); //支持字段不带引号 }catch (e) { return source; } } return source; }, /** * 判断一个变量是否为数组 * @param obj 需要判断的变量 * @returns 是否是一个数组 */ isArray(obj) { let str = Object.prototype.toString.call(obj); return str === '[object Array]' || str === '[object Array Iterator]'; }, /** * 判断一个变量是否为对象,但不是数组 * @param obj 需要判断的变量 * @param strict 是否需要判断其是不是数组,如果为false,则不判断,如果为true,则需要判断 * @returns 是否是一个对象 */ isObject(obj, strict) { return obj && typeof obj === 'object' && (!strict || !this.isArray(obj)); }, /** * 抄自highcharts,用于融合对象 * @returns 融合后的对象 */ merge() { let i, args = arguments, len, ret = {}; if (args[0] === true) { ret = args[1]; args = Array.prototype.slice.call(args, 2); } len = args.length; for (i = 0; i < len; i++) { if(args[i]!=null)//修正当为null时,跳过该对象 ret = this.doCopy(ret, args[i]); } return ret; }, /** * 扩展 * extend(ret,defaults,options...) * @returns {any} */ extend() { let args = arguments; let ret = args[0]; args = Array.prototype.slice.call(args, 1); let len = args.length; for (let i = 0; i < len; i++) { if(args[i]!=null)//修正当为null时,跳过该对象 ret = this.doCopy(ret, args[i], false); } return ret; }, /** * 融合对象,目前因为无法明确数组的融合模式,数组暂时使用对象引用模式进行融合,如果需要处理争议,请勿在参与的original包含数组 * @param copy * @param original * @param isMerge * @returns {{}} */ doCopy(copy, original, isMerge) { let value, key; if (typeof copy !== 'object') { copy = {}; } if(typeof original=="string"){ copy = original; }else { for (key in original) { if (Object.prototype.hasOwnProperty.call(original, key)) { value = original[key]; if (this.isObject(value, true) && typeof value.nodeType !== 'number' && isMerge !== false) { copy[key] = this.doCopy(copy[key] || {}, value); // }else if(this.isArray(value)){ // copy[key]=new Array();//数组采用替代式,如果需要联结2个数组,自己用concat另外实现 // for(let i=0;i<value.length;i++){ // // } } else { copy[key] = original[key]; } } } if (key == null && original != null && original.test) {//正则表达式支持 copy = original; } } return copy; },gzip(base64Data) { let strData = atob(base64Data); let charData = strData.split('').map(function (x) { return x.charCodeAt(0); }); let binData = new Uint8Array(charData); let data = pako.inflate(binData); let res = ''; let chunk = 8 * 1024; let i; for (i = 0; i < data.length / chunk; i++) { res += String.fromCharCode.apply(null, data.slice(i * chunk, (i + 1) * chunk)); } res += String.fromCharCode.apply(null, data.slice(i * chunk)); return decodeURIComponent(escape(res)); },decodeData(res, keymap, mappingNoKey) { let result=this.merge(res);//克隆数据副本 if (res.data) { //进行自解密支持 if (typeof res.data == "string") { let data = this.gzip(res.data); result.data = JSON.parse(data); }else{ result.data=res.data; } } if (keymap && res.map && result.data) { let datas = []; for (let i = 0; i < result.data.length; i++) { let item = {}; for (let j = 0; j < res.map.length; j++) { let key = res.map[j]; let name = keymap[key]; if (name) { item[name] = result.data[i][j]; } else { if (mappingNoKey !== false) { //如果配置了,没有匹配到key,则按原字段映射支持,则使用此逻辑 item[key] = result.data[i][j]; } } } datas.push(item); } result.data = datas; delete result.map; } return result; },replaceQueryString: function (url, options, isOnlyQueryString, isNoDecoding) { let params = this.getParams(url); let setting = this.extend({}, params, options, {_: new Date().getTime()});//如果不是ajax提交时,调用此函数也支持动态时间参数 let queryString = this.ObjectSerialize(setting, isNoDecoding); if (isOnlyQueryString) { return queryString; } let address = this.getPageAddress(url); if (queryString) return address + "?" + queryString; return address; },getParams: function (url) { return this.parseQueryString(this.getQueryString(url)); }, ObjectSerialize: function (obj, isNoDecoding) { let result = ""; let index = 0; for (let pro in obj) { if (index != 0) result += "&"; index++; if (obj[pro] != null) { result += pro + "=" + (isNoDecoding ? obj[pro] : encodeURIComponent(obj[pro])); } else { result += pro + "="; } } return result; },parseQueryString: function (queryString) { let result = {}; if (queryString) { let paramAndValues = queryString.split("&"); for (let i = 0; i < paramAndValues.length; i++) { let paramAndValue = paramAndValues[i]; let temp = paramAndValue.split("="); if (temp[0] != "") { let data = temp[1]; try { data = decodeURIComponent(temp[1]); } catch (e) { this.debug().error(e); } if (data === "false") data = false; if (data === "true") data = true; result[temp[0]] = data; } } // if (result.token) // delete result.token; } return result; }, getQueryString: function (url) { if (url == null) url = location.href; if (url.indexOf('?') >= 0) return url.substring(url.indexOf('?') + 1); return ""; }, getPageAddress: function (url) { if (url == null) url = location.href; if (url.indexOf('?') >= 0) return url.substring(0, url.indexOf('?')); return url; },transform2TreeData(items = [],rootId=0,supportHalfCheck=true, idKey = "id", pidKey = "pid",checkedKey="checked") { let itemCache = {}; let unFindCache={};//如果没有找到父亲,则临时存储在这边 let result = []; let findedChecked=false; items.map((item) => { this.transform2TreeItem(item, itemCache,unFindCache, result,rootId, idKey, pidKey); if(!findedChecked&&item[checkedKey]===true){ findedChecked=true; } }) itemCache = {}; //全部执行完毕后,如果仍没有认领,则自己产生族谱 for(let key in unFindCache){ result= result.concat(unFindCache[key]); delete unFindCache[key];//清理内存 } this.debug().log("选择恢复===》") if(supportHalfCheck) {//当需要半选即选中,才需要此逻辑 if (findedChecked) {//因为element ui 并不支持这样的数据整理,所以,需要我们自己的重构数据逻辑,否则改动太大 for (let index in result) { this.checkParentStatus(result[index]); } } } return result; }, transform2TreeItem(item, cache,unFindCache, result, rootId,idKey = "id", pidKey = "pid") { //检查是否保存没有被认领的儿子 if(unFindCache[item[idKey]]!=null){//执行认领逻辑 item.children=unFindCache[item[idKey]]; delete unFindCache[item[idKey]];//认领完成后,从缓存删除 } //自己不是根,则找父亲 if (cache[item[pidKey]]!=null) {//如果从树上找到了pid let parent = cache[item[pidKey]]; if (parent.children == null) parent.children = []; parent.children.push(item); } else {//如果没有找到父亲时,数据处于无序模式时 let pid=item[pidKey]; if(pid==rootId){ result.push(item); }else{ if(unFindCache[pid]==null) unFindCache[pid]=[]; unFindCache[pid].push(item); } } cache[item[idKey]] = item; return result; },checkParentStatus(item){ if(item.children&&item.children.length){ for(let i in item.children){//先检查子节点,再调整自己的数据 this.checkParentStatus(item.children[i]); } if(item.checked){//自己如果是选中状态,需要根据子阶段来处理 let notCheckedItem=item.children.find((child)=>{ if(!child.checked) return true; }); if(notCheckedItem!=null) delete item.checked; } } },isExternal(path) { return /^(http(s)?:|mailto:|tel:)/.test(path) },adapterBaseUrl(url,protocol){ return (protocol||window.location.protocol)+"//"+url.replace(/^(http(s)?)?:[//][//]/,""); },resameUrl(baseUrl,content="",blank){ let result= content.replace(/src="(?!((data:)|(http(s)?:[/][/])))/g,'src="'+baseUrl+"/") .replace(/href="(?!http(s)?:[/][/])/g,'href="'+baseUrl+"/"); if(blank) result=result.replace(/<a /g,'<a target="_blank" '); //增加全局弹窗支持 return result; },adapterType(item) { if(item.style) { if (item.style.indexOf("primary") >= 0) return "primary"; if (item.style.indexOf("success") >= 0) return "success"; if (item.style.indexOf("danger") >= 0) return "danger" if (item.style.indexOf("warning") >= 0) return "warning"; } switch (item.type) { case "print": case "link": return "success"; //使用绿色按钮主题 case "close": return "danger"; //使用红色按钮主题 default: return "primary"; //使用蓝色按钮主题 } } } Array.FindDataIndex = function (array, data, property) { switch (typeof data) { case "object": for (let i = 0; i < array.length; i++) { let isSame = false; if (property) { if (array[i][property] == data[property]) { isSame = true; } } else { for (let pro in data) { if (array[i][pro] != data[pro]) { isSame = false; break; } else { isSame = true; } } } if (isSame) return i; } return -1; case "array": return -1; default: return Array.indexOf(array, data); } } Date.prototype.format = function (fmt,timezone) { //author: meizz if(timezone) { let timezoneOffset = /[+-]\d+/.exec(timezone)*(-60); this.addMinutes(this.getTimezoneOffset()-timezoneOffset); } let o = { 'M+': this.getMonth() + 1, //月份 'd+': this.getDate(), //日 'D+': this.getDay(), //星期几 // 'h+': (this.getHours()/12>1)?'下午 ':'上午 '+ this.getHours()%12, //小时 'H+': this.getHours(), //24小时 'm+': this.getMinutes(), //分 's+': this.getSeconds(), //秒 'q+': Math.floor((this.getMonth() + 3) / 3), //季度 'S+': this.getMilliseconds(), //毫秒 'Z+': timezone||'UTC'+(this.getTimezoneOffset()<=0?'+':'')+this.getTimezoneOffset()/(-60) //时区 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length)); for (let k in o) if (new RegExp('(' + k + ')').test(fmt)) { let temp = '00' + o[k]; fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : temp.substr(temp.length - RegExp.$1.length)); } return fmt; } Date.PerSecondTick = 1000; Date.PerMinuteTick = Date.PerSecondTick * 60; Date.PerHourTick = Date.PerMinuteTick * 60; Date.PerDayTick = Date.PerHourTick * 24; Date.prototype.addSeconds = function (second) { if (second != 0) this.setTime(this.getTime() + second * Date.PerSecondTick); return this; } Date.prototype.addMinutes = function (minute) { if (minute != 0) this.setTime(this.getTime() + minute * Date.PerMinuteTick); return this; } Date.prototype.addHours = function (hour) { if (hour != 0) this.setTime(this.getTime() + hour * Date.PerHourTick); return this; } Date.prototype.addDays = function (day) { if (day != 0) this.setTime(this.getTime() + day * Date.PerDayTick); return this; } Date.prototype.addMonths = function (month) { if (month != 0) { let m = this.getMonth() + month; let y = parseInt(m / 12); this.addYears(y); this.setMonth(m % 12); } return this; } Date.prototype.addYears = function (year) { if (year != 0) this.setYear(this.getFullYear() + year); return this; } /** * 格式化字符串 * @param data 需要被格式化的数据,可以是Object对象也可以是数组,如果是object对象,格式化字符串的格式为 {属性名称},如果是数组或多个参数,则格式化字符串为 {0} {1} */ String.prototype.urlFormat = function (data,withoutEncoding=false,nofindedempty=true) { if (/\{(\w+)\}/.test(this)) { let args = arguments; if (typeof args[0] == 'object' || typeof args[0] == 'function')//对对象和数组进行支持 args = args[0]; if (args == null) args = {}; return this.replace(/\{(\w+)\}/ig, function (m, i) { let result = args[i]; if (result == null) { if (typeof i == 'string') //尝试适配小写 result = args[i.toLowerCase()]; if (!nofindedempty) { result = '{' + i + '}'; return result; } }//如果出现大小写问题,一律支持小写 if (result != null && !withoutEncoding) result = encodeURI(decodeURI(result));//对url进行编码和解码的支持 if (result == null) { if (!nofindedempty) result = '{' + i + '}'; else result = ''; } return result; }); }else{ return this; } }; /** * base64+gzip格式的数据进行解密 * @returns {string} */ String.prototype.gzip=function() { return core.gzip(this); } /** * 格式化字符串 * @param data 需要被格式化的数据,可以是Object对象也可以是数组,如果是object对象,格式化字符串的格式为 {属性名称},如果是数组或多个参数,则格式化字符串为 {0} {1} */ String.prototype.format = function (data,nofindedempty) { let args = arguments; if (typeof args[0] == 'object'||typeof args[0] == 'function')//对对象和数组进行支持 args = args[0]; return this.replace(/\{(\w+)\}/ig, function (m, i) { let result = args[i]; if (result == null && typeof i == 'string')//如果出现大小写问题,一律支持小写 result = args[i.toLowerCase()]; if (result == null || result == 'undefined') { if(nofindedempty) //如果找不到数据,则为空 result = ''; else result = '{' + i + '}'; } return result; }); }; if (!String.prototype.trim) String.prototype.trim = function () { return this.replace(/^\s+|\s+$/gm, ''); }; /** * 格式化字符串 * @param str 格式化字符串 * @param data 需要被格式化的数据,可以是Object对象也可以是数组,如果是object对象,格式化字符串的格式为 {属性名称},如果是数组或多个参数,则格式化字符串为 {0} {1} * @returns {*|String|Boolean} 格式化结果 */ String.Format = function (str) { let args = arguments; if (typeof str == 'string') { if (typeof args[1] == 'object') {//如果是对象,则直接按属性进行处理 return str.format(args[1]); } else { let data = Array.prototype.slice.call(args, 1); return String.prototype.format.call(str, data); // format.foramt(data);// args.slice(1)); 不能直接调这个 } } else { throw Error('字符串格式化第一个参数是待格式化的格式内容'); } }; export default core;