@wxhccc/es-util 1.7.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.7.0
2
+ * @wxhccc/es-util v2.0.2
3
3
  * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
6
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Smartfetch={})}(this,(function(e){"use strict";const{hasOwnProperty:t}=Object.prototype;function n(e,t=[]){return{[e]:t}}const r=/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i;const o=e=>"[object Object]"===Object.prototype.toString.call(e);const i={telphone:{startCharIndex:-8,endCharIndex:-5},idcard:{startCharIndex:-12,endCharIndex:-5}};const{hasOwnProperty:s,toString:c}=Object.prototype,a=e=>{const t=c.call(e).match(/^\[object (.*)\]$/);return t?t[1]:""};async function l(e){try{return[null,await e]}catch(e){return[e,void 0]}}const u={};function f(e,t){const n=function(e){return e?e._isVue||e.$&&e.$.vnode?"vue":"setState"in e?"react":"unknown":"unknown"}(this),r="unknown"!==n,o=r?this:u,i="react"===n?"state":"",c=i?o[i]:o,{wrap:f,lock:p,syncRefHandle:y,manualUnlock:d}="boolean"==typeof t?{wrap:t}:{...t};let h,m,g=[],b=!1,j=!1;const O=(e,t)=>!!e&&s.call(e,t),x=e=>"Object"===a(e),A=e=>{g.length?r?((e,t,r)=>{if("vue"===n&&o.$set&&!O(e,t[0]))return;const{$set:i=((e,t,n)=>{e[t]=n})}=o,s="react"===n,c=s?{...e}:e;let a=c,l=!1;for(let e=0;e<t.length;e++){const n=t[e],o=O(a,n);if(e===t.length-1){const e="boolean"==typeof a[n];l=!o||e,l&&i(a,n,r)}else{if(!o&&i(a,n,{}),!x(a[n]))break;s&&(a[n]={...a[n]}),a=a[n]}}s&&l&&o.setState({[t[0]]:c[t[0]]})})(c,g,e):u[p]=e:(m&&(m[0][m[1]]=e),h&&h(e))},B=()=>m?m[0][m[1]]:r||"string"!=typeof p?((e,t)=>{let n=!1;if(e&&x(e)&&Array.isArray(t)&&t.length){let r=e;for(let e=0;e<t.length;e++){const o=t[e];if("object"!=typeof r||!O(r,o))break;r=r[o],e===t.length-1&&(n="boolean"==typeof r&&r)}}return n})(c,g):c[p];if(p){const e=e=>Array.isArray(e)&&2===e.length;"string"==typeof p?g=p.split("."):e(p)?m=p:"function"==typeof p&&(h=p,e(y)&&(m=y)),b=g.length>0||!!m||!!h,b&&(j=B())}let v;v="function"==typeof e?j?(()=>{const e=Promise.resolve(void 0);return Object.assign(e,{then(...t){const[n]=t;return 2===t.length&&"function"==typeof n?n(void 0):e},catch:t=>e,finally:()=>e})})():f?l(e()):e():f?l(e):e;const E=()=>A(!1);return Object.defineProperties(v,{__lockValue:{get:B},_checkLockKey:{value:e=>u[e]},unlock:{value:E}}),b&&!j&&(A(!0),!d&&v.finally(E)),v}const p=Object.defineProperty(f,"_checkLockKey",{value:e=>u[e]}),y={install(e,t="$wp"){e.config&&"globalProperties"in e.config?e.config.globalProperties[t]=f:e.prototype[t]=f}};function d(e="",t){try{return JSON.parse(e)}catch(e){return t}}const h=(e,t)=>{const n={};return Object.keys(e).forEach((r=>{const o=e[r];""!==o&&null!=o&&(n[r]=t&&"[object Object]"===Object.prototype.toString.call(o)?h(o):o)})),n},{toString:m}=Object.prototype,g=e=>{if(null!==e)return Array.isArray(e)?e.map(g):("[object Object]"===m.call(e)&&Object.keys(e).forEach((t=>{e[t]=g(e[t])})),e)},b=(e,t,n)=>{const r=Object.keys(t),o={},i={};Object.keys(e).forEach((t=>{r.includes(t)?o[t]=e[t]:i[t]=e[t]}));const s=Object.keys(o);if(0===s.length)return e;const{filterNullable:c,dateFormat:a}={filterNullable:!0,...n},l=s.reduce(((e,n)=>{const r=o[n],i=t[n];if(!r||!i)return e;if("join"===i||"pop"===i)Array.isArray(r)&&r.length&&(e[n]="join"===i?r.join(","):r.slice(-1)[0]);else if(2===i.length||3===i.length){if(!r||2!==r.length)return e;const[t,n,o]=i,[s,c]=r;Object.assign(e,{[t]:a instanceof Function?a(s,o):s,[n]:a instanceof Function?a(c,o):c})}return e}),{}),u={...i,...l};return c?h(u):u},j=e=>"string"==typeof e,O=Symbol("NOMETHOD");function x(e){const t=new Map([[O,new Set]]),{name:n,customHanlderCreator:r}=e||{},o=r instanceof Function?r(t):null,i=/\|-[a-z]+-\|/,s=(e,...t)=>{try{e(...t)}catch(e){console.error(e)}},c=o instanceof Function?o:e=>{const{method:r,data:o,originEmitterName:c,targetEmitterName:a}=e||[];if(r&&"string"==typeof r){const e=[];t.forEach(((t,n)=>{if("string"==typeof n&&n.startsWith(r)){const[,r]=n.split(i);r&&c&&r!==c||e.push(...t)}})),!e.length||n&&a&&n!==a||e.forEach((e=>s(e,o)))}const l=t.get(O);l&&l.forEach((t=>s(t,o,e)))},a=(e,t)=>{const{limitFrom:n="",namespace:r=""}=t||{};return(n||r)&&"string"==typeof e?`${e}|-from-|${n}|-ns-|${r}`:e},l=(e,t,r)=>j(e)?{method:e,data:t,...r&&j(r)?{targetEmitterName:r}:{},...n&&j(n)?{originEmitterName:n}:{}}:e;return{name:n,rootEventListener:c,on:(e,n,r)=>{if("symbol"==typeof e&&e!==O)return;const o=a(e,r);t.has(o)||t.set(o,new Set);t.get(o)?.add(n)},off:(e,n,r)=>{if("symbol"==typeof e&&e!==O)return;const{limitFrom:o,namespace:i}=r||{};if(i&&!e)return void t.forEach(((e,n)=>{"string"==typeof n&&n.endsWith(i)&&t.delete(n)}));const s=a(e,r);n?t.get(s)?.delete(n):t.delete(s)},emit:(...e)=>{const t=l(...e);c(t)},createPayload:l,removeAllListeners:()=>{t.clear()},getMethodNames:e=>{if(!e){const e=[];return t.forEach(((t,n)=>j(n)&&e.push(n.split(i)))),e}const n=[];return t.forEach(((e,t)=>j(t)&&n.push(t))),n},getListeners:(e,n)=>{if("symbol"==typeof e)return e===O?Array.from(t.get(O)||[]):[];const r=a(e,n),o=t.get(r);return o?Array.from(o):[]}}}e.ChinaIdCardValid=function(e){const t=e.toString().toUpperCase();return r.test(t)&&["11","12","13","14","15","21","22","23","31","32","33","34","35","36","37","41","42","43","44","45","46","50","51","52","53","54","61","62","63","64","65","71","81","82","91"].includes(t.substr(0,2))&&(()=>{if(18===t.length){const e=t.split(""),n=[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2],r=[1,0,"X",9,8,7,6,5,4,3,2];let o=0,i=0,s=0;for(let t=0;t<17;t++)i=parseInt(e[t]),s=n[t],o+=i*s;return r[o%11].toString()===e[17]}return!0})()},e.NOMETHOD=O,e.array2tree=function(e,r={}){const{primaryKey:o,parentKey:i,childrenKey:s,createRoot:c,parentRefKey:a}={primaryKey:"id",parentKey:"pid",childrenKey:"children",createRoot:!1,parentRefKey:!1,...r},l=a&&("string"==typeof a?a:"_parent");let u={},f=[];return Array.isArray(e)&&e.forEach((e=>{!t.call(u,e[o])&&(u[e[o]]=Object.assign({},e,n(s))),t.call(u,e[i])&&u[e[i]][s].push(Object.assign(u[e[o]],l?{[l]:u[e[i]]}:{})),!e[i]&&f.push(u[e[o]])})),c instanceof Function?c(f):c?{[s]:f}:f},e.awaitWrapper=l,e.byteParse=function(e,t={}){},e.byteStringify=function(e,t){const n=Object.assign({standard:"jedec",unitLvl:"auto",precision:1,detail:!1},t),{standard:r,unitLvl:o,precision:i,detail:s}=n;let c=parseFloat(e);if(!Number.isFinite(c))return;const a=c<0?-1:1;c=Math.abs(c);const{base:l,unitMap:u}=((e,t)=>{const n={B:{expMax:0,units:{metric:"B",iec:"B",jedec:"B"}},K:{expMax:1,units:{metric:"kB",iec:"KiB",jedec:"KB"}},M:{expMax:2,units:{metric:"MB",iec:"MiB",jedec:"MB"}},G:{expMax:3,units:{metric:"GB",iec:"GiB",jedec:"GB"}},T:{expMax:4,units:{metric:"TB",iec:"TiB",jedec:"TB"}},P:{expMax:5,units:{metric:"PB",iec:"PiB",jedec:"PB"}},E:{expMax:6,units:{metric:"EB",iec:"EiB",jedec:"EB"}},Z:{expMax:7,units:{metric:"ZB",iec:"ZiB",jedec:"ZB"}},Y:{expMax:8,units:{metric:"YB",iec:"YiB",jedec:"YB"}}},r={metric:1e3,iec:1024,jedec:1024};return{base:r[e]||r.jedec,unitMap:n[t]||Object.values(n)}})(r,o),f=e=>Number.isInteger(e)?e:e.toFixed(i);let p="",y=0;if(Array.isArray(u))u.some((e=>{const t=Math.pow(l,e.expMax),n=c/t;return!(n>l)&&(p=e.units[r],y=f(n*a),!0)}));else{const e=Math.pow(l,u.expMax);p=u.units[r];y=f(c/e*a)}return s?{value:y,unit:p}:`${y} ${p}`},e.checkoutBy=function(e,t,n){return o(e)?Array.isArray(t)?t.map((t=>e[t])):t&&o(t)?Object.keys(t).map((r=>o(e[r])&&o(t[r])?n?n({},e[r],t[r]):Object.assign({},e[r],t[r]):t[r]||e[r])):Object.values(e):[]},e.eventTargetEmitter=x,e.filterNullable=h,e.formParamsSwitch=b,e.formParamsSwitchCreator=e=>(t,n,r)=>b(t,n,{dateFormat:e,...r}),e.formulaValidate=function(e,t){return e=e.replace(/\s/g,""),!/[+\-*/]{2,}/.test(e)&&!/\(\)/.test(e)&&!/\([+\-*/]/.test(e)&&!/[+\-*/]\)/.test(e)&&!/[^+\-*/]\(/.test(e)&&!/\)[^+\-*/]/.test(e)&&(()=>{let t=[];for(let n,r=0;r<e.length;r++)if(n=e.charAt(r),"("===n)t.push("(");else if(")"===n){if(!(t.length>0))return!1;t.pop()}return!t.length})()&&(!Array.isArray(t)||(n=t,e.replace(/[()+\-*/]{1,}/g,"`").split("`").every((e=>!/[A-Z]/i.test(e)||n.includes(e)))));var n},e.isNullable=e=>""===e||null==e,e.mapToObject=function(e,t="key",n="value"){const r={};return Array.isArray(e)&&t&&n&&[t,n].every((e=>["string","function"].includes(typeof e)))&&e.forEach(((e,o)=>{const i="string"==typeof t?e[t]:t(e,o),s="string"==typeof n?e[n]:n(e,o);["string","number"].includes(typeof i)&&(r[i]=s)})),r},e.maskData=function(e,t){if("string"!=typeof e||!e)return"";const n=t&&t.mode&&i[t.mode]?i[t.mode]:{},{maskWith:r,startCharIndex:o=0,endCharIndex:s,startFrom:c,endUntil:a}={maskWith:"*",...n,...t};let l=e,u="",f="";const p=c?e.indexOf(c):-1;if(p>-1){const t=p+c.length;l=l.slice(t),u=e.slice(0,t)}const y=a?e.lastIndexOf(a):-1;y>-1&&(l=l.slice(0,y),f=e.slice(y));const d=l.split(""),h=[u],m=d.length,g=[o>=0?o:m+o,void 0!==s?s>=0?s:m+s:m-1];let[b,j]=g;return j=j>0&&j<m?j:m-1,b=b>=0&&b<=j?b:0,d.forEach(((e,t)=>{h.push(t>=b&&t<=j?r:e)})),h.push(f),h.join("")},e.objType=a,e.pageCommunicate=function(e){const{messageHanlder:t,currentPage:n}=e||{},{emit:r,on:o,off:i,createPayload:s,removeAllListeners:c}=x({name:n,customHanlderCreator:t}),a=e=>r(e.data);let l;const u=window.localStorage,f="PAGE_COMMUNICATE_CHANNEL";if(void 0!==typeof BroadcastChannel)l=new BroadcastChannel(f),l.addEventListener("message",a);else{const e=()=>{const e=d(u.getItem(f)||"");e&&r(e)};window.addEventListener("storage",e)}return{on:o,off:i,send:(...e)=>{const t=s(...e);if(l)l.postMessage(t);else{const e=JSON.stringify({...t,ts:+new Date});u.setItem(f,e)}},destory:()=>{c(),l?l.close():u.removeItem(f)}}},e.pickRenameKeys=function(e,t){if(!(e&&o(e)&&t&&o(t)))return;let n={};for(let r in e)r in t&&(n[t[r]]=e[r]);return n},e.safeJsonParse=d,e.switchNullToUndefined=g,e.tree2array=function(e,t={}){const{primaryKey:r,parentKey:o,childrenKey:i,hasParentKey:s,returnObject:c}=Object.assign({hasParentKey:!0,primaryKey:"id",parentKey:"pid",childrenKey:"children",returnObject:!1},t);let a=c?{}:[];return Array.isArray(e)||"object"==typeof e?(function e(t,n,l=!1){let u=s?{}:{[o]:n};if(!l){const e=Object.assign(u,function(e,t){let n={};for(let r in e)r!==t&&(n[r]=e[r]);return n}(t,i));c?a[t[r]]=e:a.push(e)}Array.isArray(t[i])&&t[i].length&&t[i].forEach((n=>e(n,t[r])))}(Array.isArray(e)?n(i,e):e,null,!0),a):a},e.wp=p,e.wpVuePlugin=y,Object.defineProperty(e,"__esModule",{value:!0})}));
6
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).EsUtil={})}(this,(function(e){"use strict";const{hasOwnProperty:t,toString:n}=Object.prototype,r=(e,t)=>{Object.keys(e).forEach(((n,r)=>t(n,e[n],r)))},o=e=>"function"==typeof e,i=Array.isArray,s=e=>{const t=(r=e,n.call(r)).match(/^\[object (.*)\]$/);var r;return t?t[1]:""},a=e=>"Object"===s(e),c=(e,n)=>t.call(e,n);function l(e,t=[]){return{[e]:t}}const u=/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i;const d={telphone:{startCharIndex:-8,endCharIndex:-5},idcard:{startCharIndex:-12,endCharIndex:-5}};async function f(e){try{return[null,await e]}catch(e){return[e,void 0]}}const p=function(e,t){const{wrap:n,lock:r,syncRefHandle:s}={...t};let a,c,l=!1,u=!1;const d=e=>{c&&(c[0][c[1]]=e),a&&a(e)};if(r){const e=e=>i(e)&&2===e.length;e(r)?c=r:o(r)&&(a=r,e(s)&&(c=s)),l=!(!a&&!c),l&&(u=!!c&&c[0][c[1]])}let p;if(o(e)){const t=u?Promise.resolve(void 0):e();p=n?f(t):t}else p=n?f(e):e;return p instanceof Promise&&l&&!u&&(d(!0),p.finally((()=>d(!1)))),p};function m(e="",t){try{return JSON.parse(e)}catch(e){return t}}const h=e=>""===e||null==e,y=(e,t)=>{const n={};return r(e,((e,r)=>{h(r)||(t?i(r)?n[e]=r.map((e=>a(e)?y(e):e)):n[e]=a(r)?y(r):r:n[e]=r)})),n},g=e=>{if(null!==e){if(i(e))return e.map(g);if(a(e)){const t={};return r(e,((e,n)=>{t[e]=g(n)})),t}return e}},b=(e,t,n)=>{const s=Object.keys(t),a={},c={};r(e,(t=>{s.includes(t)?a[t]=e[t]:c[t]=e[t]}));const l=Object.keys(a);if(0===l.length)return e;const{filterNullable:u,dateFormat:d}={filterNullable:!0,...n},f=l.reduce(((e,n)=>{const r=a[n],s=t[n];if(!r||!s)return e;if("join"===s||"pop"===s)i(r)&&r.length&&(e[n]="join"===s?r.join(","):r.slice(-1)[0]);else if(2===s.length||3===s.length){if(!r||2!==r.length)return e;const[t,n,i]=s,[a,c]=r;Object.assign(e,{[t]:o(d)?d(a,i):a,[n]:o(d)?d(c,i):c})}return e}),{}),p={...c,...f};return u?y(p):p},j=e=>"string"==typeof e,x=Symbol("NOMETHOD");function M(e){const t=new Map([[x,new Set]]),{name:n,customHanlderCreator:r}=e||{},i=o(r)?r(t):null,s=/\|-[a-z]+-\|/,a=(e,...t)=>{try{e(...t)}catch(e){console.error(e)}},c=o(i)?i:e=>{const{method:r,data:o,originEmitterName:i,targetEmitterName:c}=e||[];if(r&&"string"==typeof r){const e=[];t.forEach(((t,n)=>{if("string"==typeof n&&n.startsWith(r)){const[,r]=n.split(s);r&&i&&r!==i||e.push(...t)}})),!e.length||n&&c&&n!==c||e.forEach((e=>a(e,o)))}const l=t.get(x);l&&l.forEach((t=>a(t,o,e)))},l=(e,t)=>{const{limitFrom:n="",namespace:r=""}=t||{};return(n||r)&&"string"==typeof e?`${e}|-from-|${n}|-ns-|${r}`:e},u=(e,t,r)=>j(e)?{method:e,data:t,...r&&j(r)?{targetEmitterName:r}:{},...n&&j(n)?{originEmitterName:n}:{}}:e;return{name:n,rootEventListener:c,on:(e,n,r)=>{if("symbol"==typeof e&&e!==x)return;const o=l(e,r);t.has(o)||t.set(o,new Set);t.get(o)?.add(n)},off:(e,n,r)=>{if("symbol"==typeof e&&e!==x)return;const{namespace:o}=r||{};if(o&&!e)return void t.forEach(((e,n)=>{"string"==typeof n&&n.endsWith(o)&&t.delete(n)}));const i=l(e,r);n?t.get(i)?.delete(n):t.delete(i)},emit:(...e)=>{const t=u(...e);c(t)},createPayload:u,removeAllListeners:()=>{t.clear()},getMethodNames:e=>{if(!e){const e=[];return t.forEach(((t,n)=>j(n)&&e.push(n.split(s)))),e}const n=[];return t.forEach(((e,t)=>j(t)&&n.push(t))),n},getListeners:(e,n)=>{if("symbol"==typeof e)return e===x?Array.from(t.get(x)||[]):[];const r=l(e,n),o=t.get(r);return o?Array.from(o):[]}}}e.ChinaIdCardValid=function(e){const t=e.toString().toUpperCase();return u.test(t)&&["11","12","13","14","15","21","22","23","31","32","33","34","35","36","37","41","42","43","44","45","46","50","51","52","53","54","61","62","63","64","65","71","81","82","91"].includes(t.substr(0,2))&&(()=>{if(18===t.length){const e=t.split(""),n=[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2],r=[1,0,"X",9,8,7,6,5,4,3,2];let o=0,i=0,s=0;for(let t=0;t<17;t++)i=parseInt(e[t]),s=n[t],o+=i*s;return r[o%11].toString()===e[17]}return!0})()},e.NOMETHOD=x,e.array2tree=function(e,t={}){const{primaryKey:n,parentKey:r,childrenKey:s,createRoot:a,parentRefKey:u}={primaryKey:"id",parentKey:"pid",childrenKey:"children",createRoot:!1,parentRefKey:!1,...t},d=u&&("string"==typeof u?u:"_parent"),f={},p=[];return i(e)&&e.forEach((e=>{!c(f,e[n])&&(f[e[n]]=Object.assign({},e,l(s))),c(f,e[r])&&f[e[r]][s].push(Object.assign(f[e[n]],d?{[d]:f[e[r]]}:{})),!e[r]&&p.push(f[e[n]])})),o(a)?a(p):a?{[s]:p}:p},e.awaitWrapper=f,e.b64UriDecode=e=>decodeURIComponent(window.atob(e)),e.b64UriEncode=e=>window.btoa(encodeURIComponent(e)),e.byteStringify=function(e,t){const n=Object.assign({standard:"jedec",unitLvl:"auto",precision:1,detail:!1},t),{standard:r,unitLvl:o,precision:s,detail:a}=n;let c=parseFloat(e);if(!Number.isFinite(c))return;const l=c<0?-1:1;c=Math.abs(c);const{base:u,unitMap:d}=((e,t)=>{const n={B:{expMax:0,units:{metric:"B",iec:"B",jedec:"B"}},K:{expMax:1,units:{metric:"kB",iec:"KiB",jedec:"KB"}},M:{expMax:2,units:{metric:"MB",iec:"MiB",jedec:"MB"}},G:{expMax:3,units:{metric:"GB",iec:"GiB",jedec:"GB"}},T:{expMax:4,units:{metric:"TB",iec:"TiB",jedec:"TB"}},P:{expMax:5,units:{metric:"PB",iec:"PiB",jedec:"PB"}},E:{expMax:6,units:{metric:"EB",iec:"EiB",jedec:"EB"}},Z:{expMax:7,units:{metric:"ZB",iec:"ZiB",jedec:"ZB"}},Y:{expMax:8,units:{metric:"YB",iec:"YiB",jedec:"YB"}}},r={metric:1e3,iec:1024,jedec:1024};return{base:r[e]||r.jedec,unitMap:n[t]||Object.values(n)}})(r,o),f=e=>Number.isInteger(e)?e:e.toFixed(s);let p="",m=0;if(i(d))d.some((e=>{const t=Math.pow(u,e.expMax),n=c/t;return!(n>u)&&(p=e.units[r],m=f(n*l),!0)}));else{const e=Math.pow(u,d.expMax);p=d.units[r];m=f(c/e*l)}return a?{value:m,unit:p}:`${m} ${p}`},e.checkoutBy=function(e,t,n){return a(e)?i(t)?t.map((t=>e[t])):t&&a(t)?Object.keys(t).map((r=>{const o=t[r];return a(e[r])&&a(o)?n?n({},e[r],o):Object.assign({},e[r],o):o||e[r]})):Object.values(e):[]},e.createRAFTimer=e=>{const{autoStopWhenNoTask:t,autoStartWhenAddTask:n}={...e};let r=0,o=!0,i=0,s=0,a=[],c=!1;const l=e=>{const n=e-(s||e);s=e,i+=n,c&&(a=a.filter((e=>!e.needClear)),c=!1),!t||a.length?(a.forEach((e=>{const{callback:t,maxTime:r,runTime:o,elapsed:s,interval:a,needClear:l}=e;if(!l){if(r&&o>=r)return e.needClear=!0,void(c=!0);if(s>=a){try{t(i)}catch(e){}e.elapsed=0,e.runTime+=1}else e.elapsed+=n}})),r=window.requestAnimationFrame(l)):o=!0},u=()=>{r=window.requestAnimationFrame(l),o=!1},d=()=>{window.cancelAnimationFrame(r),o=!0};return{start:u,stop:d,pauseToggle:()=>{o?u():d()},addTask:(e,t,r)=>{e&&(n&&o&&u(),a.push({callback:e,elapsed:0,interval:t,maxTime:r,runTime:0}))},removeTask:e=>{a=a.filter((t=>t.callback!==e))},isPaused:()=>o}},e.eventTargetEmitter=M,e.filterNullable=y,e.formParamsSwitch=b,e.formParamsSwitchCreator=e=>(t,n,r)=>b(t,n,{dateFormat:e,...r}),e.formulaValidate=function(e,t){return e=e.replace(/\s/g,""),!/[+\-*/]{2,}/.test(e)&&!/\(\)/.test(e)&&!/\([+\-*/]/.test(e)&&!/[+\-*/]\)/.test(e)&&!/[^+\-*/]\(/.test(e)&&!/\)[^+\-*/]/.test(e)&&(()=>{const t=[];for(let n,r=0;r<e.length;r++)if(n=e.charAt(r),"("===n)t.push("(");else if(")"===n){if(!(t.length>0))return!1;t.pop()}return!t.length})()&&(!i(t)||(n=t,e.replace(/[()+\-*/]{1,}/g,"`").split("`").every((e=>!/[A-Z]/i.test(e)||n.includes(e)))));var n},e.isNullable=h,e.mapToObject=function(e,t="key",n="value"){const r={};return i(e)&&t&&n&&[t,n].every((e=>["string","function"].includes(typeof e)))&&e.forEach(((e,o)=>{const i="string"==typeof t?e[t]:t(e,o),s="string"==typeof n?e[n]:n(e,o);["string","number"].includes(typeof i)&&(r[i]=s)})),r},e.maskData=function(e,t){if("string"!=typeof e||!e)return"";const n=t&&t.mode&&d[t.mode]?d[t.mode]:{},{maskWith:r,startCharIndex:o=0,endCharIndex:i,startFrom:s,endUntil:a}={maskWith:"*",...n,...t};let c=e,l="",u="";const f=s?e.indexOf(s):-1;if(f>-1){const t=f+s.length;c=c.slice(t),l=e.slice(0,t)}const p=a?e.lastIndexOf(a):-1;p>-1&&(c=c.slice(0,p),u=e.slice(p));const m=c.split(""),h=[l],y=m.length,g=[o>=0?o:y+o,void 0!==i?i>=0?i:y+i:y-1];let[b,j]=g;return j=j>0&&j<y?j:y-1,b=b>=0&&b<=j?b:0,m.forEach(((e,t)=>{h.push(t>=b&&t<=j?r:e)})),h.push(u),h.join("")},e.pageCommunicate=function(e){const{messageHanlder:t,currentPage:n}=e||{},{emit:r,on:o,off:i,createPayload:s,removeAllListeners:a}=M({name:n,customHanlderCreator:t}),c=e=>r(e.data);let l;const u=window.localStorage,d="PAGE_COMMUNICATE_CHANNEL";if(void 0!==typeof window.BroadcastChannel)l=new BroadcastChannel(d),l.addEventListener("message",c);else{const e=()=>{const e=m(u.getItem(d)||"");e&&r(e)};window.addEventListener("storage",e)}return{on:o,off:i,send:(...e)=>{const t=s(...e);if(l)l.postMessage(t);else{const e=JSON.stringify({...t,ts:+new Date});u.setItem(d,e)}},destory:()=>{a(),l?l.close():u.removeItem(d)}}},e.pickRenameKeys=function(e,t){if(!(e&&a(e)&&t&&a(t)))return;const n={};for(const r in e)r in t&&(n[t[r]]=e[r]);return n},e.safeJsonParse=m,e.secondsToDuration=(e,t="h")=>{const n=Number.isInteger(e)?e:Math.round(e),r={s:n%60};switch(t){case"m":r.m=Math.floor(n/60);break;case"h":r.m=Math.floor(n%3600/60),r.h=Math.floor(n/3600);break;case"d":r.m=Math.floor(n%3600/60),r.h=Math.floor(n%86400/3600),r.d=Math.floor(n/3600/24)}return r},e.switchNullToUndefined=g,e.tree2array=function(e,t={}){const{primaryKey:n,parentKey:r,childrenKey:o,hasParentKey:s,returnObject:a}=Object.assign({hasParentKey:!0,primaryKey:"id",parentKey:"pid",childrenKey:"children",returnObject:!1},t),c=a?{}:[];return i(e)||"object"==typeof e?(function e(t,l,u=!1){const d=s?{}:{[r]:l};if(!u){const e=Object.assign(d,function(e,t){const n={};for(const r in e)r!==t&&(n[r]=e[r]);return n}(t,o));a?c[t[n]]=e:c.push(e)}i(t[o])&&t[o].length&&t[o].forEach((r=>e(r,t[n])))}(i(e)?l(o,e):e,null,!0),c):c},e.wp=p,Object.defineProperty(e,"__esModule",{value:!0})}));
@@ -13,12 +13,12 @@ export declare function mapToObject(objectArray: AnyObject[], keyProp?: string |
13
13
  declare type MergeFn = <T>(...args: T[]) => T;
14
14
  /**
15
15
  * checkout values form object as an array
16
- *
16
+ * 从对象中挑选指定的值并以数组形式返回,必要时可使用自定义属性覆盖选中对象
17
17
  * @param {Object} object
18
18
  * @param {string[] | Object} keys
19
19
  * @param {string} valueProp
20
20
  */
21
- export declare function checkoutBy(object: AnyObject, keys?: string[] | AnyObject, mergeFn?: MergeFn): any[];
21
+ export declare function checkoutBy<T extends AnyObject = AnyObject, K extends string & keyof T = Extract<keyof T, 'string'>>(object: T, keys?: K[] | Record<string, any>, mergeFn?: MergeFn): any[];
22
22
  /**
23
23
  * pick and rename object values
24
24
  *
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.7.0
2
+ * @wxhccc/es-util v2.0.2
3
3
  * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -7,36 +7,44 @@
7
7
 
8
8
  Object.defineProperty(exports, '__esModule', { value: true });
9
9
 
10
+ var utils = require('./utils.js');
11
+
10
12
  function mapToObject(objectArray, keyProp = 'key', valueProp = 'value') {
11
13
  const result = {};
12
- Array.isArray(objectArray) && keyProp && valueProp
13
- && [keyProp, valueProp].every(val => ['string', 'function'].includes(typeof val))
14
- && objectArray.forEach((item, index) => {
14
+ utils.isArr(objectArray) &&
15
+ keyProp &&
16
+ valueProp &&
17
+ [keyProp, valueProp].every((val) => ['string', 'function'].includes(typeof val)) &&
18
+ objectArray.forEach((item, index) => {
15
19
  const key = typeof keyProp === 'string' ? item[keyProp] : keyProp(item, index);
16
20
  const value = typeof valueProp === 'string' ? item[valueProp] : valueProp(item, index);
17
21
  ['string', 'number'].includes(typeof key) && (result[key] = value);
18
22
  });
19
23
  return result;
20
24
  }
21
- const isObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]';
22
25
  /**
23
26
  * checkout values form object as an array
24
- *
27
+ * 从对象中挑选指定的值并以数组形式返回,必要时可使用自定义属性覆盖选中对象
25
28
  * @param {Object} object
26
29
  * @param {string[] | Object} keys
27
30
  * @param {string} valueProp
28
31
  */
29
32
  function checkoutBy(object, keys, mergeFn) {
30
- if (!isObject(object)) {
33
+ if (!utils.isObj(object)) {
31
34
  return [];
32
35
  }
33
- if (Array.isArray(keys)) {
34
- return keys.map(item => object[item]);
36
+ if (utils.isArr(keys)) {
37
+ return keys.map((key) => object[key]);
35
38
  }
36
- else if (keys && isObject(keys)) {
37
- return Object.keys(keys).map(item => (isObject(object[item]) && isObject(keys[item]))
38
- ? (mergeFn ? mergeFn({}, (object)[item], (keys)[item]) : Object.assign({}, object[item], keys[item]))
39
- : (keys[item] || object[item]));
39
+ else if (keys && utils.isObj(keys)) {
40
+ return Object.keys(keys).map((key) => {
41
+ const value = keys[key];
42
+ return utils.isObj(object[key]) && utils.isObj(value)
43
+ ? mergeFn
44
+ ? mergeFn({}, object[key], value)
45
+ : Object.assign({}, object[key], value)
46
+ : value || object[key];
47
+ });
40
48
  }
41
49
  return Object.values(object);
42
50
  }
@@ -47,12 +55,12 @@ function checkoutBy(object, keys, mergeFn) {
47
55
  * @param {Object} keysMap
48
56
  */
49
57
  function pickRenameKeys(object, keysMap) {
50
- if (!object || !isObject(object) || !keysMap || !isObject(keysMap)) {
58
+ if (!object || !utils.isObj(object) || !keysMap || !utils.isObj(keysMap)) {
51
59
  return;
52
60
  }
53
- let result = {};
54
- for (let i in object) {
55
- (i in keysMap) && (result[keysMap[i]] = object[i]);
61
+ const result = {};
62
+ for (const i in object) {
63
+ i in keysMap && (result[keysMap[i]] = object[i]);
56
64
  }
57
65
  return result;
58
66
  }
@@ -17,9 +17,9 @@ export declare const isNullable: (value: unknown) => value is "" | null | undefi
17
17
  * @param deep 是否需要递归过滤
18
18
  * @returns 过滤后的对象
19
19
  */
20
- export declare const filterNullable: <T extends AnyObject>(obj: T, deep?: boolean | undefined) => T;
20
+ export declare const filterNullable: <T extends AnyObject>(obj: T, deep?: boolean) => T;
21
21
  /**
22
- * 将对象中属性值为null的转换为undefined
22
+ * 将对象中属性值为null的转换为undefined,会返回一个浅拷贝的新对象
23
23
  * @param data 对象数据
24
24
  * @returns
25
25
  */
@@ -28,10 +28,7 @@ export declare const switchNullToUndefined: (data: any) => any;
28
28
  * 参数转换规则的配置对象
29
29
  * 值可以是时间范围转换所需的开始,结束时间字段的名称,或者需要进行拼接的数组
30
30
  */
31
- export declare type ParamsSwitchMaps<DK extends string = string, RK extends string = string> = Record<DK, [
32
- RK,
33
- RK
34
- ] | [RK, RK, string] | 'join' | 'pop'>;
31
+ export declare type ParamsSwitchMaps<DK extends string = string, RK extends string = string> = Record<DK, [RK, RK] | [RK, RK, string] | 'join' | 'pop'>;
35
32
  export declare type DateFormat = (date: any, format?: string) => string;
36
33
  /**
37
34
  * 将搜素条件里的数组字段转换为其他格式,通常用于搜索表单的字段转换
@@ -41,10 +38,10 @@ export declare type DateFormat = (date: any, format?: string) => string;
41
38
  */
42
39
  export declare const formParamsSwitch: <R extends AnyObject = AnyObject, T extends AnyObject = AnyObject>(formData: T, maps: Partial<ParamsSwitchMaps<Exclude<keyof T, number | symbol>, Exclude<keyof R, number | symbol>>>, options?: {
43
40
  /** 是否需要过滤空数据 */
44
- filterNullable?: boolean | undefined;
41
+ filterNullable?: boolean;
45
42
  /** 时间格式换函数 */
46
- dateFormat?: DateFormat | undefined;
47
- } | undefined) => R;
43
+ dateFormat?: DateFormat;
44
+ }) => R;
48
45
  /** 创建一个绑定了默认时间格式转换函数的formParamsSwitch函数 */
49
46
  export declare const formParamsSwitchCreator: (dateFormat: DateFormat) => typeof formParamsSwitch;
50
47
  export {};
@@ -0,0 +1,136 @@
1
+ /*!
2
+ * @wxhccc/es-util v2.0.2
3
+ * (c) 2022 wxhccc
4
+ * @license MIT
5
+ */
6
+ 'use strict';
7
+
8
+ Object.defineProperty(exports, '__esModule', { value: true });
9
+
10
+ var utils = require('./utils.js');
11
+
12
+ function safeJsonParse(json = '', faileValue) {
13
+ try {
14
+ return JSON.parse(json);
15
+ }
16
+ catch (_e) {
17
+ return faileValue;
18
+ }
19
+ }
20
+ /**
21
+ * check value whether empty text
22
+ * 判断给定变量是否是字面量空值 */
23
+ const isNullable = (value) => value === '' || value === undefined || value === null;
24
+ /**
25
+ * 过滤对象中属性为空('' | undefined | null)的字段
26
+ * @param obj 给定对象
27
+ * @param deep 是否需要递归过滤
28
+ * @returns 过滤后的对象
29
+ */
30
+ const filterNullable = (obj, deep) => {
31
+ const result = {};
32
+ utils.objForEch(obj, (key, value) => {
33
+ if (!isNullable(value)) {
34
+ if (!deep) {
35
+ result[key] = value;
36
+ }
37
+ else if (utils.isArr(value)) {
38
+ result[key] = value.map((item) => utils.isObj(item) ? filterNullable(item) : item);
39
+ }
40
+ else {
41
+ result[key] = utils.isObj(value) ? filterNullable(value) : value;
42
+ }
43
+ }
44
+ });
45
+ return result;
46
+ };
47
+ /**
48
+ * 将对象中属性值为null的转换为undefined,会返回一个浅拷贝的新对象
49
+ * @param data 对象数据
50
+ * @returns
51
+ */
52
+ const switchNullToUndefined = (data) => {
53
+ if (data === null) {
54
+ return undefined;
55
+ }
56
+ if (utils.isArr(data)) {
57
+ return data.map(switchNullToUndefined);
58
+ }
59
+ else if (utils.isObj(data)) {
60
+ const result = {};
61
+ utils.objForEch(data, (key, value) => {
62
+ result[key] = switchNullToUndefined(value);
63
+ });
64
+ return result;
65
+ }
66
+ return data;
67
+ };
68
+ /**
69
+ * 将搜素条件里的数组字段转换为其他格式,通常用于搜索表单的字段转换
70
+ * @param formData 传入参数
71
+ * @param maps 转换的映射关系,eg:{ date: ['startTime', 'endTime'] }
72
+ * @param options 额外的配置参数
73
+ */
74
+ const formParamsSwitch = (formData, maps, options) => {
75
+ const dateKeys = Object.keys(maps);
76
+ const dateData = {};
77
+ const restData = {};
78
+ utils.objForEch(formData, (key) => {
79
+ if (dateKeys.includes(key)) {
80
+ dateData[key] = formData[key];
81
+ }
82
+ else {
83
+ restData[key] = formData[key];
84
+ }
85
+ });
86
+ const accessKeys = Object.keys(dateData);
87
+ // 如无需要转换的数据时,直接返回原对象
88
+ if (accessKeys.length === 0) {
89
+ return formData;
90
+ }
91
+ const { filterNullable: filterNullableValue, dateFormat } = {
92
+ filterNullable: true,
93
+ ...options
94
+ };
95
+ const handleData = accessKeys.reduce((acc, key) => {
96
+ const values = dateData[key];
97
+ const mapValue = maps[key];
98
+ if (!values || !mapValue) {
99
+ return acc;
100
+ }
101
+ // 数组合并操作/取最后一位操作
102
+ if (mapValue === 'join' || mapValue === 'pop') {
103
+ if (utils.isArr(values) && values.length) {
104
+ acc[key] = mapValue === 'join' ? values.join(',') : values.slice(-1)[0];
105
+ }
106
+ }
107
+ else if (mapValue.length === 2 || mapValue.length === 3) {
108
+ if (!values || values.length !== 2) {
109
+ return acc;
110
+ }
111
+ const [startKey, endKey, format] = mapValue;
112
+ const [startValue, endValue] = values;
113
+ Object.assign(acc, {
114
+ [startKey]: utils.isFn(dateFormat)
115
+ ? dateFormat(startValue, format)
116
+ : startValue,
117
+ [endKey]: utils.isFn(dateFormat) ? dateFormat(endValue, format) : endValue
118
+ });
119
+ }
120
+ return acc;
121
+ }, {});
122
+ const result = {
123
+ ...restData,
124
+ ...handleData
125
+ };
126
+ return filterNullableValue ? filterNullable(result) : result;
127
+ };
128
+ /** 创建一个绑定了默认时间格式转换函数的formParamsSwitch函数 */
129
+ const formParamsSwitchCreator = (dateFormat) => (formData, maps, options) => formParamsSwitch(formData, maps, { dateFormat, ...options });
130
+
131
+ exports.filterNullable = filterNullable;
132
+ exports.formParamsSwitch = formParamsSwitch;
133
+ exports.formParamsSwitchCreator = formParamsSwitchCreator;
134
+ exports.isNullable = isNullable;
135
+ exports.safeJsonParse = safeJsonParse;
136
+ exports.switchNullToUndefined = switchNullToUndefined;
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.7.0
2
+ * @wxhccc/es-util v2.0.2
3
3
  * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -7,16 +7,9 @@
7
7
 
8
8
  Object.defineProperty(exports, '__esModule', { value: true });
9
9
 
10
+ var optional = require('./optional.js');
10
11
  var eventTargetEmitter = require('./event-target-emitter.js');
11
-
12
- function safeJsonParse(json = '', faileValue) {
13
- try {
14
- return JSON.parse(json);
15
- }
16
- catch (_e) {
17
- return faileValue;
18
- }
19
- }
12
+ require('./utils.js');
20
13
 
21
14
  /**
22
15
  * 创建同源页面之间通信的封装实例,默认使用BroadcastChannel实现,在不支持的浏览器环境中会使用localstorage实现
@@ -25,18 +18,21 @@ function safeJsonParse(json = '', faileValue) {
25
18
  */
26
19
  function pageCommunicate(options) {
27
20
  const { messageHanlder, currentPage } = options || {};
28
- const { emit, on, off, createPayload, removeAllListeners } = eventTargetEmitter.eventTargetEmitter({ name: currentPage, customHanlderCreator: messageHanlder });
21
+ const { emit, on, off, createPayload, removeAllListeners } = eventTargetEmitter.eventTargetEmitter({
22
+ name: currentPage,
23
+ customHanlderCreator: messageHanlder
24
+ });
29
25
  const onMessage = (event) => emit(event.data);
30
26
  let bc;
31
27
  const ls = window.localStorage;
32
28
  const channelName = 'PAGE_COMMUNICATE_CHANNEL';
33
- if (typeof BroadcastChannel !== undefined) {
29
+ if (typeof window.BroadcastChannel !== undefined) {
34
30
  bc = new BroadcastChannel(channelName);
35
31
  bc.addEventListener('message', onMessage);
36
32
  }
37
33
  else {
38
34
  const onStorageMessage = () => {
39
- const payload = safeJsonParse(ls.getItem(channelName) || '');
35
+ const payload = optional.safeJsonParse(ls.getItem(channelName) || '');
40
36
  if (payload) {
41
37
  emit(payload);
42
38
  }
@@ -66,5 +62,5 @@ function pageCommunicate(options) {
66
62
  }
67
63
 
68
64
  exports.NOMETHOD = eventTargetEmitter.NOMETHOD;
69
- exports.default = pageCommunicate;
65
+ exports["default"] = pageCommunicate;
70
66
  exports.pageCommunicate = pageCommunicate;
package/dist/promise.d.ts CHANGED
@@ -1,44 +1,41 @@
1
- export declare const objType: (val: unknown) => string;
2
1
  /**
3
2
  * wrap promise and handle reject or err by return an array like [error, undefined]
4
3
  * @param promise promise
5
4
  * @returns Promise<[K, undefined] | [null, T]>
6
5
  */
7
6
  export declare function awaitWrapper<T, K = Error>(promise: Promise<T>): Promise<[null, T] | [K, undefined]>;
8
- export declare type SyncRefHandle = [Record<string, boolean>, string];
9
- export declare type LockSwitchHook = (val: boolean) => unknown;
10
- export interface PromiseWithLock<T> extends Promise<T> {
11
- readonly __lockValue: boolean;
12
- unlock: () => void;
13
- }
14
- export declare type ContextType = 'react' | 'vue' | 'unknown';
7
+ /** 防止多次promise函数运行控制器,对于响应式系统,可以同时用作BoolSwitch */
8
+ export declare type LockRefHandle<T extends {
9
+ [key: string]: boolean;
10
+ } = Record<string, boolean>> = [T, string];
11
+ /** loading等状态的切换函数 */
12
+ export declare type BoolSwitch = (val: boolean) => unknown;
15
13
  /**
16
14
  * wrap promise with lock, support reactive environment like react or vue
17
15
  * @param promise promise
18
16
  * @param wrap whether use awaitWrap to wrap result
19
17
  */
20
18
  export interface WpOptions {
19
+ /** whether use `awaitWrapper` to wrap then promise. */
21
20
  wrap?: boolean;
22
- lock?: string | LockSwitchHook | SyncRefHandle;
23
- syncRefHandle?: SyncRefHandle;
24
- manualUnlock?: boolean;
21
+ /** useful in Hook / Composition Api, you can pass setXXX to method */
22
+ lock?: BoolSwitch | LockRefHandle;
23
+ /** when you need function and syncRefHandle at sametime, in react hooks */
24
+ syncRefHandle?: LockRefHandle;
25
25
  }
26
- declare type WpReturn<T> = PromiseWithLock<T | undefined>;
27
- declare type WpArrReturn<T> = PromiseWithLock<[null, T] | [Error, undefined]>;
26
+ declare type WpReturn<T> = Promise<T | undefined>;
27
+ declare type WpArrReturn<T> = Promise<[null, T] | [Error, undefined]>;
28
+ declare type WpMayLockArrReturn<T> = Promise<[null, T] | [Error, undefined]>;
28
29
  declare type WpPromise<T> = Promise<T> | (() => Promise<T>);
29
- declare function wrapPromise<T>(this: any, promise: WpPromise<T>, wrap?: false): WpReturn<T>;
30
- declare function wrapPromise<T>(this: any, promise: WpPromise<T>, wrap: true): WpArrReturn<T>;
31
- declare function wrapPromise<T>(this: any, promise: WpPromise<T>, options?: WpOptions & {
30
+ declare function wrapPromise<T>(promise: WpPromise<T>, options?: WpOptions & {
32
31
  wrap?: false;
33
32
  }): WpReturn<T>;
34
- declare function wrapPromise<T>(this: any, promise: WpPromise<T>, options?: WpOptions & {
33
+ declare function wrapPromise<T>(promise: Promise<T>, options?: WpOptions & {
35
34
  wrap: true;
36
35
  }): WpArrReturn<T>;
37
- declare type WP = typeof wrapPromise & {
38
- _checkLockKey: (key: string) => boolean;
39
- };
40
- export declare const wp: WP;
41
- export declare const wpVuePlugin: {
42
- install(appOrVue: any, key?: string): void;
43
- };
36
+ declare function wrapPromise<T>(promise: () => Promise<T>, options?: WpOptions & {
37
+ wrap: true;
38
+ }): WpMayLockArrReturn<T>;
39
+ /** short for method `wrapPromise` */
40
+ export declare const wp: typeof wrapPromise;
44
41
  export {};
package/dist/promise.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.7.0
2
+ * @wxhccc/es-util v2.0.2
3
3
  * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -7,11 +7,8 @@
7
7
 
8
8
  Object.defineProperty(exports, '__esModule', { value: true });
9
9
 
10
- const { hasOwnProperty, toString } = Object.prototype;
11
- const objType = (val) => {
12
- const typeKeys = toString.call(val).match(/^\[object (.*)\]$/);
13
- return typeKeys ? typeKeys[1] : '';
14
- };
10
+ var utils = require('./utils.js');
11
+
15
12
  /**
16
13
  * wrap promise and handle reject or err by return an array like [error, undefined]
17
14
  * @param promise promise
@@ -26,160 +23,55 @@ async function awaitWrapper(promise) {
26
23
  return [err, undefined];
27
24
  }
28
25
  }
29
- function checkContext(context) {
30
- if (!context)
31
- return 'unknown';
32
- if (context._isVue || (context.$ && context.$.vnode)) {
33
- return 'vue';
34
- }
35
- else if ('setState' in context) {
36
- return 'react';
37
- }
38
- return 'unknown';
39
- }
40
- const emptyPromise = () => {
41
- const ep = Promise.resolve(undefined);
42
- return Object.assign(ep, {
43
- then(...args) {
44
- const [onfulfilled] = args;
45
- // if then has be called by Promise.all, let ite pass
46
- if (args.length === 2 && typeof onfulfilled === 'function') {
47
- return onfulfilled(undefined);
48
- }
49
- return ep;
50
- },
51
- catch: (onrejected) => ep,
52
- finally: () => ep
53
- });
54
- };
55
- const lockCtx = {};
56
- function wrapPromise(promise, wrapOrOptions) {
57
- const contextType = checkContext(this);
58
- const isReactiveIns = contextType !== 'unknown';
59
- const context = isReactiveIns ? this : lockCtx;
60
- const stateKey = contextType === 'react' ? 'state' : '';
61
- const contextState = stateKey ? context[stateKey] : context;
62
- const { wrap, lock, syncRefHandle, manualUnlock } = typeof wrapOrOptions === 'boolean' ? { wrap: wrapOrOptions } : { ...wrapOrOptions };
26
+ function wrapPromise(promise, options) {
27
+ const { wrap, lock, syncRefHandle } = { ...options };
63
28
  let lockSwitchHook = undefined;
64
29
  let lockRefHandle = undefined;
65
- let lockKey = [];
66
30
  let needLock = false;
67
- let ignoreLock = false;
68
- const has = (val, key) => !!val && hasOwnProperty.call(val, key);
69
- const isObj = (obj) => objType(obj) === 'Object';
70
- const getValue = (obj, path) => {
71
- let result = false;
72
- if (obj && isObj(obj) && Array.isArray(path) && path.length) {
73
- let curObj = obj;
74
- for (let i = 0; i < path.length; i++) {
75
- const key = path[i];
76
- if (typeof curObj !== 'object' || !has(curObj, key)) {
77
- break;
78
- }
79
- curObj = curObj[key];
80
- i === path.length - 1 &&
81
- (result = (typeof curObj === 'boolean') ? curObj : false);
82
- }
83
- }
84
- return result;
85
- };
86
- const setValue = (obj, path, value) => {
87
- // if vue2 and path[0] not defined, do nothing
88
- if (contextType === 'vue' && context.$set && !has(obj, path[0]))
89
- return;
90
- const { $set = (o, key, val) => { o[key] = val; } } = context;
91
- const isStateRect = contextType === 'react';
92
- const originObj = isStateRect ? { ...obj } : obj;
93
- let curObj = originObj;
94
- let canSet = false;
95
- for (let i = 0; i < path.length; i++) {
96
- const key = path[i];
97
- const keyExist = has(curObj, key);
98
- if (i === path.length - 1) {
99
- const isBool = typeof curObj[key] === 'boolean';
100
- canSet = !keyExist || isBool;
101
- canSet && $set(curObj, key, value);
102
- }
103
- else {
104
- !keyExist && $set(curObj, key, {});
105
- if (!isObj(curObj[key]))
106
- break;
107
- isStateRect && (curObj[key] = { ...curObj[key] });
108
- curObj = curObj[key];
109
- }
110
- }
111
- // trigger setState when run in react class component
112
- isStateRect && canSet && context.setState({ [path[0]]: originObj[path[0]] });
113
- };
31
+ let isLocking = false;
114
32
  const stateLock = (bool) => {
115
- if (lockKey.length) {
116
- // if not reactive instance, save lock key as string, no need to structure nested object
117
- isReactiveIns ? setValue(contextState, lockKey, bool) : (lockCtx[lock] = bool);
118
- return;
119
- }
120
- if (lockRefHandle)
33
+ if (lockRefHandle) {
121
34
  lockRefHandle[0][lockRefHandle[1]] = bool;
122
- if (lockSwitchHook)
35
+ }
36
+ if (lockSwitchHook) {
123
37
  lockSwitchHook(bool);
38
+ }
124
39
  };
125
40
  const checkLock = () => {
126
- // use refHandle if contextState not update sync
127
- if (lockRefHandle)
128
- return lockRefHandle[0][lockRefHandle[1]];
129
- if (!isReactiveIns && typeof lock === 'string')
130
- return contextState[lock];
131
- return getValue(contextState, lockKey);
41
+ // use refHandle if state not update sync
42
+ return lockRefHandle ? lockRefHandle[0][lockRefHandle[1]] : false;
132
43
  };
133
44
  if (lock) {
134
- const isRefHandle = (val) => Array.isArray(val) && val.length === 2;
135
- if (typeof lock === 'string') {
136
- lockKey = lock.split('.');
137
- }
138
- else if (isRefHandle(lock)) {
45
+ const isRefHandle = (val) => utils.isArr(val) && val.length === 2;
46
+ if (isRefHandle(lock)) {
139
47
  lockRefHandle = lock;
140
48
  }
141
- else if (typeof lock === 'function') {
49
+ else if (utils.isFn(lock)) {
142
50
  lockSwitchHook = lock;
143
51
  if (isRefHandle(syncRefHandle)) {
144
52
  lockRefHandle = syncRefHandle;
145
53
  }
146
54
  }
147
- needLock = lockKey.length > 0 || !!lockRefHandle || !!lockSwitchHook;
148
- needLock && (ignoreLock = checkLock());
55
+ needLock = !!(lockSwitchHook || lockRefHandle);
56
+ needLock && (isLocking = checkLock());
149
57
  }
150
58
  let corePromsie;
151
59
  // if promise is a function, here need to call it in promise.then to use locking check to prevent next call
152
- if (typeof promise === 'function') {
153
- corePromsie = ignoreLock ? emptyPromise() : wrap ? awaitWrapper(promise()) : promise();
60
+ if (utils.isFn(promise)) {
61
+ const truePromise = isLocking ? Promise.resolve(undefined) : promise();
62
+ corePromsie = wrap ? awaitWrapper(truePromise) : truePromise;
154
63
  }
155
64
  else {
156
65
  corePromsie = wrap ? awaitWrapper(promise) : promise;
157
66
  }
158
- const unlock = () => stateLock(false);
159
- Object.defineProperties(corePromsie, {
160
- '__lockValue': { get: checkLock },
161
- _checkLockKey: { value: (key) => lockCtx[key] },
162
- unlock: { value: unlock }
163
- });
164
- if (needLock && !ignoreLock) {
67
+ if (corePromsie instanceof Promise && needLock && !isLocking) {
165
68
  stateLock(true);
166
- !manualUnlock && corePromsie.finally(unlock);
69
+ corePromsie.finally(() => stateLock(false));
167
70
  }
168
71
  return corePromsie;
169
72
  }
170
- const wp = Object.defineProperty(wrapPromise, '_checkLockKey', { value: (key) => lockCtx[key] });
171
- const wpVuePlugin = {
172
- install(appOrVue, key = '$wp') {
173
- if (appOrVue.config && 'globalProperties' in appOrVue.config) {
174
- appOrVue.config.globalProperties[key] = wrapPromise;
175
- }
176
- else {
177
- appOrVue.prototype[key] = wrapPromise;
178
- }
179
- }
180
- };
73
+ /** short for method `wrapPromise` */
74
+ const wp = wrapPromise;
181
75
 
182
76
  exports.awaitWrapper = awaitWrapper;
183
- exports.objType = objType;
184
77
  exports.wp = wp;
185
- exports.wpVuePlugin = wpVuePlugin;