youtil 3.1.0-beta2 → 3.1.0-beta3
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.umd.js +55 -0
- package/dist/types/enum.d.ts +30 -0
- package/dist/types/index.d.ts +8 -0
- package/dist/types/loading.d.ts +19 -0
- package/dist/types/message.d.ts +12 -0
- package/dist/types/other.d.ts +42 -0
- package/dist/types/param.d.ts +48 -0
- package/dist/types/request.d.ts +62 -0
- package/dist/types/string.d.ts +42 -0
- package/dist/types/time.d.ts +21 -0
- package/package.json +3 -2
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
var youtil=(()=>{var I=Object.defineProperty,B=Object.defineProperties,K=Object.getOwnPropertyDescriptor,N=Object.getOwnPropertyDescriptors,V=Object.getOwnPropertyNames,L=Object.getOwnPropertySymbols;var j=Object.prototype.hasOwnProperty,X=Object.prototype.propertyIsEnumerable;var H=(e,n,t)=>n in e?I(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t,O=(e,n)=>{for(var t in n||(n={}))j.call(n,t)&&H(e,t,n[t]);if(L)for(var t of L(n))X.call(n,t)&&H(e,t,n[t]);return e},P=(e,n)=>B(e,N(n));var J=(e,n)=>{for(var t in n)I(e,t,{get:n[t],enumerable:!0})},Z=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of V(n))!j.call(e,s)&&s!==t&&I(e,s,{get:()=>n[s],enumerable:!(r=K(n,s))||r.enumerable});return e};var z=e=>Z(I({},"__esModule",{value:!0}),e);var me={};J(me,{Request:()=>ie,copyToClipboard:()=>ee,createEnum:()=>Y,decodeHtml:()=>_,deepCopy:()=>W,delParam:()=>ae,encodeHtml:()=>D,formatDate:()=>ce,formatJson:()=>de,getIdCardLastChar:()=>F,getParam:()=>E,getParamInt:()=>re,getParams:()=>se,getRandom:()=>A,getRandomStr:()=>ge,hideLoading:()=>M,initWindowMessage:()=>Q,keyCodes:()=>te,parseDate:()=>le,request:()=>R,setParam:()=>oe,showLoading:()=>G,sleep:()=>ue,toHump:()=>fe,toUnderline:()=>pe,toUrlParams:()=>T,validateIdCard:()=>ne});function Y(e){let n=[...e];return e.forEach(t=>{n[t.key]=t.value}),n.pick=t=>e.find(r=>r.key===t||r.value===t),n.pickLabel=t=>{var r;return(r=n.pick(t))==null?void 0:r.label},n.pickValue=t=>{var r;return(r=n.pick(t))==null?void 0:r.value},n.pickKey=t=>{var r;return(r=n.pick(t))==null?void 0:r.key},n}var G=(e="\u8BF7\u7A0D\u5019",n=10,t={})=>{t=Object.assign({},{hasMask:!1,maskColor:"#00000070",onCancel:null,cancelInline:!1,id:"com_global_page_loading"},t);let{id:s,hasMask:c,maskColor:l,onCancel:d,cancelInline:w}=t,x=`_${s}_timeout`;window[x]&&clearTimeout(window[x]);let u=document.getElementById(s);u||(u=document.createElement("div"),u.id=s,u.className=s,document.body.append(u));let a=`${s}_style`;if(!document.getElementById(a)){let i=document.createElement("style");i.id=a,i.innerHTML=`
|
|
2
|
+
.${s} {
|
|
3
|
+
position: fixed;
|
|
4
|
+
left: 0;
|
|
5
|
+
top: 0;
|
|
6
|
+
width: 100vw;
|
|
7
|
+
height: 100vh;
|
|
8
|
+
display: flex;
|
|
9
|
+
justify-content: center;
|
|
10
|
+
align-items: center;
|
|
11
|
+
pointer-events: none;
|
|
12
|
+
z-index: 10000;
|
|
13
|
+
}
|
|
14
|
+
.${s}.show-mask {
|
|
15
|
+
pointer-events: unset;
|
|
16
|
+
background: #00000070;
|
|
17
|
+
}
|
|
18
|
+
.${s} .mask-wrapper {
|
|
19
|
+
position: fixed;
|
|
20
|
+
}
|
|
21
|
+
.${s} .loading-wrapper {
|
|
22
|
+
width: 120px;
|
|
23
|
+
height: 120px;
|
|
24
|
+
z-index: 8000;
|
|
25
|
+
background: rgba(0, 0, 0, 0.6);
|
|
26
|
+
border-radius: 8px;
|
|
27
|
+
text-align: center;
|
|
28
|
+
color: white;
|
|
29
|
+
display: flex;
|
|
30
|
+
justify-content: center;
|
|
31
|
+
flex-direction: column;
|
|
32
|
+
align-items: center;
|
|
33
|
+
pointer-events: initial;
|
|
34
|
+
line-height: 1.3;
|
|
35
|
+
}
|
|
36
|
+
.${s} .loading-wrapper img {
|
|
37
|
+
width: 50px;
|
|
38
|
+
height: 50px;
|
|
39
|
+
margin-bottom: 10px;
|
|
40
|
+
}
|
|
41
|
+
.${s} .loading-wrapper a {
|
|
42
|
+
color: #6ab2ff;
|
|
43
|
+
}`,document.head.appendChild(i)}if(u.innerHTML=`
|
|
44
|
+
<div class="loading-wrapper">
|
|
45
|
+
<img src="https://img.alicdn.com/tfs/TB1bnUsQBLoK1RjSZFuXXXn0XXa-32-32.svg" alt="\u52A0\u8F7D\u4E2D">
|
|
46
|
+
<div>
|
|
47
|
+
<span>${e}</span>
|
|
48
|
+
${w?"":"<br />"}
|
|
49
|
+
${d?'<a href="javascript:;" class="cancel">\u53D6\u6D88</a>':""}
|
|
50
|
+
</div>
|
|
51
|
+
</div>`,d){let i=u.querySelector(".cancel");i&&i.addEventListener("click",()=>{M(),d()})}u.addEventListener("click",()=>{M()}),u.style.display="flex",u.style.background=c?l:"transparent",u.className=`${s} ${c?"show-mask":""}`,n>0&&(window[x]=setTimeout(()=>{M()},n*1e3))},M=()=>{let n=document.getElementById("com_global_page_loading");n&&(n.style.display="none")};function Q(e,n){!n&&window!==window.parent&&(n=window.parent),!n&&window.opener&&(n=window.opener);let t=new Map,r=new Map,s=()=>Math.random().toString(36).substring(2),c={},l="_local_function_";function d(a){let i=`${l}${s()}`;return c[i]=a,i}let w=(a,i)=>(a==null?void 0:a.map(g=>{if(typeof g=="object")for(let k in g)g[k]=i(g[k]);return i(g)}))||[];function x(a,...i){if(!n){console.warn("TargetWindow is null.");return}return new Promise((g,k)=>{let f=s();t.set(f,{resolve:g,reject:k}),n.postMessage({scene:e,type:"event",eventName:a,payload:w(i,y=>typeof y=="function"?d(y):y),callbackId:f},"*")})}window.addEventListener("message",async a=>{if(!a.data||a.data.scene!==e)return;n=a.source;let{type:i,eventName:g,payload:k,callbackId:f}=a.data;if(i==="event"){let y=w(k,m=>{if(typeof m=="string"&&m.startsWith(l)){let p=`getFn_${m}`;return(...b)=>x("executeLocalFunction",p,...b)}return m}),h=r.get(g)||[],v=r.get("*")||[];try{let m=await Promise.all(h.map(b=>Promise.resolve(b(...y)))),p=await Promise.all(v.map(b=>Promise.resolve(b(g,...y))));if(f){let b=m[m.length-1]||p[p.length-1];if(!h.length&&!b)return;n.postMessage({scene:e,type:"callback",callbackId:f,payload:b},"*")}}catch(m){console.error(m),f&&n.postMessage({scene:e,type:"callback",callbackId:f,error:m||"unknown error"},"*")}}else if(i==="callback"&&f){let y=t.get(f);y&&(a.data.error?y.reject(a.data.error):y.resolve(a.data.payload),t.delete(f))}});function u(a,i){r.has(a)||r.set(a,[]),r.get(a).push(i)}return u("executeLocalFunction",(a,...i)=>{if(a=(a==null?void 0:a.replace("getFn_",""))||"",!c[a])throw new Error(`\u672A\u627E\u5230\u672C\u5730\u7F13\u5B58\u65B9\u6CD5\uFF1A${a}`);return c[a](...i)}),x("auto-connect"),{postMessage:x,onMessage:u}}var W=e=>!e||typeof e!="object"?e:JSON.parse(JSON.stringify(e)),D=e=>{if(typeof e=="string"){let n=document.createElement("div");return n.innerText=e,n.innerHTML}else if(typeof e=="object"&&e)for(let n in e)e[n]=D(e[n]);return e},_=e=>{if(typeof e=="string"){let n=document.createElement("div");return n.innerHTML=e,n.innerText}else if(typeof e=="object"&&e)for(let n in e)e[n]=_(e[n]);return e},ee=(e,n,t)=>{if(!e)throw new Error("text can not be empty.");return n=n||(r=>console.error(`\u590D\u5236\u5230\u526A\u8D34\u677F\u5931\u8D25\uFF1A${r||""}`)),navigator.clipboard&&!t?navigator.clipboard.writeText(e).catch(r=>{throw n(r.message),r}):new Promise((r,s)=>{let c=document.createElement("input");c.value=e,c.style.cssText="position:fixed;left:0;top:0;opacity:0;",document.body.appendChild(c),c.select();try{if(document.execCommand("copy"))r();else{let l="Failed to execute 'document.execCommand'.";n(l),s(new Error(l))}}catch(l){n(l.message),s(l)}finally{document.body.removeChild(c)}})},F=e=>{if(!e||e.length<17)throw new Error("\u4F20\u5165\u7684\u8EAB\u4EFD\u8BC1\u53F7\u957F\u5EA6\u5FC5\u987B>=17");let n=[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2],t=["1","0","X","9","8","7","6","5","4","3","2"],r=0;for(let s=0;s<17;s++)r+=parseInt(e.charAt(s),10)*n[s];return t[r%11]},ne=e=>!e||e.length!==18?(console.error("\u8EAB\u4EFD\u8BC1\u53F7\u4E0D\u662F18\u4F4D\uFF01"),!1):`${F(e)}`===e.charAt(17),te=(()=>{let e={backspace:8,tab:9,clear:12,enter:13,shift:16,ctrl:17,alt:18,esc:27,space:32,pageup:33,pagedown:34,end:35,home:36,left:37,up:38,right:39,down:40,insert:45,delete:46};for(let n=48;n<=57;n++)e[String.fromCharCode(n)]=n;for(let n=65;n<=90;n++)e[String.fromCharCode(n).toLowerCase()]=n;for(let n=96;n<=105;n++)e[`num${n-96}`]=n;for(let n=112;n<=123;n++)e[`f${n-111}`]=n;return e})();var E=(e,n=location.search)=>(new RegExp(`(^|\\?|&)${e}=(.*?)(?=&|#|$)`,"g").exec(n)||[])[2],re=(e,n=location.search)=>parseInt(E(e,n)||"0",10),se=(e=location.search)=>{let n=((e||"").split("?").pop()||"").split("#")[0]||"",t={};return n.split("&").map(r=>r.split("=")).forEach(([r,s])=>{t[r]=s||""}),t},oe=(e,n,t)=>{if(t=t||`${location.pathname}${location.search}`,E(e,t)!==void 0)return t.replace(new RegExp(`(^|\\?|&)${e}=(.*?)(?=&|#|$)`,"g"),`$1${e}=${n}`);let[r,s]=t.split("#");return`${r}${r.indexOf("?")<0?"?":"&"}${e}=${n}${s?"#":""}${s||""}`},ae=(e,n)=>(n=n||`${location.pathname}${location.search}`,n.replace(new RegExp(`(^|\\?|&)${e}=.*?(&|#|$)`,"g"),(t,r,s)=>s==="&"?r:s)),T=e=>Object.keys(e||{}).filter(n=>e[n]!==void 0).map(n=>{let t=typeof e[n]=="object"?JSON.stringify(e[n]):e[n];return`${encodeURIComponent(n)}=${encodeURIComponent(t)}`}).join("&");var C=(e,n)=>{let t=Object.assign({},(e==null?void 0:e.headers)||{},(n==null?void 0:n.headers)||{}),r=Object.assign({},(e==null?void 0:e.fetchOptions)||{},(n==null?void 0:n.fetchOptions)||{});return Object.assign({},e||{},n||{},{headers:t,fetchOptions:r})},S=class extends Error{constructor(n,t){super(n),Object.assign(this,t||{})}},R=async(e,n)=>{var b,q;n=C({errorMessage:"\u7CFB\u7EDF\u7E41\u5FD9\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",errorHandler:o=>{var $;throw!(n!=null&&n.silent)&&o&&(($=n==null?void 0:n.toastHandler)==null||$.call(n,o)),new Error(o)},baseUrl:"",headers:{},fetchOptions:{credentials:"include"},checkSuccess:o=>(o==null?void 0:o.code)==0||(o==null?void 0:o.code)==200,toastHandler:o=>console.error(`[\u60A8\u8FD8\u6CA1\u6709\u914D\u7F6EtoastHandler\uFF0C\u8BF7\u6839\u636E\u60A8\u7684UI\u7EC4\u4EF6\u5E93\u914D\u7F6E\u5408\u9002\u7684\u63D0\u793A\u65B9\u6CD5] ${o||""}`),onFetchResponse:o=>{if(o.status===200)return o.json();throw new S(o.statusText,{response:P(O({},o),{code:o.status,message:o.statusText,isHttpResponse:!0})})}},n);let{params:r,data:s,formData:c,json:l,method:d,headers:w,baseUrl:x,fetchOptions:u,checkSuccess:a,afterRequest:i,errorHandler:g,errorMessage:k,responseConverter:f,onFetchResponse:y,setLoading:h,overrideMessage:v}=n||{},m=(n==null?void 0:n.defaultErrorMessage)||k;if(u.headers=O(O({},w||{}),u.headers||{}),r&&(u.method=d||"GET",e=`${e}${e.indexOf("?")>=0?"&":"?"}${T(r)}`),s)Object.assign(u,{method:d||"POST",body:T(s),headers:O({"Content-Type":"application/x-www-form-urlencoded;charset=utf-8"},u.headers||{})});else if(c){let o=c;if(!(c instanceof FormData)){o=new FormData;for(let $ in c)o.append($,c[$])}Object.assign(u,{method:d||"POST",body:o})}else l&&Object.assign(u,{method:d||"POST",body:JSON.stringify(l),headers:O({"Content-Type":"application/json;charset=utf-8"},u.headers||{})});let p=null;h==null||h(!0);try{let o=`${/^(http|\/\/)/g.test(e)?"":x||""}${e}`;o.indexOf("//")===0&&location.protocol==="blob:"&&(o=`${(b=location.pathname.split(":"))==null?void 0:b[0]}:${o}`),p=await fetch(o,u).then(y)}catch(o){console.error(o),h==null||h(!1),i==null||i(!1,o.response);let $=typeof v=="function"?v(o.response):v;g==null||g($!=null?$:((q=o.response)==null?void 0:q.message)||m,o.response,n);return}if(h==null||h(!1),p=f?f(p):p,a!=null&&a(p))return i==null||i(!0,p),p.data;{i==null||i(!1,p);let o=typeof v=="function"?v(p):v;g==null||g(o!=null?o:p.message||m,p,n);return}},U=function(e){let n=C(this.overrideDefaultOptions,e),t=(r,s)=>R(r,C(n,s));return t.overrideDefaultOptions=n,t.create=U.bind(t),t};R.create=U.bind(R);var ie=function(e,n){let t=n;return n||(t=e,e=R),(r,s)=>e(r,O(O({},t||{}),s||{}))};var ce=(e,n)=>{if(!e)return"";if(typeof e=="number")e=new Date(e);else if(typeof e=="string")if(/^\d{12,13}$/g.test(e))e=new Date(parseInt(e,10));else if(/^.{10}T.{8,12}Z?$/g.test(e))e=new Date(e);else return e;if(!(e instanceof Date))throw new Error("formatDate error: not date.");if(isNaN(e==null?void 0:e.getFullYear()))throw new Error("formatDate error: invalid date.");n=n||"yyyy-MM-dd HH:mm:ss";let t={y:e.getFullYear(),M:e.getMonth()+1,d:e.getDate(),q:Math.floor((e.getMonth()+3)/3),w:e.getDay(),H:e.getHours(),h:e.getHours()%12===0?12:e.getHours()%12,m:e.getMinutes(),s:e.getSeconds(),S:e.getMilliseconds()},r=["\u5929","\u4E00","\u4E8C","\u4E09","\u56DB","\u4E94","\u516D"];for(let s in t)n=n.replace(new RegExp(`${s}+`,"g"),c=>{let l=`${t[s]}`;if(s==="w")return`${c.length>2?"\u661F\u671F":"\u5468"}${r[l]}`;for(let d=0,w=l.length;d<c.length-w;d++)l=`0${l}`;return c.length===1?l:l.substring(l.length-c.length)});return n},le=(e,n)=>{n=n||"yyyy-MM-dd";let t={y:0,M:1,d:0,H:0,h:0,m:0,s:0,S:0};n.replace(/([^yMdHmsS]*?)(([yMdHmsS])\3*)([^yMdHmsS]*?)/g,(s,c,l,d,w)=>(e=e.replace(new RegExp(`${c}(\\d{${l.length}})${w}`),(x,u)=>(t[d]=parseInt(u,10),"")),"")),t.M--;let r=new Date(t.y,t.M,t.d,t.H,t.m,t.s);return t.S!==0&&r.setMilliseconds(t.S),r},ue=e=>new Promise(n=>setTimeout(n,e||0));var de=(json,indent,leftBracesInSameLine)=>{function getIndentStr(e){let n="";for(let t=0;t<e;t++)n+=indent||" ";return n}function format(e,n){n=n===void 0?0:n;let t="";if(typeof e=="object"&&e!=null){let r=e instanceof Array,s=0;t+=`${r?"[":"{"}
|
|
52
|
+
`;for(let c in e){t+=s++>0?`,
|
|
53
|
+
`:"";let l=typeof e[c]=="object"&&e[c]!=null,d=getIndentStr(n+1);t+=r&&l?"":d,t+=r?"":`"${c}": ${l&&!leftBracesInSameLine?`
|
|
54
|
+
`:""}`,t+=!l||l&&leftBracesInSameLine&&!r?"":d,t+=format(e[c],n+1)}t+=`
|
|
55
|
+
${getIndentStr(n)}${r?"]":"}"}`}else{let r=typeof e=="string"?'"':"";t+=`${r}${e}${r}`}return t}return format(eval(`(${json})`))},A=(e,n)=>typeof e=="number"?(typeof n=="undefined"&&(n=e,e=0),e+Math.floor(Math.random()*(n-e))):e instanceof Array?typeof n=="undefined"?e.length===0?null:e.length===1?e[0]:e[Math.floor(Math.random()*e.length)]:(e.sort(()=>Math.random()>.5?1:-1),e.slice(0,n)):Math.random(),ge=(e,n)=>{e=e||18;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz0123456789".split("");n==="number"&&(t="0123456789".split(""));let r="";for(let s=0;s<e;s++)r+=A(t);return r},pe=(e,n)=>e.replace(/([A-Z])/g,(t,r)=>`${n||"_"}${r.toLowerCase()}`),fe=(e,n)=>e.replace(new RegExp(`${n||"_"}(\\w)`,"g"),(t,r)=>r.toUpperCase());return z(me);})();
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
type EnumItem<K extends string, V extends string | number> = {
|
|
2
|
+
label: string;
|
|
3
|
+
value: V;
|
|
4
|
+
key: K;
|
|
5
|
+
[key: string]: any;
|
|
6
|
+
};
|
|
7
|
+
type EnumType<T extends ReadonlyArray<EnumItem<string, string | number>>> = T & {
|
|
8
|
+
[K in T[number]['key']]: Extract<T[number], {
|
|
9
|
+
key: K;
|
|
10
|
+
}>['value'];
|
|
11
|
+
} & {
|
|
12
|
+
pick: (keyOrValue: string | number) => T[number] | undefined;
|
|
13
|
+
pickLabel: (keyOrValue: string | number) => T[number]['label'] | undefined;
|
|
14
|
+
pickValue: (keyOrValue: string | number) => T[number]['value'] | undefined;
|
|
15
|
+
pickKey: (keyOrValue: string | number) => T[number]['key'] | undefined;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* 创建一个枚举,支持多种高级用法:
|
|
19
|
+
* const enums = createEnum([{ key: 'MAN', label: '男', value: 1 }])
|
|
20
|
+
* console.log(enums.MAN) // 1
|
|
21
|
+
* console.log(enums.pick('MAN')) // 对象
|
|
22
|
+
* console.log(enums.pick(1)) // 对象
|
|
23
|
+
* console.log(enums.pickLabel('MAN')) // 男
|
|
24
|
+
* console.log(enums.pickValue('MAN')) // 1
|
|
25
|
+
* console.log(enums) // 数组对象
|
|
26
|
+
* @param items
|
|
27
|
+
* @returns
|
|
28
|
+
*/
|
|
29
|
+
export declare function createEnum<T extends ReadonlyArray<EnumItem<string, string | number>>>(items: T): EnumType<T>;
|
|
30
|
+
export {};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** showLoading配置 */
|
|
2
|
+
export interface IShowLoadingConfig {
|
|
3
|
+
hasMask?: boolean;
|
|
4
|
+
maskColor?: string;
|
|
5
|
+
cancelInline?: boolean;
|
|
6
|
+
onCancel?: Function;
|
|
7
|
+
id?: string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* 显示全局loading,不依赖任何框架
|
|
11
|
+
* @param {*} text 提示文案
|
|
12
|
+
* @param {*} seconds 超时自动关闭时间,单位秒
|
|
13
|
+
* @param {*} options 可选配置
|
|
14
|
+
*/
|
|
15
|
+
export declare const showLoading: (text?: string, seconds?: number, config?: IShowLoadingConfig) => void;
|
|
16
|
+
/**
|
|
17
|
+
* 主动关闭loading提示
|
|
18
|
+
*/
|
|
19
|
+
export declare const hideLoading: () => void;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
type onMessageListener = (eventName?: string, ...payload: any[]) => Promise<any> | any;
|
|
2
|
+
/**
|
|
3
|
+
* 初始化窗口通信
|
|
4
|
+
* @param {string} scene 场景,必传,互相通信的2个窗口必须保证 scene 相同
|
|
5
|
+
* @param {Window} targetWindow 目标窗口对象(父窗口或子窗口),互相通信时允许有一方不传,自动从 event.source 获取
|
|
6
|
+
* @returns {{postMessage: function, onMessage: function}} 返回postMessage和onMessage方法
|
|
7
|
+
*/
|
|
8
|
+
export declare function initWindowMessage(scene: string, targetWindow?: Window): {
|
|
9
|
+
postMessage: <T>(eventName: string, ...payload: any[]) => Promise<T> | void;
|
|
10
|
+
onMessage: (eventName: string, listener: onMessageListener) => void;
|
|
11
|
+
};
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 基于JSON的简单深拷贝
|
|
3
|
+
* @param obj 要复制的对象,非对象格式会直接返回
|
|
4
|
+
* @returns
|
|
5
|
+
*/
|
|
6
|
+
export declare const deepCopy: (obj: any) => any;
|
|
7
|
+
/**
|
|
8
|
+
* HTML编码,例如将 【"】 变成 【"】
|
|
9
|
+
* @param {*} html 待编码的原始字符串,如果传入对象会遍历处理
|
|
10
|
+
* @returns
|
|
11
|
+
*/
|
|
12
|
+
export declare const encodeHtml: (html: string | any) => any;
|
|
13
|
+
/**
|
|
14
|
+
* HTML解码,例如将 【"】 变成 【"】
|
|
15
|
+
* @param {*} html 已经被HTML编码过的字符串,如果传入对象会遍历处理
|
|
16
|
+
* @returns
|
|
17
|
+
*/
|
|
18
|
+
export declare const decodeHtml: (html: string | any) => any;
|
|
19
|
+
/**
|
|
20
|
+
* 复制一段文本到剪贴板,如果失败会抛出异常,推荐使用姿势:
|
|
21
|
+
* await copyTextToClipboard('要复制的文本', message => alert(`复制到剪贴板失败:${message}`));
|
|
22
|
+
* alert('复制到剪贴板成功!');
|
|
23
|
+
* @param {*} text 要复制的文本
|
|
24
|
+
* @param {*} onFailure 失败回调,接受一个 message 参数
|
|
25
|
+
* @param {*} supportSilent 是否支持后台静默复制,如果是则优先采用 execCommand
|
|
26
|
+
* @returns
|
|
27
|
+
*/
|
|
28
|
+
export declare const copyToClipboard: (text: string, onFailure: (message: string) => void, supportSilent: boolean) => Promise<void>;
|
|
29
|
+
/**
|
|
30
|
+
* 获取身份证号第18位校验码
|
|
31
|
+
* @params cid 身份证号码,17或18位均可
|
|
32
|
+
*/
|
|
33
|
+
export declare const getIdCardLastChar: (cid: string) => string;
|
|
34
|
+
/**
|
|
35
|
+
* 检测某个身份证ID是否合法,包括长度和最后一位校验码检测
|
|
36
|
+
* @params cid 身份证号码,必须是18位
|
|
37
|
+
*/
|
|
38
|
+
export declare const validateIdCard: (cid: string) => boolean;
|
|
39
|
+
/**
|
|
40
|
+
* 键盘键值映射,如: keyCodes.ctrl == 17
|
|
41
|
+
*/
|
|
42
|
+
export declare const keyCodes: Record<string, number>;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 从URL中获取某个参数,如果不存在返回 undefined ,如果存在多个同名参数,返回第一个匹配值
|
|
3
|
+
* getParam('a', '?a=1&b=&c=3&c=33#abc') // '1'
|
|
4
|
+
* getParam('b', '?a=1&b=&c=3&c=33#abc') // ''
|
|
5
|
+
* getParam('c', '?a=1&b=&c=3&c=33#abc') // 3
|
|
6
|
+
* getParam('d', '?a=1&b=&c=3&c=33#abc') // undefined
|
|
7
|
+
* @param {*} name 参数名
|
|
8
|
+
* @param {*} url 要获取的URL,默认当前地址
|
|
9
|
+
*/
|
|
10
|
+
export declare const getParam: (name: string, url?: string) => string;
|
|
11
|
+
/**
|
|
12
|
+
* 从URL中获取int参数
|
|
13
|
+
* @param {*} name 参数名
|
|
14
|
+
* @param {*} url 要获取的URL,默认当前地址
|
|
15
|
+
*/
|
|
16
|
+
export declare const getParamInt: (name: string, url?: string) => number;
|
|
17
|
+
/**
|
|
18
|
+
* 获取某个URL的全部参数
|
|
19
|
+
* getParams('?a=1&b=2#cc') // {a: '1', b: '2'}
|
|
20
|
+
* @param url
|
|
21
|
+
* @returns 参数对象
|
|
22
|
+
*/
|
|
23
|
+
export declare const getParams: (url?: string) => any;
|
|
24
|
+
/**
|
|
25
|
+
* 给URL设置参数,如果已经存在,替换之,兼容hash存在的情况
|
|
26
|
+
* setParam('a', '123', '?a=1&b=2&a=3#d') // '?a=123&b=2&a=123#d'
|
|
27
|
+
* setParam('d', '444', '?a=1&b=2&a=3#d') // '?a=1&b=2&a=3&d=444#d'
|
|
28
|
+
* @param {Object} name 参数名
|
|
29
|
+
* @param {Object} value 参数值
|
|
30
|
+
* @param {Object} url 如果不传默认当前页面URL
|
|
31
|
+
*/
|
|
32
|
+
export declare const setParam: (name: string, value: string | number, url?: string) => string;
|
|
33
|
+
/**
|
|
34
|
+
* 删除URL中某个参数
|
|
35
|
+
* delParam('a', '?a=1&b=2&a=3#d') // '?b=2#d'
|
|
36
|
+
* delParam('b', '?a=1&b=2&a=3#d') // '?a=1&a=3#d'
|
|
37
|
+
* delParam('a', '?a=1#d') // '#d'
|
|
38
|
+
* @param name 参数名
|
|
39
|
+
* @param url 要删除的URL,默认当前页面URL
|
|
40
|
+
* @returns 处理完后的URL
|
|
41
|
+
*/
|
|
42
|
+
export declare const delParam: (name: string, url: string) => string;
|
|
43
|
+
/**
|
|
44
|
+
* 将一个普通对象转为 a=1&b=2 的URL格式,会自动过滤undefined的值
|
|
45
|
+
* @param data 一个普通对象,如果对象嵌对象则会被自动转为JSON
|
|
46
|
+
* @returns 返回类似 a=1&b=2 的字符串
|
|
47
|
+
*/
|
|
48
|
+
export declare const toUrlParams: (data: any) => string;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/** requestAPI的第二个参数类型 */
|
|
2
|
+
export interface IRequestOptions {
|
|
3
|
+
/** GET请求时传递的参数 */
|
|
4
|
+
params?: Record<string, any>;
|
|
5
|
+
/** POST请求时传递的参数 */
|
|
6
|
+
data?: Record<string, any>;
|
|
7
|
+
/** 采用formData模式请求,可以传入普通的对象,也可以传入标准的formData */
|
|
8
|
+
formData?: Record<string, any>;
|
|
9
|
+
/** postJson请求时传递的参数 */
|
|
10
|
+
json?: Record<string, any>;
|
|
11
|
+
/** API前缀,不传默认为空 */
|
|
12
|
+
baseUrl?: string;
|
|
13
|
+
/** 请求方法,绝大部分情况无需手动指定 */
|
|
14
|
+
method?: string;
|
|
15
|
+
/** headers */
|
|
16
|
+
headers?: Record<string, any>;
|
|
17
|
+
/** 其它自定义fetchOptions,优先级高于上面所有参数 */
|
|
18
|
+
fetchOptions?: RequestInit;
|
|
19
|
+
/** 请求完成之后触发的钩子,无论成功与否均会触发 */
|
|
20
|
+
afterRequest?: (success: boolean, resp?: any) => void;
|
|
21
|
+
/** 判断接口是否调用成功,默认规则 resp => resp.code == 0 || resp.code == 200 */
|
|
22
|
+
checkSuccess?: (resp: any) => boolean;
|
|
23
|
+
/** 对响应进行自定义格式化处理,包含 checkSuccess 全部能力 */
|
|
24
|
+
responseConverter?: (resp: any) => any;
|
|
25
|
+
/** @deprecated 后端未返回 message 时的默认异常文案,由于名称经常引发歧义,估改名为 defaultErrorMessage */
|
|
26
|
+
errorMessage?: string;
|
|
27
|
+
/** 后端未返回 message 时的默认异常文案 */
|
|
28
|
+
defaultErrorMessage?: string;
|
|
29
|
+
/** 发生异常时的处理方法,一般不太建议重写此方法 */
|
|
30
|
+
errorHandler?: (message: string, resp: any, options: IRequestOptions) => void;
|
|
31
|
+
/** 自定义toast实现,为了和UI解耦,方法默认不包含UI处理代码 */
|
|
32
|
+
toastHandler?: (message: string) => void;
|
|
33
|
+
/** 是否关闭默认的异常toast */
|
|
34
|
+
silent?: boolean;
|
|
35
|
+
/** 自定义 fetch.then() ,非常底层的一个方法,非必要请勿使用 */
|
|
36
|
+
onFetchResponse?: (response: Response) => any;
|
|
37
|
+
/** 切换loading状态的方法,会在开始请求前置为true,结束时置为false。为什么设计这个方法?在非hooks场景下更方便的切换loading状态 */
|
|
38
|
+
setLoading?: (loading?: boolean) => void;
|
|
39
|
+
/** 覆盖默认的 resp.message 自定义异常抛出文案,也支持传入方法,注意返回''和undefined效果不同 */
|
|
40
|
+
overrideMessage?: string | ((resp: any) => string);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* 通用的API请求方法
|
|
44
|
+
* @param url
|
|
45
|
+
* @param options
|
|
46
|
+
* @returns
|
|
47
|
+
*/
|
|
48
|
+
declare const request: {
|
|
49
|
+
<T = any>(url: string, options?: IRequestOptions): Promise<T>;
|
|
50
|
+
create: any;
|
|
51
|
+
};
|
|
52
|
+
export { request };
|
|
53
|
+
type IRequest = typeof request;
|
|
54
|
+
interface RequestConstructor {
|
|
55
|
+
new (overrideOptions: IRequestOptions): IRequest;
|
|
56
|
+
new (req: IRequest, overrideOptions: IRequestOptions): IRequest;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* 支持实例化一个新的request方法,覆盖默认的部分配置项
|
|
60
|
+
* @deprecated 推荐使用 request.create() 实例化新的request
|
|
61
|
+
*/
|
|
62
|
+
export declare const Request: RequestConstructor;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 格式化一段JSON字符串,支持解析非标准JSON
|
|
3
|
+
* 不同于绝大多数格式化工具,本方法支持设置缩进方式以及左大括号是否换行
|
|
4
|
+
* @start 2016-08-24
|
|
5
|
+
* @param {Object} json 要格式化的json串
|
|
6
|
+
* @param {Object} indent 缩进方式,可以是若干个空格和tab,默认tab缩进,如 2个空格:" "、4个空格:" "、tab:" "
|
|
7
|
+
* @param {Object} leftBracesInSameLine 左大括号是否保持在同一行,默认 false
|
|
8
|
+
*/
|
|
9
|
+
export declare const formatJson: (json: string, indent?: string, leftBracesInSameLine?: boolean) => string;
|
|
10
|
+
/**
|
|
11
|
+
* 获取各种随机数,支持如下几种调用方式:
|
|
12
|
+
* getRandom() 返回0-1的随机小数,等同于Math.random(),0 <= result < 1
|
|
13
|
+
* getRandom(start, end) 返回start-end的随机整数,start <= result < end
|
|
14
|
+
* getRandom(end) 返回0-end的随机整数,0 <= result < end
|
|
15
|
+
* getRandom(array) 随机返回数组中的某一个内容
|
|
16
|
+
* getRandom(array, count) 随机从数组中返回长度为count的不重复内容组成的新数组,如果不足count个,返回全部 并乱序
|
|
17
|
+
* @param {Object} start
|
|
18
|
+
* @param {Object} end
|
|
19
|
+
* @return {Object}
|
|
20
|
+
*/
|
|
21
|
+
export declare const getRandom: (start?: any, end?: any) => any;
|
|
22
|
+
/**
|
|
23
|
+
* 获取随机字符串
|
|
24
|
+
* @param length 字符串长度
|
|
25
|
+
* @param type all 表示所有,number表示仅数字,默认所有
|
|
26
|
+
* @return string
|
|
27
|
+
*/
|
|
28
|
+
export declare const getRandomStr: (length: number, type?: "number" | "all") => string;
|
|
29
|
+
/**
|
|
30
|
+
* 字符串转下划线形式,示例:getParam 转 get_param
|
|
31
|
+
* @param str 要转换的字符串
|
|
32
|
+
* @param flag 默认下划线-,也可以传其它字符
|
|
33
|
+
*/
|
|
34
|
+
export declare const toUnderline: (str: string, flag?: string) => string;
|
|
35
|
+
/**
|
|
36
|
+
* 字符串转驼峰形式
|
|
37
|
+
* 示例一: toHump('get_param'),返回getParam
|
|
38
|
+
* 示例二: toHump('font-size','-'),返回fontSize
|
|
39
|
+
* @param str
|
|
40
|
+
* @param 分割的标志,默认为“_”
|
|
41
|
+
*/
|
|
42
|
+
export declare const toHump: (str: string, flag?: string) => string;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 将日期格式化成指定格式的字符串
|
|
3
|
+
* @param date 要格式化的日期,不传时默认当前时间,也可以是一个时间戳等
|
|
4
|
+
* @param fmt 目标字符串格式,支持的字符有:y,M,d,q,w,H,h,m,S,默认:yyyy-MM-dd HH:mm:ss
|
|
5
|
+
* @returns 返回格式化后的日期字符串
|
|
6
|
+
*/
|
|
7
|
+
export declare const formatDate: (date?: Date | number | string, fmt?: string) => string;
|
|
8
|
+
/**
|
|
9
|
+
* 将字符串解析成日期
|
|
10
|
+
* @param str 输入的日期字符串,如'2014-09-13'
|
|
11
|
+
* @param fmt 字符串格式,默认'yyyy-MM-dd',支持如下:y、M、d、H、m、s、S,不支持w和q
|
|
12
|
+
* @returns 解析后的Date类型日期
|
|
13
|
+
*/
|
|
14
|
+
export declare const parseDate: (str: string, fmt?: string) => Date;
|
|
15
|
+
/**
|
|
16
|
+
* 休息一段时间,单位毫秒
|
|
17
|
+
* 示例:await sleep(200); // 休息200毫秒
|
|
18
|
+
* @param ms 要休息的时间,单位毫秒,不传默认0
|
|
19
|
+
* @returns
|
|
20
|
+
*/
|
|
21
|
+
export declare const sleep: (ms?: number) => Promise<unknown>;
|
package/package.json
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "youtil",
|
|
3
|
-
"version": "3.1.0-
|
|
3
|
+
"version": "3.1.0-beta3",
|
|
4
4
|
"description": "油梯,一个与框架、环境无关的小巧、精简、实用的JavaScript工具库",
|
|
5
5
|
"files": [
|
|
6
6
|
"es",
|
|
7
7
|
"esm",
|
|
8
8
|
"cjs",
|
|
9
9
|
"docs",
|
|
10
|
-
"umd"
|
|
10
|
+
"umd",
|
|
11
|
+
"dist"
|
|
11
12
|
],
|
|
12
13
|
"main": "dist/index.mjs",
|
|
13
14
|
"module": "dist/index.mjs",
|