@nano-lib/util 1.0.5

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 @nanofe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,8 @@
1
+ declare const dateFormats: readonly [readonly ["date", "YYYY-MM-DD"], readonly ["daterange", "YYYY-MM-DD"], readonly ["datetime", "YYYY-MM-DD HH:mm:ss"], readonly ["datetimerange", "YYYY-MM-DD HH:mm:ss"], readonly ["month", "YYYY-MM"], readonly ["monthrange", "YYYY-MM"], readonly ["year", "YYYY"], readonly ["yearrange", "YYYY"], readonly ["time", "HH:mm:ss"]];
2
+ export type DateFormat = (typeof dateFormats)[number][1];
3
+ export declare const DATE_VALUE_FORMAT: Map<string, DateFormat>;
4
+ export declare const IMAGE_TYPE: string[];
5
+ export declare const MEDIA_TYPE: string[];
6
+ export declare const DOC_TYPE: string[];
7
+ export declare const FILE_TYPE: string[];
8
+ export {};
package/lib/index.d.ts ADDED
@@ -0,0 +1,93 @@
1
+ import { default as scrollTo } from './utils/scroll';
2
+ import { debounce, creatCancelTask, downloadFile, getGenderByIdNumber, getBirthdayByIdNumber, trimArray } from './utils/common';
3
+ import { uuid, randomNum } from './utils/random';
4
+ import { phoneToAsterisk, idNumberToAsterisk, firstLetterToUpperCase, firstLetterToLowerCase } from './utils/string';
5
+ import { parseTime, getTimeDistance, getDayRange } from './utils/date';
6
+ import { addClass, removeClass, hasClass, toggleClass, noContextmenu, useRafThrottle } from './utils/element';
7
+ import { encodeURIToParams, paramsToQueryString, queryStringToParams, errorCodeToString, YNToString, HNToString, valueToLabel, chargeToLabel, cascaderToLabel, multipleSelectToLabel } from './utils/to';
8
+ import { validHttp, validExternal, validString, validNumberStr, validEmptyObject, validURL, validPassword, validEmail, validIdNumber, validPhone, validTel } from './utils/valid';
9
+ export declare const constants: {
10
+ DATE_VALUE_FORMAT: Map<string, "YYYY-MM-DD HH:mm:ss" | "YYYY-MM-DD" | "YYYY-MM" | "YYYY" | "HH:mm:ss">;
11
+ IMAGE_TYPE: string[];
12
+ MEDIA_TYPE: string[];
13
+ DOC_TYPE: string[];
14
+ FILE_TYPE: string[];
15
+ };
16
+ export declare const commonUtil: {
17
+ NOOP: () => void;
18
+ debounce: typeof debounce;
19
+ creatCancelTask: typeof creatCancelTask;
20
+ downloadFile: typeof downloadFile;
21
+ trimArray: typeof trimArray;
22
+ getFullUrl: (relativeUrl: string, domain?: string) => string;
23
+ getArrayFullUrl: (relativeUrls: string | string[], domain?: string) => string[];
24
+ getGenderByIdNumber: typeof getGenderByIdNumber;
25
+ getBirthdayByIdNumber: typeof getBirthdayByIdNumber;
26
+ };
27
+ export declare const toUtil: {
28
+ encodeURIToParams: typeof encodeURIToParams;
29
+ paramsToQueryString: typeof paramsToQueryString;
30
+ queryStringToParams: typeof queryStringToParams;
31
+ errorCodeToString: typeof errorCodeToString;
32
+ YNToString: typeof YNToString;
33
+ HNToString: typeof HNToString;
34
+ valueToLabel: typeof valueToLabel;
35
+ chargeToLabel: typeof chargeToLabel;
36
+ cascaderToLabel: typeof cascaderToLabel;
37
+ multipleSelectToLabel: typeof multipleSelectToLabel;
38
+ };
39
+ export declare const validUtil: {
40
+ validHttp: typeof validHttp;
41
+ validExternal: typeof validExternal;
42
+ validString: typeof validString;
43
+ validNumberStr: typeof validNumberStr;
44
+ validEmptyObject: typeof validEmptyObject;
45
+ validURL: typeof validURL;
46
+ validPassword: typeof validPassword;
47
+ validEmail: typeof validEmail;
48
+ validIdNumber: typeof validIdNumber;
49
+ validPhone: typeof validPhone;
50
+ validTel: typeof validTel;
51
+ };
52
+ export declare const elementUtil: {
53
+ scrollTo: typeof scrollTo;
54
+ addClass: typeof addClass;
55
+ removeClass: typeof removeClass;
56
+ hasClass: typeof hasClass;
57
+ toggleClass: typeof toggleClass;
58
+ noContextmenu: typeof noContextmenu;
59
+ useRafThrottle: typeof useRafThrottle;
60
+ };
61
+ export declare const cacheUtil: {
62
+ local: {
63
+ set(key: string, value: string): void;
64
+ get(key: string): string | null;
65
+ setJSON(key: string, jsonValue: import('./types').AnyObj): void;
66
+ getJSON(key: string): import('./types').AnyObj | null;
67
+ remove(key: string): void;
68
+ clear(): void;
69
+ };
70
+ session: {
71
+ set(key: string, value: string): void;
72
+ get(key: string): string | null;
73
+ setJSON(key: string, jsonValue: import('./types').AnyObj): void;
74
+ getJSON(key: string): import('./types').AnyObj | null;
75
+ remove(key: string): void;
76
+ clear(): void;
77
+ };
78
+ };
79
+ export declare const randomUtil: {
80
+ uuid: typeof uuid;
81
+ randomNum: typeof randomNum;
82
+ };
83
+ export declare const stringUtil: {
84
+ phoneToAsterisk: typeof phoneToAsterisk;
85
+ idNumberToAsterisk: typeof idNumberToAsterisk;
86
+ firstLetterToUpperCase: typeof firstLetterToUpperCase;
87
+ firstLetterToLowerCase: typeof firstLetterToLowerCase;
88
+ };
89
+ export declare const dateUtil: {
90
+ parseTime: typeof parseTime;
91
+ getTimeDistance: typeof getTimeDistance;
92
+ getDayRange: typeof getDayRange;
93
+ };
package/lib/index.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=(t,e,n,r)=>(t/=r/2,t<1?n/2*t*t+e:(t--,-n/2*(t*(t-2)-1)+e)),A=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.msRequestAnimationFrame||(t=>window.setTimeout(t,1e3/60));function $(t,e){if(e){document.querySelector(e).scrollTop=t;return}document.documentElement.scrollTop=t,document.body.parentNode.scrollTop=t,document.body.scrollTop=t}function M(t){return t?document.querySelector(t).scrollTop:document.documentElement.scrollTop||document.body.parentNode.scrollTop||document.body.scrollTop}function D(t){const{target:e,to:n=0,duration:r=500,callback:o}=t??{},s=M(e),i=n-s,c=20;let a=0;const u=function(){a+=c;const l=I(a,s,i,r);$(l,e),a<r?A(u):o&&o()};u()}function E(t){return/^(http(s)?:\/\/)/.test(t)}function O(t){return/^(https?:|mailto:|tel:)/.test(t)}function R(t){return Object.prototype.toString.call(t)==="[object String]"}function x(t){return/^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(t)}function U(t){return!Object.keys(t).length}function C(t){return/^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/.test(t)}function v(t,e=8){return new RegExp(`^S*(?=S{${e}},})(?=S*d)(?=S*[A-Z])(?=S*[a-z])(?=S*[!@#$%^&*?])S*$`).test(t)}function P(t){return/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(t)}function g(t){return/^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/.test(t)}function H(t){return/^0\d{2,3}-?\d{7,8}$/.test(t)}function N(t){return/^1[3-9]\d{9}$/.test(t)}const d=()=>{};function z(t,e){let n=null;return function(...r){n!==null&&clearTimeout(n),n=setTimeout(()=>{t.apply(this,r),n=null},e)}}function F(t){if(!g(t))throw new Error("Please provide a valid ID number!");const e=t.length,n=e===15?t[e-1]:t[e-2];return parseInt(n)%2===1?"1":"2"}function L(t){if(!g(t))throw new Error("Please provide a valid ID number!");return t.substring(6,10)+"-"+t.substring(10,12)+"-"+t.substring(12,14)}const h=(t,e="")=>{e||(e=globalThis.location.origin);const n=new RegExp(/^http(s)?:\/\//),r=new RegExp(/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i);return n.test(t)||r.test(t)?t:e+t},q=(t,e="")=>{typeof t=="string"&&(t=t===""?[]:t.split(","));for(const n in t)t[n]=h(t[n],e);return t};function Z(t){let e=d;return(...n)=>new Promise((r,o)=>{e(),e=()=>{r=o=d},t(...n).then(s=>r(s),s=>o(s))})}function j(t,e){const n=document.createElement("a");n.download=e,n.href=t,n.click()}function S(t){const e=[];for(let n=0;n<t.length;n++)t[n]&&e.push(t[n]);return e}function k(t,e){switch(arguments.length){case 1:return parseInt((Math.random()*t+1).toString(),10);case 2:return parseInt((Math.random()*(e-t+1)+t).toString(),10);default:return 0}}function J(){let t="";const e=[];for(let n=0;n<=15;n++)e[n]=n.toString(16);for(let n=1;n<=36;n++)n===9||n===14||n===19||n===24?t+="-":n===15?t+=4:n===20?t+=e[Math.random()*4|8]:t+=e[Math.random()*16|0];return t}function _(t){return t?t.replace(/(\d{3})\d{4}(\d{4})/,"$1****$2"):""}function B(t,e,n){if(e??(e=4),n??(n=4),t){const r=t.length;return t.substring(0,e)+"*".repeat(r-e-n)+t.substring(r-n)}return""}function G(t){return t.replace(/( |^)[a-z]/g,e=>e.toUpperCase())}function Q(t){return t.replace(/( |^)[A-Z]/g,e=>e.toLowerCase())}function f(t,e){if(!t)return"-";t.toString().length===10&&(t=+t*1e3),e??(e="YYYY-MM-DD HH:mm:ss");const n=new Date(t),r=(i,c,a=" ")=>{if(i.length>=c)return i;const u=c-i.length;let l=Math.ceil(u/a.length);for(;l>>=1;)a+=a,l===1&&(a+=a);return a.slice(0,u)+i};let o;const s={"Y+":n.getFullYear().toString(),"M+":(n.getMonth()+1).toString(),"D+":n.getDate().toString(),"H+":n.getHours().toString(),"m+":n.getMinutes().toString(),"s+":n.getSeconds().toString()};for(const i in s)o=new RegExp("("+i+")").exec(e),o&&(e=e.replace(o[1],o[1].length==1?s[i]:r(s[i],o[1].length,"0")));return e}function X(t,e){`${t}`.length===10?t=parseInt(t+"")*1e3:t=+t;const n=new Date(t),o=(Date.now()-Number(n))/1e3;return o<30?"刚刚":o<3600?`${Math.ceil(o/60)}分钟前`:o<3600*24?`${Math.ceil(o/3600)}小时前`:o<3600*24*2?"1天前":e?f(t,e):`${n.getMonth()+1}月${n.getDate()}日${n.getHours()}时${n.getMinutes()}分`}function K(t){const e=t||new Date,n=new Date(e),r=new Date(e);return n.setHours(0,0,0),r.setHours(23,59,59),{dateRange:[f(n),f(r)],timestampRange:[n.getTime(),r.getTime()]}}const V={set(t,e){sessionStorage&&t&&e&&sessionStorage.setItem(t,e)},get(t){return!sessionStorage||!t?null:sessionStorage.getItem(t)},setJSON(t,e){e&&this.set(t,JSON.stringify(e))},getJSON(t){const e=this.get(t);return e?JSON.parse(e):null},remove(t){sessionStorage.removeItem(t)},clear(){sessionStorage.clear()}},W={set(t,e){localStorage&&t&&e&&localStorage.setItem(t,e)},get(t){return!localStorage||!t?null:localStorage.getItem(t)},setJSON(t,e){e&&this.set(t,JSON.stringify(e))},getJSON(t){const e=this.get(t);return e?JSON.parse(e):null},remove(t){localStorage.removeItem(t)},clear(){localStorage.clear()}};function tt(t,e){if(!t||!e)return;let n=t.className;const r=n.indexOf(e);r===-1?n+=`${e}`:n=n.substring(0,r)+n.substring(r+e.length),t.className=n}function p(t,e){return t.className.match(new RegExp("(?:\\s|^)"+e+"(?:\\s|$)"))}function et(t,e){p(t,e)||(t.className+=` ${e}`)}function nt(t,e){if(p(t,e)){const n=new RegExp("(?:\\s|^)"+e+"(?:\\s|$)");t.className=t.className.replace(n," ")}}function rt(t){let e=!1;return function(...n){e||(e=!0,window.requestAnimationFrame(()=>{t.apply(this,n),e=!1}))}}function ot(t){t&&(t.oncontextmenu=()=>!1)}function st(t){switch(t){case 400:return"请求失败!请您稍后重试";case 401:return"认证失败,无法访问系统资源";case 403:return"当前操作没有权限!";case 404:return"你所访问的资源不存在!";case 405:return"请求方式错误!请您稍后重试";case 408:return"请求超时!请您稍后重试";case 500:return"服务异常!";case 502:return"网关错误!";case 503:return"服务不可用!";case 504:return"网关超时!";default:return"系统未知错误,请反馈给管理员"}}function ct(t){switch(t){case"1":return"是";case"0":return"否";default:return"未填写"}}function it(t){switch(t){case"1":return"有";case"0":return"无";default:return"未填写"}}function at(t,e){const n=t.find(r=>r.value===e);return n?n.label:""}function ut(t,e,n){const r=[],o=e.split(","),s=n.split(",");return Array.from(new Set(o)).forEach(c=>{const a=t.find(u=>u.value===c);a&&s.forEach(u=>{var m;const l=(m=a.children)==null?void 0:m.find(y=>y.value===u);l&&r.push(l)})}),r.map(c=>c.label).join()}function w(t,e,n){var s;if(!e)return"";const r=e.split(","),o=n.find(i=>i.value===r[t]);return o?((s=o.children)!=null&&s.length&&w(t+1,e,o.children),o.label):""}function lt(t,e,n){if(!t)return"";const r=t.split(","),o=[],s=r.length-1,i=r.findIndex(c=>c===n);if(i!==-1){const c=r[s]===n;r.splice(c?0:i,c?s:1)}return r.forEach(c=>{const a=e.find(u=>u.value===c);a&&o.push(a)}),o.map(c=>c.label).join()}function ft(t){let e="";for(const n of Object.keys(t)){const r=t[n],o=`${encodeURIComponent(n)}=`;if(r!==null&&typeof r<"u")if(typeof r=="object"){for(const s of Object.keys(r))if(r[s]!==null&&typeof r[s]<"u"){const i=`${n}[${s}]`,c=`${encodeURIComponent(i)}=`;e+=`${c+encodeURIComponent(r[s])}&`}}else e+=`${o+encodeURIComponent(r)}&`}return e}function dt(t){return t?S(Object.keys(t).map(e=>t[e]===void 0?"":`${encodeURIComponent(e)}=${encodeURIComponent(t[e])}`)).join("&"):""}function gt(t){const e=decodeURIComponent(t.split("?")[1]).replace(/\+/g," ");if(!e)return{};const n={};return e.split("&").forEach(o=>{const s=o.indexOf("=");if(s!==-1){const i=o.substring(0,s),c=o.substring(s+1,o.length);n[i]=c}}),n}const pt=[["date","YYYY-MM-DD"],["daterange","YYYY-MM-DD"],["datetime","YYYY-MM-DD HH:mm:ss"],["datetimerange","YYYY-MM-DD HH:mm:ss"],["month","YYYY-MM"],["monthrange","YYYY-MM"],["year","YYYY"],["yearrange","YYYY"],["time","HH:mm:ss"]],mt=new Map(pt),Y=["jpg","jpeg","png","bmp","gif"],b=["mp3","mp4","webm","ogg","3gp"],T=["doc","docx","xls","xlsx","ppt","txt","pdf","zip"],ht=[...Y,...b,...T],St={DATE_VALUE_FORMAT:mt,IMAGE_TYPE:Y,MEDIA_TYPE:b,DOC_TYPE:T,FILE_TYPE:ht},wt={NOOP:d,debounce:z,creatCancelTask:Z,downloadFile:j,trimArray:S,getFullUrl:h,getArrayFullUrl:q,getGenderByIdNumber:F,getBirthdayByIdNumber:L},Yt={encodeURIToParams:ft,paramsToQueryString:dt,queryStringToParams:gt,errorCodeToString:st,YNToString:ct,HNToString:it,valueToLabel:at,chargeToLabel:ut,cascaderToLabel:w,multipleSelectToLabel:lt},bt={validHttp:E,validExternal:O,validString:R,validNumberStr:x,validEmptyObject:U,validURL:C,validPassword:v,validEmail:P,validIdNumber:g,validPhone:N,validTel:H},Tt={scrollTo:D,addClass:et,removeClass:nt,hasClass:p,toggleClass:tt,noContextmenu:ot,useRafThrottle:rt},yt={local:W,session:V},It={uuid:J,randomNum:k},At={phoneToAsterisk:_,idNumberToAsterisk:B,firstLetterToUpperCase:G,firstLetterToLowerCase:Q},$t={parseTime:f,getTimeDistance:X,getDayRange:K};exports.cacheUtil=yt;exports.commonUtil=wt;exports.constants=St;exports.dateUtil=$t;exports.elementUtil=Tt;exports.randomUtil=It;exports.stringUtil=At;exports.toUtil=Yt;exports.validUtil=bt;
package/lib/index.mjs ADDED
@@ -0,0 +1,416 @@
1
+ const I = (t, e, n, r) => (t /= r / 2, t < 1 ? n / 2 * t * t + e : (t--, -n / 2 * (t * (t - 2) - 1) + e)), A = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || ((t) => window.setTimeout(t, 16.666666666666668));
2
+ function $(t, e) {
3
+ if (e) {
4
+ document.querySelector(e).scrollTop = t;
5
+ return;
6
+ }
7
+ document.documentElement.scrollTop = t, document.body.parentNode.scrollTop = t, document.body.scrollTop = t;
8
+ }
9
+ function M(t) {
10
+ return t ? document.querySelector(t).scrollTop : document.documentElement.scrollTop || document.body.parentNode.scrollTop || document.body.scrollTop;
11
+ }
12
+ function D(t) {
13
+ const { target: e, to: n = 0, duration: r = 500, callback: o } = t ?? {}, s = M(e), i = n - s, c = 20;
14
+ let a = 0;
15
+ const u = function() {
16
+ a += c;
17
+ const l = I(a, s, i, r);
18
+ $(l, e), a < r ? A(u) : o && o();
19
+ };
20
+ u();
21
+ }
22
+ function E(t) {
23
+ return /^(http(s)?:\/\/)/.test(t);
24
+ }
25
+ function x(t) {
26
+ return /^(https?:|mailto:|tel:)/.test(t);
27
+ }
28
+ function O(t) {
29
+ return Object.prototype.toString.call(t) === "[object String]";
30
+ }
31
+ function R(t) {
32
+ return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(t);
33
+ }
34
+ function C(t) {
35
+ return !Object.keys(t).length;
36
+ }
37
+ function v(t) {
38
+ return /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/.test(t);
39
+ }
40
+ function H(t, e = 8) {
41
+ return new RegExp(`^S*(?=S{${e}},})(?=S*d)(?=S*[A-Z])(?=S*[a-z])(?=S*[!@#$%^&*?])S*$`).test(t);
42
+ }
43
+ function N(t) {
44
+ return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(t);
45
+ }
46
+ function d(t) {
47
+ return /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/.test(t);
48
+ }
49
+ function P(t) {
50
+ return /^0\d{2,3}-?\d{7,8}$/.test(t);
51
+ }
52
+ function z(t) {
53
+ return /^1[3-9]\d{9}$/.test(t);
54
+ }
55
+ const g = () => {
56
+ };
57
+ function U(t, e) {
58
+ let n = null;
59
+ return function(...r) {
60
+ n !== null && clearTimeout(n), n = setTimeout(() => {
61
+ t.apply(this, r), n = null;
62
+ }, e);
63
+ };
64
+ }
65
+ function F(t) {
66
+ if (!d(t))
67
+ throw new Error("Please provide a valid ID number!");
68
+ const e = t.length, n = e === 15 ? t[e - 1] : t[e - 2];
69
+ return parseInt(n) % 2 === 1 ? "1" : "2";
70
+ }
71
+ function L(t) {
72
+ if (!d(t))
73
+ throw new Error("Please provide a valid ID number!");
74
+ return t.substring(6, 10) + "-" + t.substring(10, 12) + "-" + t.substring(12, 14);
75
+ }
76
+ const h = (t, e = "") => {
77
+ e || (e = globalThis.location.origin);
78
+ const n = new RegExp(/^http(s)?:\/\//), r = new RegExp(/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i);
79
+ return n.test(t) || r.test(t) ? t : e + t;
80
+ }, q = (t, e = "") => {
81
+ typeof t == "string" && (t = t === "" ? [] : t.split(","));
82
+ for (const n in t)
83
+ t[n] = h(t[n], e);
84
+ return t;
85
+ };
86
+ function Z(t) {
87
+ let e = g;
88
+ return (...n) => new Promise((r, o) => {
89
+ e(), e = () => {
90
+ r = o = g;
91
+ }, t(...n).then(
92
+ (s) => r(s),
93
+ (s) => o(s)
94
+ );
95
+ });
96
+ }
97
+ function j(t, e) {
98
+ const n = document.createElement("a");
99
+ n.download = e, n.href = t, n.click();
100
+ }
101
+ function S(t) {
102
+ const e = [];
103
+ for (let n = 0; n < t.length; n++)
104
+ t[n] && e.push(t[n]);
105
+ return e;
106
+ }
107
+ function k(t, e) {
108
+ switch (arguments.length) {
109
+ case 1:
110
+ return parseInt((Math.random() * t + 1).toString(), 10);
111
+ case 2:
112
+ return parseInt((Math.random() * (e - t + 1) + t).toString(), 10);
113
+ default:
114
+ return 0;
115
+ }
116
+ }
117
+ function J() {
118
+ let t = "";
119
+ const e = [];
120
+ for (let n = 0; n <= 15; n++)
121
+ e[n] = n.toString(16);
122
+ for (let n = 1; n <= 36; n++)
123
+ n === 9 || n === 14 || n === 19 || n === 24 ? t += "-" : n === 15 ? t += 4 : n === 20 ? t += e[Math.random() * 4 | 8] : t += e[Math.random() * 16 | 0];
124
+ return t;
125
+ }
126
+ function _(t) {
127
+ return t ? t.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2") : "";
128
+ }
129
+ function B(t, e, n) {
130
+ if (e ?? (e = 4), n ?? (n = 4), t) {
131
+ const r = t.length;
132
+ return t.substring(0, e) + "*".repeat(r - e - n) + t.substring(r - n);
133
+ }
134
+ return "";
135
+ }
136
+ function G(t) {
137
+ return t.replace(/( |^)[a-z]/g, (e) => e.toUpperCase());
138
+ }
139
+ function Q(t) {
140
+ return t.replace(/( |^)[A-Z]/g, (e) => e.toLowerCase());
141
+ }
142
+ function f(t, e) {
143
+ if (!t) return "-";
144
+ t.toString().length === 10 && (t = +t * 1e3), e ?? (e = "YYYY-MM-DD HH:mm:ss");
145
+ const n = new Date(t), r = (i, c, a = " ") => {
146
+ if (i.length >= c) return i;
147
+ const u = c - i.length;
148
+ let l = Math.ceil(u / a.length);
149
+ for (; l >>= 1; )
150
+ a += a, l === 1 && (a += a);
151
+ return a.slice(0, u) + i;
152
+ };
153
+ let o;
154
+ const s = {
155
+ "Y+": n.getFullYear().toString(),
156
+ "M+": (n.getMonth() + 1).toString(),
157
+ "D+": n.getDate().toString(),
158
+ "H+": n.getHours().toString(),
159
+ "m+": n.getMinutes().toString(),
160
+ "s+": n.getSeconds().toString()
161
+ };
162
+ for (const i in s)
163
+ o = new RegExp("(" + i + ")").exec(e), o && (e = e.replace(o[1], o[1].length == 1 ? s[i] : r(s[i], o[1].length, "0")));
164
+ return e;
165
+ }
166
+ function X(t, e) {
167
+ `${t}`.length === 10 ? t = parseInt(t + "") * 1e3 : t = +t;
168
+ const n = new Date(t), o = (Date.now() - Number(n)) / 1e3;
169
+ return o < 30 ? "刚刚" : o < 3600 ? `${Math.ceil(o / 60)}分钟前` : o < 3600 * 24 ? `${Math.ceil(o / 3600)}小时前` : o < 3600 * 24 * 2 ? "1天前" : e ? f(t, e) : `${n.getMonth() + 1}月${n.getDate()}日${n.getHours()}时${n.getMinutes()}分`;
170
+ }
171
+ function K(t) {
172
+ const e = t || /* @__PURE__ */ new Date(), n = new Date(e), r = new Date(e);
173
+ return n.setHours(0, 0, 0), r.setHours(23, 59, 59), {
174
+ dateRange: [f(n), f(r)],
175
+ timestampRange: [n.getTime(), r.getTime()]
176
+ };
177
+ }
178
+ const V = {
179
+ set(t, e) {
180
+ sessionStorage && t && e && sessionStorage.setItem(t, e);
181
+ },
182
+ get(t) {
183
+ return !sessionStorage || !t ? null : sessionStorage.getItem(t);
184
+ },
185
+ setJSON(t, e) {
186
+ e && this.set(t, JSON.stringify(e));
187
+ },
188
+ getJSON(t) {
189
+ const e = this.get(t);
190
+ return e ? JSON.parse(e) : null;
191
+ },
192
+ remove(t) {
193
+ sessionStorage.removeItem(t);
194
+ },
195
+ clear() {
196
+ sessionStorage.clear();
197
+ }
198
+ }, W = {
199
+ set(t, e) {
200
+ localStorage && t && e && localStorage.setItem(t, e);
201
+ },
202
+ get(t) {
203
+ return !localStorage || !t ? null : localStorage.getItem(t);
204
+ },
205
+ setJSON(t, e) {
206
+ e && this.set(t, JSON.stringify(e));
207
+ },
208
+ getJSON(t) {
209
+ const e = this.get(t);
210
+ return e ? JSON.parse(e) : null;
211
+ },
212
+ remove(t) {
213
+ localStorage.removeItem(t);
214
+ },
215
+ clear() {
216
+ localStorage.clear();
217
+ }
218
+ };
219
+ function tt(t, e) {
220
+ if (!t || !e)
221
+ return;
222
+ let n = t.className;
223
+ const r = n.indexOf(e);
224
+ r === -1 ? n += `${e}` : n = n.substring(0, r) + n.substring(r + e.length), t.className = n;
225
+ }
226
+ function p(t, e) {
227
+ return t.className.match(new RegExp("(?:\\s|^)" + e + "(?:\\s|$)"));
228
+ }
229
+ function et(t, e) {
230
+ p(t, e) || (t.className += ` ${e}`);
231
+ }
232
+ function nt(t, e) {
233
+ if (p(t, e)) {
234
+ const n = new RegExp("(?:\\s|^)" + e + "(?:\\s|$)");
235
+ t.className = t.className.replace(n, " ");
236
+ }
237
+ }
238
+ function rt(t) {
239
+ let e = !1;
240
+ return function(...n) {
241
+ e || (e = !0, window.requestAnimationFrame(() => {
242
+ t.apply(this, n), e = !1;
243
+ }));
244
+ };
245
+ }
246
+ function ot(t) {
247
+ t && (t.oncontextmenu = () => !1);
248
+ }
249
+ function st(t) {
250
+ switch (t) {
251
+ case 400:
252
+ return "请求失败!请您稍后重试";
253
+ case 401:
254
+ return "认证失败,无法访问系统资源";
255
+ case 403:
256
+ return "当前操作没有权限!";
257
+ case 404:
258
+ return "你所访问的资源不存在!";
259
+ case 405:
260
+ return "请求方式错误!请您稍后重试";
261
+ case 408:
262
+ return "请求超时!请您稍后重试";
263
+ case 500:
264
+ return "服务异常!";
265
+ case 502:
266
+ return "网关错误!";
267
+ case 503:
268
+ return "服务不可用!";
269
+ case 504:
270
+ return "网关超时!";
271
+ default:
272
+ return "系统未知错误,请反馈给管理员";
273
+ }
274
+ }
275
+ function ct(t) {
276
+ switch (t) {
277
+ case "1":
278
+ return "是";
279
+ case "0":
280
+ return "否";
281
+ default:
282
+ return "未填写";
283
+ }
284
+ }
285
+ function it(t) {
286
+ switch (t) {
287
+ case "1":
288
+ return "有";
289
+ case "0":
290
+ return "无";
291
+ default:
292
+ return "未填写";
293
+ }
294
+ }
295
+ function at(t, e) {
296
+ const n = t.find((r) => r.value === e);
297
+ return n ? n.label : "";
298
+ }
299
+ function ut(t, e, n) {
300
+ const r = [], o = e.split(","), s = n.split(",");
301
+ return Array.from(new Set(o)).forEach((c) => {
302
+ const a = t.find((u) => u.value === c);
303
+ a && s.forEach((u) => {
304
+ var m;
305
+ const l = (m = a.children) == null ? void 0 : m.find((y) => y.value === u);
306
+ l && r.push(l);
307
+ });
308
+ }), r.map((c) => c.label).join();
309
+ }
310
+ function w(t, e, n) {
311
+ var s;
312
+ if (!e) return "";
313
+ const r = e.split(","), o = n.find((i) => i.value === r[t]);
314
+ return o ? ((s = o.children) != null && s.length && w(t + 1, e, o.children), o.label) : "";
315
+ }
316
+ function lt(t, e, n) {
317
+ if (!t) return "";
318
+ const r = t.split(","), o = [], s = r.length - 1, i = r.findIndex((c) => c === n);
319
+ if (i !== -1) {
320
+ const c = r[s] === n;
321
+ r.splice(c ? 0 : i, c ? s : 1);
322
+ }
323
+ return r.forEach((c) => {
324
+ const a = e.find((u) => u.value === c);
325
+ a && o.push(a);
326
+ }), o.map((c) => c.label).join();
327
+ }
328
+ function ft(t) {
329
+ let e = "";
330
+ for (const n of Object.keys(t)) {
331
+ const r = t[n], o = `${encodeURIComponent(n)}=`;
332
+ if (r !== null && typeof r < "u")
333
+ if (typeof r == "object") {
334
+ for (const s of Object.keys(r))
335
+ if (r[s] !== null && typeof r[s] < "u") {
336
+ const i = `${n}[${s}]`, c = `${encodeURIComponent(i)}=`;
337
+ e += `${c + encodeURIComponent(r[s])}&`;
338
+ }
339
+ } else
340
+ e += `${o + encodeURIComponent(r)}&`;
341
+ }
342
+ return e;
343
+ }
344
+ function gt(t) {
345
+ return t ? S(
346
+ Object.keys(t).map((e) => t[e] === void 0 ? "" : `${encodeURIComponent(e)}=${encodeURIComponent(t[e])}`)
347
+ ).join("&") : "";
348
+ }
349
+ function dt(t) {
350
+ const e = decodeURIComponent(t.split("?")[1]).replace(/\+/g, " ");
351
+ if (!e)
352
+ return {};
353
+ const n = {};
354
+ return e.split("&").forEach((o) => {
355
+ const s = o.indexOf("=");
356
+ if (s !== -1) {
357
+ const i = o.substring(0, s), c = o.substring(s + 1, o.length);
358
+ n[i] = c;
359
+ }
360
+ }), n;
361
+ }
362
+ const pt = [
363
+ ["date", "YYYY-MM-DD"],
364
+ ["daterange", "YYYY-MM-DD"],
365
+ ["datetime", "YYYY-MM-DD HH:mm:ss"],
366
+ ["datetimerange", "YYYY-MM-DD HH:mm:ss"],
367
+ ["month", "YYYY-MM"],
368
+ ["monthrange", "YYYY-MM"],
369
+ ["year", "YYYY"],
370
+ ["yearrange", "YYYY"],
371
+ ["time", "HH:mm:ss"]
372
+ ], mt = new Map(pt), Y = ["jpg", "jpeg", "png", "bmp", "gif"], T = ["mp3", "mp4", "webm", "ogg", "3gp"], b = ["doc", "docx", "xls", "xlsx", "ppt", "txt", "pdf", "zip"], ht = [...Y, ...T, ...b], St = { DATE_VALUE_FORMAT: mt, IMAGE_TYPE: Y, MEDIA_TYPE: T, DOC_TYPE: b, FILE_TYPE: ht }, wt = {
373
+ NOOP: g,
374
+ debounce: U,
375
+ creatCancelTask: Z,
376
+ downloadFile: j,
377
+ trimArray: S,
378
+ getFullUrl: h,
379
+ getArrayFullUrl: q,
380
+ getGenderByIdNumber: F,
381
+ getBirthdayByIdNumber: L
382
+ }, Yt = {
383
+ encodeURIToParams: ft,
384
+ paramsToQueryString: gt,
385
+ queryStringToParams: dt,
386
+ errorCodeToString: st,
387
+ YNToString: ct,
388
+ HNToString: it,
389
+ valueToLabel: at,
390
+ chargeToLabel: ut,
391
+ cascaderToLabel: w,
392
+ multipleSelectToLabel: lt
393
+ }, Tt = {
394
+ validHttp: E,
395
+ validExternal: x,
396
+ validString: O,
397
+ validNumberStr: R,
398
+ validEmptyObject: C,
399
+ validURL: v,
400
+ validPassword: H,
401
+ validEmail: N,
402
+ validIdNumber: d,
403
+ validPhone: z,
404
+ validTel: P
405
+ }, bt = { scrollTo: D, addClass: et, removeClass: nt, hasClass: p, toggleClass: tt, noContextmenu: ot, useRafThrottle: rt }, yt = { local: W, session: V }, It = { uuid: J, randomNum: k }, At = { phoneToAsterisk: _, idNumberToAsterisk: B, firstLetterToUpperCase: G, firstLetterToLowerCase: Q }, $t = { parseTime: f, getTimeDistance: X, getDayRange: K };
406
+ export {
407
+ yt as cacheUtil,
408
+ wt as commonUtil,
409
+ St as constants,
410
+ $t as dateUtil,
411
+ bt as elementUtil,
412
+ It as randomUtil,
413
+ At as stringUtil,
414
+ Yt as toUtil,
415
+ Tt as validUtil
416
+ };
@@ -0,0 +1,23 @@
1
+ export type Fn<T = any, R = T> = {
2
+ (...arg: T[]): R;
3
+ };
4
+ export type PromiseFn<T = any, R = T> = {
5
+ (...arg: T[]): Promise<R>;
6
+ };
7
+ export type AnyObj<T = any> = {
8
+ [key: string]: T;
9
+ };
10
+ export type Nullable<T> = T | null;
11
+ export type Writable<T> = {
12
+ -readonly [P in keyof T]: T[P];
13
+ };
14
+ export type TimeoutHandle = ReturnType<typeof setTimeout>;
15
+ export type IntervalHandle = ReturnType<typeof setInterval>;
16
+ export type OptionType = {
17
+ value: string | number;
18
+ label: string;
19
+ };
20
+ export type CategoryType = {
21
+ id?: string | number;
22
+ children?: CategoryType[];
23
+ } & OptionType;
@@ -0,0 +1,17 @@
1
+ import { AnyObj } from '../types';
2
+ export declare const session: {
3
+ set(key: string, value: string): void;
4
+ get(key: string): string | null;
5
+ setJSON(key: string, jsonValue: AnyObj): void;
6
+ getJSON(key: string): AnyObj | null;
7
+ remove(key: string): void;
8
+ clear(): void;
9
+ };
10
+ export declare const local: {
11
+ set(key: string, value: string): void;
12
+ get(key: string): string | null;
13
+ setJSON(key: string, jsonValue: AnyObj): void;
14
+ getJSON(key: string): AnyObj | null;
15
+ remove(key: string): void;
16
+ clear(): void;
17
+ };
@@ -0,0 +1,22 @@
1
+ import { PromiseFn } from '../types';
2
+ export declare const NOOP: () => void;
3
+ export declare function debounce<T extends (...args: any[]) => any>(func: T, delay: number): (...args: Parameters<T>) => void;
4
+ /**
5
+ * Gets the gender of the person from the given ID number.
6
+ * @param idNumber the ID number
7
+ * @returns the gender of the person, '1' for male, '2' for female
8
+ * @throws error if the given ID number is invalid
9
+ */
10
+ export declare function getGenderByIdNumber(idNumber: string): "1" | "2";
11
+ /**
12
+ * Gets the birthday of the person from the given ID number.
13
+ * @param idNumber the ID number
14
+ * @returns the birthday of the person in the format 'YYYY-MM-DD'
15
+ * @throws error if the given ID number is invalid
16
+ */
17
+ export declare function getBirthdayByIdNumber(idNumber: string): string;
18
+ export declare const getFullUrl: (relativeUrl: string, domain?: string) => string;
19
+ export declare const getArrayFullUrl: (relativeUrls: string | string[], domain?: string) => string[];
20
+ export declare function creatCancelTask(asyncTask: PromiseFn): (...args: any[]) => Promise<unknown>;
21
+ export declare function downloadFile(url: string, name: string): void;
22
+ export declare function trimArray<T>(actual: Array<T>): Array<T>;
@@ -0,0 +1,6 @@
1
+ export declare function parseTime(dateTime?: string | number | Date | null, format?: string): string;
2
+ export declare function getTimeDistance(time: number, option: string): string;
3
+ export declare function getDayRange(date?: string | number | Date): {
4
+ dateRange: [string, string];
5
+ timestampRange: [number, number];
6
+ };
@@ -0,0 +1,6 @@
1
+ export declare function toggleClass(element: Element, className: string): void;
2
+ export declare function hasClass(ele: Element, cls: string): RegExpMatchArray | null;
3
+ export declare function addClass(ele: Element, cls: string): void;
4
+ export declare function removeClass(ele: Element, cls: string): void;
5
+ export declare function useRafThrottle(fn: Function): (...args: any[]) => void;
6
+ export declare function noContextmenu(ele: HTMLElement): void;
@@ -0,0 +1,2 @@
1
+ export declare function randomNum(min: number, max: number): number;
2
+ export declare function uuid(): string;
@@ -0,0 +1,6 @@
1
+ export default function scrollTo(options?: {
2
+ target?: string;
3
+ to?: number;
4
+ duration?: number;
5
+ callback?: Function;
6
+ }): void;
@@ -0,0 +1,4 @@
1
+ export declare function phoneToAsterisk(phone?: string): string;
2
+ export declare function idNumberToAsterisk(idNumber?: string, startLength?: number, endLength?: number): string;
3
+ export declare function firstLetterToUpperCase(str: string): string;
4
+ export declare function firstLetterToLowerCase(str: string): string;
@@ -0,0 +1,11 @@
1
+ import { AnyObj, CategoryType } from '../types';
2
+ export declare function errorCodeToString(code: number): string;
3
+ export declare function YNToString(value?: string | null): "是" | "否" | "未填写";
4
+ export declare function HNToString(value?: string | null): "未填写" | "有" | "无";
5
+ export declare function valueToLabel(data: CategoryType[], value?: string): string;
6
+ export declare function chargeToLabel(data: CategoryType[], type: string, charge: string): string;
7
+ export declare function cascaderToLabel(index: number, value: string | undefined, data: CategoryType[]): string;
8
+ export declare function multipleSelectToLabel(value: string | undefined, data: CategoryType[], str?: string): string;
9
+ export declare function encodeURIToParams(params: AnyObj): string;
10
+ export declare function paramsToQueryString(json: AnyObj): string;
11
+ export declare function queryStringToParams(url: string): AnyObj;
@@ -0,0 +1,18 @@
1
+ import { AnyObj } from '../types';
2
+ export declare function validHttp(http: string): boolean;
3
+ export declare function validExternal(str: string): boolean;
4
+ export declare function validString(str: string): boolean;
5
+ export declare function validNumberStr(str: string): boolean;
6
+ export declare function validEmptyObject(object: AnyObj): boolean;
7
+ export declare function validURL(url: string): boolean;
8
+ /**
9
+ * Validate the password strength
10
+ * @param {string} password The password to be validated
11
+ * @param {number} [minLength=8] The minimum length of the password,The default value is 8
12
+ * @returns {boolean} Whether the password is valid
13
+ */
14
+ export declare function validPassword(password: string, minLength?: number): boolean;
15
+ export declare function validEmail(email: string): boolean;
16
+ export declare function validIdNumber(idNumber: string): boolean;
17
+ export declare function validTel(tel: string): boolean;
18
+ export declare function validPhone(phone: string): boolean;
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@nano-lib/util",
3
+ "version": "1.0.5",
4
+ "description": "Custom utility functions for the nano library",
5
+ "author": "kevin chen",
6
+ "license": "MIT",
7
+ "main": "lib/index.js",
8
+ "module": "lib/index.mjs",
9
+ "types": "lib/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./lib/index.d.ts",
13
+ "import": "./lib/index.mjs",
14
+ "require": "./lib/index.js"
15
+ }
16
+ },
17
+ "files": [
18
+ "package.json",
19
+ "README.md",
20
+ "LICENSE",
21
+ "lib"
22
+ ],
23
+ "scripts": {
24
+ "lib": "rimraf lib && vite build"
25
+ },
26
+ "devDependencies": {
27
+ "@types/node": "^22.13.17",
28
+ "@typescript-eslint/eslint-plugin": "^8.29.0",
29
+ "@typescript-eslint/parser": "^8.29.0",
30
+ "eslint": "^9.23.0",
31
+ "eslint-config-prettier": "^10.1.1",
32
+ "prettier": "^3.5.3",
33
+ "typescript": "^5.8.2",
34
+ "vite": "^6.0.5",
35
+ "vite-plugin-dts": "^4.5.3"
36
+ },
37
+ "packageManager": "pnpm@9.1.3",
38
+ "keywords": [
39
+ "nano-lib"
40
+ ]
41
+ }