@likg/tools
Version:
3 lines (2 loc) • 12 kB
JavaScript
/* eslint-disable */
var Tools=function(){"use strict";class e{static instance;constructor(){}static defaultUtils(){return this.instance||(this.instance=new e),this.instance}static query(e,t){let n="";if(n=t?/^http/.test(t)?t.split("?")[1]:t:window.location.search,n){n=/\?/.test(n)?n.slice(1):n;const t={};return n.split("&").forEach((e=>{if(/=/.test(e)){const n=e.split("="),o=n[0],a=n[1];t[o]=a?decodeURIComponent(a):void 0}})),e&&e?t[e]?t[e]:"":t}return e?"":{}}static convertToQueryWith(t,n=!0){if(!t||"object"!==e.toRawType(t))return"";let o=n?"?":"";return Object.keys(t).forEach((e=>{const n=t[e];o+=`${e}=${void 0!==n?encodeURIComponent(n):""}&`})),o?o.slice(0,o.length-1):o}static convertToFormDataWith(e){const t=new FormData;for(const n of Object.keys(e))t.append(n,e[n]);return t}static dateFormat(e,t="YYYY-MM-DD HH:mm:ss"){const n=e=>e.toString().padStart(2,"0");"string"==typeof e&&/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(e)&&(e=e.replace(/-/g,"/"));const o=new Date(e);if(isNaN(o.getTime()))return"-";const a=o.getFullYear().toString(),r=n(o.getMonth()+1),s=n(o.getDate()),i=n(o.getHours()),c=n(o.getMinutes()),l=n(o.getSeconds()),d=["星期日","星期一","星期二","星期三","星期四","星期五","星期六"][o.getDay()];return t.replace(/YYYY/gi,a).replace(/MM/,r).replace(/DD/,s).replace(/HH/,i).replace(/mm/,c).replace(/ss/,l).replace(/dddd/,d)}static del(e,t,n){const o=[...e],a=o.findIndex((e=>e[t]===n));return o.splice(a,1),o}static unique(e,t){const n={};return e.reduce(((e,o)=>{const a=o[t]+"";return!n[a]&&(n[a]=e.push(o)),e}),[])}static phoneFormatter(e,t="$1 **** $2"){return e&&"string"==typeof e&&11===e.length?e.replace(/(\d{3})(\d{4})(\d{4})/,((e,n,o,a)=>t.replace("$1",n).replace("$2",o).replace("$3",a))):""}static px2vw(e){return e/375*100+"vw"}static clipboard(e){return new Promise(((t,n)=>{const o=document.createElement("input");o.setAttribute("value",e),document.body.appendChild(o),o.select();const a=document.execCommand("copy");document.body.removeChild(o),a?t(null):n()}))}static timeDown(e){const{timeStamp:t,format:n,mode:o="default",type:a="default",showDay:r=!0,pending:s,complete:i}=e;let c=t;const l="default"===a?1e3:100;let d,p=performance.now();const u=e=>"seconds"===o?String(e):String(e).padStart(2,"0"),m=()=>{const e=r?u(Math.floor(c/1e3/60/60/24)):"",t=u(r?Math.floor(c/1e3/60/60%24):Math.floor(c/1e3/60/60)),o=u(Math.floor(c/1e3/60%60)),i=u(Math.floor(c/1e3%60)),l=u(Math.floor(c%1e3/100));let d="";n?d=n.replace(/dd/gi,e).replace(/hh/gi,t).replace(/mm/gi,o).replace(/ss/gi,i).replace(/ms/gi,l):("default"===a&&(d=[e,t,o,i]),"ms"===a&&(d=[e,t,o,i,l])),s(d)},f=()=>{const e=u(Math.floor(c/1e3)),t=u(Math.floor(c%1e3/100));let o="";n?o=n.replace(/ss/gi,e).replace(/ms/gi,t):("default"===a&&(o=[e]),"ms"===a&&(o=[e,t])),s(o)},g=()=>{const e=performance.now();e-p>=l&&(c-=l,p=e,c>0&&("default"===o&&m(),"seconds"===o&&f())),c>0?d=requestAnimationFrame(g):i()};return c<=0?i():("default"===o&&m(),"seconds"===o&&f(),d=requestAnimationFrame(g)),()=>{d&&cancelAnimationFrame(d)}}static toRawType(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}static track(e){if(window._hmt)switch(e.type){case"pv":window._hmt.push(["_trackPageview",e.pageURL||location.pathname]);break;case"es":window._hmt.push(["_trackEvent",e.category,e.action||"click",e.opt_label,e.opt_value])}}static randomCharacters(e,t){let n="";switch(t=t||"default"){case"digital":n+="0123456789";break;case"uppercase":n+="ABCDEFGHIJKLMNOPQRSTUVWXYZ";break;case"lowercase":n+="abcdefghijklmnopqrstuvwxyz";break;default:n+="0123456789",n+="ABCDEFGHIJKLMNOPQRSTUVWXYZ",n+="abcdefghijklmnopqrstuvwxyz"}let o="";for(let t=0;t<e;++t){const e=Math.floor(Math.random()*n.length);o+=n.slice(e,e+1)}return o}static randomDecimals(e,t){return void 0===e||void 0===t||isNaN(e)||isNaN(t)?-1:Math.random()*(t-e)+e}static randomInteger(e,t){return void 0===e||void 0===t||isNaN(e)||isNaN(t)?-1:Math.floor(Math.random()*(t-e+1))+e}static launchFullscreen(){const e=document.documentElement,t=e.requestFullScreen||e.webkitRequestFullScreen||e.mozRequestFullScreen||e.msRequestFullscreen;void 0!==t&&t&&t.call(e)}static exitFullscreen(){if(document.fullscreenElement){const e=document,t=e.exitFullscreen||e.mozCancelFullScreen||e.webkitCancelFullScreen||e.msExitFullscreen;void 0!==t&&t&&t.call(e)}}static getYears(e=1970,t=(new Date).getFullYear()){const n=[];for(let o=e;o<=t;o++)n.push(`${o.toString()}年`);return n}static getMonths(){const e=[];for(let t=1;t<=12;t++)e.push((t<10?`0${t}`:t.toString())+"月");return e}static getDays(e){const t=[];let n=31;if(e){const{year:t,month:o}=e;-1!==[4,6,9,11].indexOf(o)?n=30:2===o&&(n=t%4==0&&t%100!=0||t%400==0?29:28)}for(let e=1;e<=n;e++)t.push((e<10?`0${e}`:e.toString())+"日");return t}static async downloadFiles(e,t="blob"){if(!e||0===e.length)throw new Error("[downloadFiles]:未传入下载源");const n=(e,n)=>{const o=document.createElement("a");o.style.display="none",o.href=e,o.download=n,document.body.appendChild(o),o.click(),document.body.removeChild(o),"blob"===t&&setTimeout((()=>URL.revokeObjectURL(e)),1e3)},o={"application/pdf":".pdf","application/msword":".doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":".docx","application/vnd.ms-excel":".xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":".xlsx","application/vnd.ms-powerpoint":".ppt","application/vnd.openxmlformats-officedocument.presentationml.presentation":".pptx","text/plain":".txt","text/csv":".csv","application/json":".json","application/xml":".xml","application/zip":".zip","application/x-rar-compressed":".rar","application/x-tar":".tar","application/x-7z-compressed":".7z","image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/svg+xml":".svg","image/webp":".webp","image/bmp":".bmp","image/tiff":".tiff","audio/mpeg":".mp3","audio/wav":".wav","audio/ogg":".ogg","audio/aac":".aac","audio/webm":".webm","video/mp4":".mp4","video/mpeg":".mpeg","video/ogg":".ogv","video/webm":".webm","video/x-msvideo":".avi","video/quicktime":".mov","video/x-matroska":".mkv","application/octet-stream":".bin","application/x-binary":".bin","application/x-download":".bin"},a=(e,t)=>{let n=t??"file",a=".bin";if("string"==typeof e){const o=new URL(e).pathname;if(!t){const e=o.lastIndexOf("/")+1,t=-1!==o.lastIndexOf(".")?o.lastIndexOf("."):o.length;n=o.slice(e,t)}const r=o.lastIndexOf(".");-1!==r&&r<o.length-1&&(a=o.slice(r))}else r=e.type,a=o[r]||".bin";var r;return n.endsWith(a)?n:n+a},r=e.map((e=>{const{source:o,filename:r}=e,s=a(o,r);return"string"==typeof o?"blob"===t?(async(e,t)=>{try{const o=await fetch(e,{mode:"cors"});if(!o.ok)throw new Error(`[downloadFiles]:下载失败,HTTP ${o.status} ${o.statusText}`);const a=await o.blob();n(URL.createObjectURL(a),t)}catch(e){throw new Error(`[downloadFiles]:下载失败,${e.message}`)}})(o,s):(n(o,s),Promise.resolve()):(n(URL.createObjectURL(o),s),Promise.resolve())}));await Promise.allSettled(r).then((t=>{t.forEach(((t,n)=>{"rejected"===t.status&&console.warn(`[downloadFiles]:下载失败,${e[n].source}`,t.reason)}))}))}static numFormat(e){return e<10?`0${e}`:e.toString()}static getEnv(){const e=window.navigator.userAgent;return/MicroMessenger/i.test(e)?"weixin":/AlipayClient/i.test(e)?"alipay":/Linux|Android/i.test(e)?"android":/iPhone/i.test(e)?"ios":"unknown"}static getFilePath(t,n){const o=e=>e<10?`0${e}`:e,a=new Date,r=a.getFullYear(),s=a.getMonth()+1,i=a.getDate(),c=`${r}${o(s)}${o(i)}`,l=t.name.split(".").slice(-1).toString();return`${n}/${c}/${e.randomCharacters(3,"uppercase")}${a.getTime()}.${l}`}static base64ToUint8Array(e){const t=e.includes(",")?e.split(",")[1]:e,n=(t+"=".repeat((4-t.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/");try{const e=window.atob(n),t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}catch(e){throw console.error("Failed to decode Base64 string:",e),new Error("Invalid Base64 string")}}static base64(e){return new Promise(((t,n)=>{const o=new FileReader,a=e=>{o.readAsDataURL(e),o.onload=()=>{t(o.result)},o.onerror=()=>{n(new Error("读取文件或Blob对象失败"))}};if(e instanceof File||e instanceof Blob)a(e);else if("string"==typeof e&&/http/.test(e)){const t=new XMLHttpRequest;t.open("GET",e,!0),t.responseType="blob",t.onload=function(){200===this.status?a(this.response):n(new Error("请求图片失败,状态码: "+this.status))},t.onerror=()=>{n(new Error("请求图片失败"))},t.send()}else n(new Error("文件格式有误或目标类型不支持"))}))}static loadScript(e,t="text/javascript"){const n=e=>new Promise((n=>{const o=document.createElement("script");o.type=t,o.src=e,o.onload=()=>n(!0),o.onerror=()=>n(!1),document.body.appendChild(o)}));return new Promise((async t=>{if(!e||Array.isArray(e)&&0===e.length)return console.log("@likg/tools: loading script error. [no params]"),t(!1);const o=Array.isArray(e)?e:[e];for(let e=0;e<o.length;e++){if(!await n(o[e]))return console.log(`🔴 脚本「${e}」加载失败,地址:${o[e]}`),t(!1);console.log(`🟢 脚本「${e}」加载成功,地址:${o[e]}`)}t(!0)}))}static deepClone(t){const n=Array.isArray(t)?[]:{};if(t&&"object"==typeof t)for(const o in t)Object.prototype.hasOwnProperty.call(t,o)&&(!t[o]||"object"!=typeof t[o]||t[o]instanceof HTMLElement?n[o]=t[o]:n[o]=e.deepClone(t[o]));return n}static update(e,t,n){if(/\./.test(t)){let o=e,a=0;const r=t.split(".");for(;a<r.length-1;){const e=r[a++];e in o||(o[e]={}),o=o[e]}o[r[r.length-1]]=n}else e[t]=n;return e}static deepUpdate(t,n,o){const a=e.deepClone(t);return e.update(a,n,o)}static getLastDay(){return new Date((new Date).getTime()-864e5)}static getLastMonth(){const e=new Date;let t=e.getFullYear(),n=e.getMonth();return 0===n&&(t-=1,n=12),new Date(`${t}-${n}`)}static debounce(e,t=500){let n=null;return(...o)=>{n&&clearTimeout(n),n=setTimeout((()=>{e.apply(this,o)}),t)}}static getConstellation(t,n){if(!t)return"";let o,a;if("date"===e.toRawType(t))o=t.getMonth()+1,a=t.getDate();else{if("number"!=typeof t||"number"!=typeof n)return"";if(t<1||t>12||n<1||n>31)return"";o=t,a=n}let r="";switch(o){case 1:r=a>19?"水瓶座":"摩羯座";break;case 2:r=a>18?"双鱼座":"水瓶座";break;case 3:r=a>20?"白羊座":"双鱼座";break;case 4:r=a>19?"金牛座":"白羊座";break;case 5:r=a>20?"双子座":"金牛座";break;case 6:r=a>21?"巨蟹座":"双子座";break;case 7:r=a>22?"狮子座":"巨蟹座";break;case 8:r=a>22?"处女座":"狮子座";break;case 9:r=a>22?"天秤座":"处女座";break;case 10:r=a>23?"天蝎座":"天秤座";break;case 11:r=a>22?"射手座":"天蝎座";break;case 12:r=a>21?"摩羯座":"射手座"}return r}static canvasFillText(e,t,n,o,a,r,s=5){if(!e||"string"!=typeof t||"number"!=typeof n||"number"!=typeof o||"number"!=typeof a||"number"!=typeof r)return 0;e.textBaseline="top";const i=e.canvas,c=void 0===r?i&&i.width||200:r;let l=0,d=1,p=0;const u=t.split("");for(let r=0;r<u.length;r++){if(l+=e.measureText(u[r]).width,l>c){d++;let i=t.slice(p,r);if(d>s&&t.length>r&&(i=t.substring(p,r-2)+" ..."),e.fillText(i,n,o),l=0,o+=a,p=r,d>s)break}r===t.length-1&&(e.fillText(t.slice(p,r+1),n,o),d++)}return(d-1)*a}static ellipsis(e,t=6,n="middle"){if("string"!=typeof e||!e||e&&e.length<=t)return e;e.length<2*t&&(t=Math.ceil(e.length/2));const o=e.slice(0,t),a=e.slice(-t);switch(n){case"head":return`··· ${a}`;case"middle":return`${o} ··· ${a}`;case"tail":return`${o} ···`;default:return e}}static analysisDateString(e){if("string"!=typeof e)return{start:void 0,end:void 0};const[t,n]=e.split("-");if(isNaN(Number(t))||isNaN(Number(n)))return{start:void 0,end:void 0};let o=!1;(+t%4==0&&+t%100!=0||+t%400==0)&&(o=!0);const a=[31,o?29:28,31,30,31,30,31,31,30,31,30,31][+n-1];return{start:`${e}-01 00:00:00`,end:`${e}-${a<10?"0"+a:a} 23:59:59`}}static shuffleArray(e){const t=[...e];for(let e=t.length-1;e>0;e--){const n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t}static sleep(e=500){return new Promise((t=>setTimeout(t,e)))}}return e}();