ziya-utils 1.1.7 → 1.1.9

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.
@@ -1 +1 @@
1
- !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).ZiyaUtils={})}(this,function(e){"use strict";function t(e,t,n,o){return new(n||(n=Promise))(function(s,r){function i(e){try{c(o.next(e))}catch(e){r(e)}}function a(e){try{c(o.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(i,a)}c((o=o.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const n={PHONE:/^1[3-9]\d{9}$/,EMAIL:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,ID_CARD:/(^\d{15}$)|(^\d{17}(\d|X|x)$)/,URL:/^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/,IPV4:/^(\d{1,3}\.){3}\d{1,3}$/,STRONG_PASSWORD:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/,CHINESE:/^[\u4e00-\u9fa5]+$/};class o{}class s extends o{static isPhone(e){return n.PHONE.test(e)}static isEmail(e){return n.EMAIL.test(e)}static isIdCard(e){return n.ID_CARD.test(e)}static isUrl(e){return n.URL.test(e)}static isIpv4(e){return n.IPV4.test(e)}static isStrongPassword(e){return n.STRONG_PASSWORD.test(e)}static isChinese(e){return n.CHINESE.test(e)}}var r={patterns:n,validator:s};const i=e=>{if(!e)return"";const t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return-1===t?e:e.slice(t+1)};function a(e){if("string"==typeof e){if(!/^\d+$/.test(e))return!1;e=Number(e)}if("number"!=typeof e||isNaN(e))return!1;const t=41024448e5;return 13===e.toString().length?e>=0&&e<=t:10===e.toString().length&&(e>=0&&e<=4102444800)}const c=e=>a(e)&&10===e.toString().length;class l{constructor(e={}){var t;this.interceptRules=[],this.isActive=!1,this.originalXMLHttpRequest=window.XMLHttpRequest,this.enableLogging=null===(t=e.enableLogging)||void 0===t||t}start(){if(this.isActive)return void this.log("拦截器已经启动");const e=this;window.XMLHttpRequest=function(){const t=new e.originalXMLHttpRequest;let n="";const o=t.open;t.open=function(e,t,s=!0,r,i){return n="string"==typeof t?t:t.toString(),o.call(this,e,t,s,r,i)};const s=t.send;return t.send=function(o){const r=e.findMatchingRule(n);if(!r)return s.call(this,o);let i=o;if(r.requestCallback&&o)try{i=r.requestCallback(o,n)}catch(e){console.error("XHR请求拦截器处理失败:",e),i=o}const a=t.onreadystatechange;return t.onreadystatechange=function(o){if(4===t.readyState&&t.status>=200&&t.status<300)try{const o=JSON.parse(t.responseText),s=r.responseCallback(o,n);Object.defineProperty(t,"responseText",{writable:!0,configurable:!0,value:JSON.stringify(s)}),Object.defineProperty(t,"response",{writable:!0,configurable:!0,value:JSON.stringify(s)}),e.log(`已拦截并修改响应: ${n}`)}catch(t){e.log("拦截器处理失败:",t)}a&&a.call(this,o)},s.call(this,i)},t},Object.setPrototypeOf(window.XMLHttpRequest,this.originalXMLHttpRequest),window.XMLHttpRequest.prototype=this.originalXMLHttpRequest.prototype,this.isActive=!0,this.log("XHR拦截器已启动")}stop(){this.isActive?(window.XMLHttpRequest=this.originalXMLHttpRequest,this.isActive=!1,this.log("XHR拦截器已停止,已恢复原始XMLHttpRequest")):this.log("拦截器未启动")}setRules(e){this.interceptRules=[...e],this.log("已设置拦截规则:",e.map(e=>e.url))}addRule(e,t,n){this.interceptRules.push({url:e,responseCallback:t,requestCallback:n}),this.log(`已添加拦截规则: ${e}`)}removeRule(e){const t=this.interceptRules.length;this.interceptRules=this.interceptRules.filter(t=>t.url!==e);const n=this.interceptRules.length<t;return n?this.log(`已移除拦截规则: ${e}`):this.log(`未找到拦截规则: ${e}`),n}clearRules(){this.interceptRules=[],this.log("已清除所有拦截规则")}getRules(){return[...this.interceptRules]}getStatus(){return{isActive:this.isActive,rulesCount:this.interceptRules.length}}findMatchingRule(e){return this.interceptRules.find(t=>e.includes(t.url))}log(e,...t){this.enableLogging&&console.log(`[XHRInterceptor] ${e}`,...t)}}const u=new l({enableLogging:!0}),d="ziya-utils";e.Lib_Name=d,e.RegexPatterns=n,e.RegexValidator=s,e.ScriptDomBuilder=class{constructor(e=document.body,t="glk-script-container"){this.container=null,this.elements=new Map,this.data=new Map,this.styleElement=null,this.parentNode=e,this.containerId=t}createMain(e,t="",n={}){return t&&this.createStyles(t),this.container=this.createElement("div",Object.assign({id:this.containerId},n)),e.forEach((e,t)=>{const n=this.createItem(e,t);n&&this.container.appendChild(n)}),this.parentNode.appendChild(this.container),{container:this.container,get:e=>this.getChild(e),getValue:e=>this.getValue(e),setValue:(e,t)=>this.setValue(e,t),show:e=>this.show(e),hide:e=>this.hide(e),remove:()=>this.remove(),on:(e,t,n)=>this.on(e,t,n),getData:e=>this.getData(e),setData:(e,t)=>this.setData(e,t)}}createStyles(e){this.styleElement=document.createElement("style"),this.styleElement.textContent=e,document.head.appendChild(this.styleElement)}createItem(e,t){const{type:n,keyword:o}=e;!function(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(o=Object.getOwnPropertySymbols(e);s<o.length;s++)t.indexOf(o[s])<0&&Object.prototype.propertyIsEnumerable.call(e,o[s])&&(n[o[s]]=e[o[s]])}}(e,["type","keyword"]);let s=null;switch(n){case"input":s=this.createInput(e);break;case"button":s=this.createButton(e);break;case"select":s=this.createSelect(e);break;case"textarea":s=this.createTextarea(e);break;case"checkbox":s=this.createCheckbox(e);break;case"label":s=this.createLabel(e);break;case"div":s=this.createDiv(e);break;default:return console.warn(`未支持的元素类型: ${n}`),null}return o&&s&&(this.setChild(o,s),e.saveToLocal&&this.isFormElement(n)&&this.handleLocalStorage(s,e,n)),s}isFormElement(e){return["input","textarea","select","checkbox"].includes(e)}handleLocalStorage(e,t,n){const o=this.getStorageKey(t.keyword),s=this.getFromLocalStorage(o);if(null!==s)if("checkbox"===n){const t=e.querySelector('input[type="checkbox"]');t&&(t.checked="true"===s)}else{e.value=s}else if("checkbox"===n){const n=e.querySelector('input[type="checkbox"]');n&&(n.checked=t.checked||!1)}else{e.value=t.value||""}if("checkbox"===n){const t=e.querySelector('input[type="checkbox"]');t&&t.addEventListener("change",e=>{const t=e.target;this.saveToLocalStorage(o,t.checked.toString())})}else{const t="select"===n?"change":"input";e.addEventListener(t,e=>{const t=e.target;this.saveToLocalStorage(o,t.value)})}}createInput(e){const t=this.createElement("input",Object.assign({type:e.inputType||"text",name:e.keyword,placeholder:e.placeholder||"",value:e.value||""},e.props));return this.bindEvents(t,e),t}createButton(e){const t=this.createElement("button",Object.assign({textContent:e.text||e.keyword||"Button",name:e.keyword},e.props));return this.bindEvents(t,e),t}createSelect(e){const t=this.createElement("select",Object.assign({name:e.keyword},e.props));return e.options&&e.options.forEach(e=>{const n=document.createElement("option");"string"==typeof e?(n.value=e,n.textContent=e):(n.value=e.value||e.text||"",n.textContent=e.text||e.value||"",e.selected&&(n.selected=!0)),t.appendChild(n)}),this.bindEvents(t,e),t}createTextarea(e){const t=this.createElement("textarea",Object.assign({name:e.keyword,placeholder:e.placeholder||"",value:e.value||"",rows:e.rows||3},e.props));return this.bindEvents(t,e),t}createCheckbox(e){const t=document.createElement("div"),n=this.createElement("input",Object.assign({type:"checkbox",id:e.keyword,name:e.keyword,checked:e.checked||!1},e.props)),o=document.createElement("label");return o.setAttribute("for",e.keyword||""),o.textContent=e.text||e.keyword||"Checkbox",this.bindEvents(n,e),t.appendChild(n),t.appendChild(o),e.keyword&&this.setChild(e.keyword,n),t}createLabel(e){return this.createElement("label",Object.assign({textContent:e.text||e.keyword||"",name:e.keyword},e.props))}createDiv(e){const t=this.createElement("div",Object.assign({textContent:e.text||"",innerHTML:e.html||void 0,name:e.keyword},e.props));return this.bindEvents(t,e),t}createElement(e,t={}){const n=document.createElement(e);return Object.keys(t).forEach(e=>{"innerHTML"===e?n.innerHTML=t[e]:n[e]=t[e]}),n}bindEvents(e,t){["onClick","onChange","onInput","onFocus","onBlur","onMouseEnter","onMouseLeave"].forEach(n=>{const o=t[n];if(o){const t=n.slice(2).toLowerCase();e.addEventListener(t,o)}})}getChild(e){return this.elements.get(e)||null}setChild(e,t){this.elements.has(e)||this.elements.set(e,t)}getValue(e){const t=this.getChild(e);if(!t)return null;if("checkbox"===t.type)return t.checked;return t.value||t.textContent||null}setValue(e,t){const n=this.getChild(e);if(n)if("checkbox"===n.type)n.checked=Boolean(t);else{const e=n;void 0!==e.value?e.value=String(t):n.textContent=String(t)}}show(e){if(e){const t=this.getChild(e);if(t){const e="checkbox"===t.type?t.parentElement:t;e&&(e.style.display="")}}else this.container&&(this.container.style.display="")}hide(e){if(e){const t=this.getChild(e);if(t){const e="checkbox"===t.type?t.parentElement:t;e&&(e.style.display="none")}}else this.container&&(this.container.style.display="none")}remove(){this.container&&(this.container.remove(),this.container=null,this.elements.clear()),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}on(e,t,n){const o=this.getChild(e);o&&o.addEventListener(t,n)}getStorageKey(e){return`${this.containerId}_${e}`}saveToLocalStorage(e,t){try{localStorage.setItem(e,t)}catch(e){console.warn("无法保存到本地存储:",e)}}getFromLocalStorage(e){try{return localStorage.getItem(e)}catch(e){return console.warn("无法从本地存储读取:",e),null}}setData(e,t){this.data.set(e,t)}getData(e){return this.data.get(e)}},e.XHRInterceptor=l,e.addStyleStr=(e="")=>{let t=document.createElement("style");return t.innerHTML=e,document.getElementsByTagName("head")[0].appendChild(t),t},e.copyToClipboard=function(e){return t(this,void 0,void 0,function*(){try{var t=JSON.stringify(e);if(navigator.clipboard&&(window.isSecureContext||"https:"===location.protocol||"localhost"===location.hostname))return yield navigator.clipboard.writeText(t),!0;var n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.left="-9999px",n.style.top="-9999px",document.body.appendChild(n),n.select();var o=document.execCommand("copy");return document.body.removeChild(n),o}catch(e){return console.error("复制失败:",e),!1}})},e.createAsyncTask=function(e=()=>null,n=()=>{},o={}){const{duration:s=1,timeout:r,immediate:i=!1}=o;return new Promise((o,a)=>{let c=null,l=null;const u=()=>{c&&(clearInterval(c),c=null),l&&(clearTimeout(l),l=null)},d=()=>t(this,void 0,void 0,function*(){try{const t=yield e();if(t){u();const e=yield n(t);o(e)}}catch(e){u(),a(e)}});r&&r>0&&(l=setTimeout(()=>{u(),a(new Error(`${r} 秒后任务将会超时。`))},1e3*r)),i&&d(),c=setInterval(d,1e3*s)})},e.createFormData=e=>{const t=new FormData;if("string"==typeof e){const n=new URLSearchParams(e);for(const[e,o]of n)t.append(e,o)}else"object"==typeof e&&null!==e&&Object.keys(e).forEach(n=>{const o=e[n];null!=o?Array.isArray(o)?o.forEach(e=>t.append(n,String(e))):o instanceof File||o instanceof Blob?t.append(n,o):"object"==typeof o?t.append(n,JSON.stringify(o)):t.append(n,String(o)):t.append(n,"")});return t},e.createMaskLoading=(e="加载中...",t="")=>{const n=`${d}-mask-loading-container`,o=document.getElementById(n);o&&document.body.removeChild(o);const s=document.createElement("div");s.id=n,s.innerHTML=`\n <div class="mask"></div>\n <div class="message">${e}</div>\n `;const r=document.createElement("style");return r.innerHTML=`\n #${n} {\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: 9999;\n transition: opacity 0.3s;\n }\n #${n} .mask {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background-color: rgba(0, 0, 0, 0.45);\n }\n #${n} .message {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n color: #fff;\n }\n\n ${t}\n `,document.head.appendChild(r),document.body.append(s),{close:()=>{document.body.removeChild(s)},updateMsg:e=>{s.querySelector(".message").innerHTML=e}}},e.downloadSingleFile=(e,n)=>t(void 0,void 0,void 0,function*(){if(!e||!r.validator.isUrl(e))throw new Error("无效的URL");try{const t=yield fetch(e);if(!t.ok)throw new Error(`下载失败: ${t.status} ${t.statusText}`);let o=n;if(!o){o=i(e);const t=o.indexOf("?");-1!==t&&(o=o.substring(0,t)),o||(o="downloaded_file")}const s=yield t.blob(),r=URL.createObjectURL(s),a=document.createElement("a");a.href=r,a.download=o,document.body.appendChild(a),a.click(),setTimeout(()=>{URL.revokeObjectURL(r),a.remove()},100)}catch(e){throw console.error("文件下载失败:",e),e}}),e.extractFileNameFromPath=i,e.formatDateTypeSafe=function(e,t){return function(e,t){const n=t||new Date,o=(e,t=2)=>e.toString().padStart(t,"0"),s={year:n.getFullYear(),month:n.getMonth()+1,day:n.getDate(),hours:n.getHours(),minutes:n.getMinutes(),seconds:n.getSeconds(),milliseconds:n.getMilliseconds()},r={YYYY:s.year.toString(),YY:s.year.toString().slice(-2),MM:o(s.month),M:s.month.toString(),DD:o(s.day),D:s.day.toString(),HH:o(s.hours),H:s.hours.toString(),mm:o(s.minutes),m:s.minutes.toString(),ss:o(s.seconds),s:s.seconds.toString(),SSS:o(s.milliseconds,3)};return Object.keys(r).sort((e,t)=>t.length-e.length).reduce((e,t)=>e.replace(new RegExp(t,"g"),r[t]),e)}(e,t)},e.getElapsedTimeSince=e=>{const t=Date.now();a(e)||(e=t);const n=Math.max(0,t-(c(e)?1e3*e:e));return{hours:Math.floor(n/36e5),minutes:Math.floor(n%36e5/6e4),seconds:Math.floor(n%6e4/1e3)}},e.getUuid=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)})},e.isMillisecondTimestamp=e=>a(e)&&13===e.toString().length,e.isSecondTimestamp=c,e.isValidTimestamp=a,e.jsonToQueryString=e=>new URLSearchParams(e).toString(),e.precisionFormat=function(e,t,n=!0,o=!0){var s=e<0&&o?-1:1;const r=Math.pow(10,t);return n?Math.round(e*r*s)/r*s:Math.floor(e*r*s)/r*s},e.sleep=e=>new Promise(t=>{setTimeout(()=>{t(!0)},1e3*e)}),e.xhrInterceptor=u});
1
+ !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).ZiyaUtils={})}(this,function(e){"use strict";function t(e,t,n,o){return new(n||(n=Promise))(function(s,i){function r(e){try{c(o.next(e))}catch(e){i(e)}}function a(e){try{c(o.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}c((o=o.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const n={PHONE:/^1[3-9]\d{9}$/,EMAIL:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,ID_CARD:/(^\d{15}$)|(^\d{17}(\d|X|x)$)/,URL:/^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/,IPV4:/^(\d{1,3}\.){3}\d{1,3}$/,STRONG_PASSWORD:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/,CHINESE:/^[\u4e00-\u9fa5]+$/};class o{}class s extends o{static isPhone(e){return n.PHONE.test(e)}static isEmail(e){return n.EMAIL.test(e)}static isIdCard(e){return n.ID_CARD.test(e)}static isUrl(e){return n.URL.test(e)}static isIpv4(e){return n.IPV4.test(e)}static isStrongPassword(e){return n.STRONG_PASSWORD.test(e)}static isChinese(e){return n.CHINESE.test(e)}}var i={patterns:n,validator:s};const r=e=>{if(!e)return"";const t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return-1===t?e:e.slice(t+1)};function a(e){if("string"==typeof e){if(!/^\d+$/.test(e))return!1;e=Number(e)}if("number"!=typeof e||isNaN(e))return!1;const t=41024448e5;return 13===e.toString().length?e>=0&&e<=t:10===e.toString().length&&(e>=0&&e<=4102444800)}const c=e=>a(e)&&10===e.toString().length;class l{constructor(e={}){var t;this.interceptRules=[],this.isActive=!1,this.originalXMLHttpRequest=window.XMLHttpRequest,this.enableLogging=null===(t=e.enableLogging)||void 0===t||t}start(){if(this.isActive)return void this.log("拦截器已经启动");const e=this;window.XMLHttpRequest=function(){const t=new e.originalXMLHttpRequest;let n="";const o=t.open;t.open=function(e,t,s=!0,i,r){return n="string"==typeof t?t:t.toString(),o.call(this,e,t,s,i,r)};const s=t.send;return t.send=function(o){const i=e.findMatchingRule(n);if(!i)return s.call(this,o);let r=o;if(i.requestCallback&&o)try{r=i.requestCallback(o,n)}catch(e){console.error("XHR请求拦截器处理失败:",e),r=o}const a=t.onreadystatechange;return t.onreadystatechange=function(o){if(4===t.readyState&&t.status>=200&&t.status<300)try{const o=JSON.parse(t.responseText),s=i.responseCallback(o,n);Object.defineProperty(t,"responseText",{writable:!0,configurable:!0,value:JSON.stringify(s)}),Object.defineProperty(t,"response",{writable:!0,configurable:!0,value:JSON.stringify(s)}),e.log(`已拦截并修改响应: ${n}`)}catch(t){e.log("拦截器处理失败:",t)}a&&a.call(this,o)},s.call(this,r)},t},Object.setPrototypeOf(window.XMLHttpRequest,this.originalXMLHttpRequest),window.XMLHttpRequest.prototype=this.originalXMLHttpRequest.prototype,this.isActive=!0,this.log("XHR拦截器已启动")}stop(){this.isActive?(window.XMLHttpRequest=this.originalXMLHttpRequest,this.isActive=!1,this.log("XHR拦截器已停止,已恢复原始XMLHttpRequest")):this.log("拦截器未启动")}setRules(e){this.interceptRules=[...e],this.log("已设置拦截规则:",e.map(e=>e.url))}addRule(e,t,n){this.interceptRules.push({url:e,responseCallback:t,requestCallback:n}),this.log(`已添加拦截规则: ${e}`)}removeRule(e){const t=this.interceptRules.length;this.interceptRules=this.interceptRules.filter(t=>t.url!==e);const n=this.interceptRules.length<t;return n?this.log(`已移除拦截规则: ${e}`):this.log(`未找到拦截规则: ${e}`),n}clearRules(){this.interceptRules=[],this.log("已清除所有拦截规则")}getRules(){return[...this.interceptRules]}getStatus(){return{isActive:this.isActive,rulesCount:this.interceptRules.length}}findMatchingRule(e){return this.interceptRules.find(t=>e.includes(t.url))}log(e,...t){this.enableLogging&&console.log(`[XHRInterceptor] ${e}`,...t)}}const d=new l({enableLogging:!0}),u="ziya-utils";e.Lib_Name=u,e.RegexPatterns=n,e.RegexValidator=s,e.ScriptDomBuilder=class{constructor(e=document.body,t="glk-script-container"){this.container=null,this.elements=new Map,this.data=new Map,this.styleElement=null,this.parentNode=e,this.containerId=t}createMain(e,t="",n={}){return t&&this.createStyles(t),this.container=this.createElement("div",Object.assign({id:this.containerId},n)),e.forEach((e,t)=>{const n=this.createItem(e,t);n&&this.container.appendChild(n)}),this.parentNode.appendChild(this.container),{container:this.container,get:e=>this.getChild(e),getValue:e=>this.getValue(e),setValue:(e,t)=>this.setValue(e,t),show:e=>this.show(e),hide:e=>this.hide(e),remove:()=>this.remove(),on:(e,t,n)=>this.on(e,t,n),getData:e=>this.getData(e),setData:(e,t)=>this.setData(e,t)}}createStyles(e){this.styleElement=document.createElement("style"),this.styleElement.textContent=e,document.head.appendChild(this.styleElement)}createItem(e,t){const{type:n,keyword:o}=e;!function(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(o=Object.getOwnPropertySymbols(e);s<o.length;s++)t.indexOf(o[s])<0&&Object.prototype.propertyIsEnumerable.call(e,o[s])&&(n[o[s]]=e[o[s]])}}(e,["type","keyword"]);let s=null;switch(n){case"input":s=this.createInput(e);break;case"button":s=this.createButton(e);break;case"select":s=this.createSelect(e);break;case"textarea":s=this.createTextarea(e);break;case"checkbox":s=this.createCheckbox(e);break;case"label":s=this.createLabel(e);break;case"div":s=this.createDiv(e);break;default:return console.warn(`未支持的元素类型: ${n}`),null}return o&&s&&(this.setChild(o,s),e.saveToLocal&&this.isFormElement(n)&&this.handleLocalStorage(s,e,n)),s}isFormElement(e){return["input","textarea","select","checkbox"].includes(e)}handleLocalStorage(e,t,n){const o=this.getStorageKey(t.keyword),s=this.getFromLocalStorage(o);if(null!==s)if("checkbox"===n){const t=e.querySelector('input[type="checkbox"]');t&&(t.checked="true"===s)}else{e.value=s}else if("checkbox"===n){const n=e.querySelector('input[type="checkbox"]');n&&(n.checked=t.checked||!1)}else{e.value=t.value||""}if("checkbox"===n){const t=e.querySelector('input[type="checkbox"]');t&&t.addEventListener("change",e=>{const t=e.target;this.saveToLocalStorage(o,t.checked.toString())})}else{const t="select"===n?"change":"input";e.addEventListener(t,e=>{const t=e.target;this.saveToLocalStorage(o,t.value)})}}createInput(e){const t=this.createElement("input",Object.assign({type:e.inputType||"text",name:e.keyword,placeholder:e.placeholder||"",value:e.value||""},e.props));return this.bindEvents(t,e),t}createButton(e){const t=this.createElement("button",Object.assign({textContent:e.text||e.keyword||"Button",name:e.keyword},e.props));return this.bindEvents(t,e),t}createSelect(e){const t=this.createElement("select",Object.assign({name:e.keyword},e.props));return e.options&&e.options.forEach(e=>{const n=document.createElement("option");"string"==typeof e?(n.value=e,n.textContent=e):(n.value=e.value||e.text||"",n.textContent=e.text||e.value||"",e.selected&&(n.selected=!0)),t.appendChild(n)}),this.bindEvents(t,e),t}createTextarea(e){const t=this.createElement("textarea",Object.assign({name:e.keyword,placeholder:e.placeholder||"",value:e.value||"",rows:e.rows||3},e.props));return this.bindEvents(t,e),t}createCheckbox(e){const t=document.createElement("div"),n=this.createElement("input",Object.assign({type:"checkbox",id:e.keyword,name:e.keyword,checked:e.checked||!1},e.props)),o=document.createElement("label");return o.setAttribute("for",e.keyword||""),o.textContent=e.text||e.keyword||"Checkbox",this.bindEvents(n,e),t.appendChild(n),t.appendChild(o),e.keyword&&this.setChild(e.keyword,n),t}createLabel(e){return this.createElement("label",Object.assign({textContent:e.text||e.keyword||"",name:e.keyword},e.props))}createDiv(e){const t=this.createElement("div",Object.assign({textContent:e.text||"",innerHTML:e.html||void 0,name:e.keyword},e.props));return this.bindEvents(t,e),t}createElement(e,t={}){const n=document.createElement(e);return Object.keys(t).forEach(e=>{"innerHTML"===e?n.innerHTML=t[e]:n[e]=t[e]}),n}bindEvents(e,t){["onClick","onChange","onInput","onFocus","onBlur","onMouseEnter","onMouseLeave"].forEach(n=>{const o=t[n];if(o){const t=n.slice(2).toLowerCase();e.addEventListener(t,o)}})}getChild(e){return this.elements.get(e)||null}setChild(e,t){this.elements.has(e)||this.elements.set(e,t)}getValue(e){const t=this.getChild(e);if(!t)return null;if("checkbox"===t.type)return t.checked;return t.value||t.textContent||null}setValue(e,t){const n=this.getChild(e);if(n)if("checkbox"===n.type)n.checked=Boolean(t);else{const e=n;void 0!==e.value?e.value=String(t):n.textContent=String(t)}}show(e){if(e){const t=this.getChild(e);if(t){const e="checkbox"===t.type?t.parentElement:t;e&&(e.style.display="")}}else this.container&&(this.container.style.display="")}hide(e){if(e){const t=this.getChild(e);if(t){const e="checkbox"===t.type?t.parentElement:t;e&&(e.style.display="none")}}else this.container&&(this.container.style.display="none")}remove(){this.container&&(this.container.remove(),this.container=null,this.elements.clear()),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}on(e,t,n){const o=this.getChild(e);o&&o.addEventListener(t,n)}getStorageKey(e){return`${this.containerId}_${e}`}saveToLocalStorage(e,t){try{localStorage.setItem(e,t)}catch(e){console.warn("无法保存到本地存储:",e)}}getFromLocalStorage(e){try{return localStorage.getItem(e)}catch(e){return console.warn("无法从本地存储读取:",e),null}}setData(e,t){this.data.set(e,t)}getData(e){return this.data.get(e)}},e.XHRInterceptor=l,e.addStyleStr=(e="")=>{let t=document.createElement("style");return t.innerHTML=e,document.getElementsByTagName("head")[0].appendChild(t),t},e.copyToClipboard=function(e){return t(this,void 0,void 0,function*(){try{var t=JSON.stringify(e);if(navigator.clipboard&&(window.isSecureContext||"https:"===location.protocol||"localhost"===location.hostname))return yield navigator.clipboard.writeText(t),!0;var n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.left="-9999px",n.style.top="-9999px",document.body.appendChild(n),n.select();var o=document.execCommand("copy");return document.body.removeChild(n),o}catch(e){return console.error("复制失败:",e),!1}})},e.createAsyncTask=function(e=()=>null,n=()=>{},o={}){const{duration:s=1,timeout:i,immediate:r=!1}=o;return new Promise((o,a)=>{let c=null,l=null;const d=()=>{c&&(clearInterval(c),c=null),l&&(clearTimeout(l),l=null)},u=()=>t(this,void 0,void 0,function*(){try{const t=yield e();if(t){d();const e=yield n(t);o(e)}}catch(e){d(),a(e)}});i&&i>0&&(l=setTimeout(()=>{d(),a(new Error(`${i} 秒后任务将会超时。`))},1e3*i)),r&&u(),c=setInterval(u,1e3*s)})},e.createFormData=e=>{const t=new FormData;if("string"==typeof e){const n=new URLSearchParams(e);for(const[e,o]of n)t.append(e,o)}else"object"==typeof e&&null!==e&&Object.keys(e).forEach(n=>{const o=e[n];null!=o?Array.isArray(o)?o.forEach(e=>t.append(n,String(e))):o instanceof File||o instanceof Blob?t.append(n,o):"object"==typeof o?t.append(n,JSON.stringify(o)):t.append(n,String(o)):t.append(n,"")});return t},e.createMaskLoading=(e="加载中...",t="")=>{const n=`${u}-mask-loading-container`,o=document.getElementById(n);o&&document.body.removeChild(o);const s=document.createElement("div");s.id=n,s.innerHTML=`\n <div class="mask"></div>\n <div class="message">${e}</div>\n `;const i=document.createElement("style");return i.innerHTML=`\n #${n} {\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: 9999;\n transition: opacity 0.3s;\n }\n #${n} .mask {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background-color: rgba(0, 0, 0, 0.45);\n }\n #${n} .message {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n color: #fff;\n }\n\n ${t}\n `,document.head.appendChild(i),document.body.append(s),{close:()=>{document.body.removeChild(s)},updateMsg:e=>{s.querySelector(".message").innerHTML=e}}},e.downloadSingleFile=(e,n)=>t(void 0,void 0,void 0,function*(){if(!e||!i.validator.isUrl(e))throw new Error("无效的URL");try{const t=yield fetch(e);if(!t.ok)throw new Error(`下载失败: ${t.status} ${t.statusText}`);let o=n;if(!o){o=r(e);const t=o.indexOf("?");-1!==t&&(o=o.substring(0,t)),o||(o="downloaded_file")}const s=yield t.blob(),i=URL.createObjectURL(s),a=document.createElement("a");a.href=i,a.download=o,document.body.appendChild(a),a.click(),setTimeout(()=>{URL.revokeObjectURL(i),a.remove()},100)}catch(e){throw console.error("文件下载失败:",e),e}}),e.extractFileNameFromPath=r,e.formatDateTypeSafe=function(e,t){return function(e,t){const n=t||new Date,o=(e,t=2)=>e.toString().padStart(t,"0"),s={year:n.getFullYear(),month:n.getMonth()+1,day:n.getDate(),hours:n.getHours(),minutes:n.getMinutes(),seconds:n.getSeconds(),milliseconds:n.getMilliseconds()},i={YYYY:s.year.toString(),YY:s.year.toString().slice(-2),MM:o(s.month),M:s.month.toString(),DD:o(s.day),D:s.day.toString(),HH:o(s.hours),H:s.hours.toString(),mm:o(s.minutes),m:s.minutes.toString(),ss:o(s.seconds),s:s.seconds.toString(),SSS:o(s.milliseconds,3)};return Object.keys(i).sort((e,t)=>t.length-e.length).reduce((e,t)=>e.replace(new RegExp(t,"g"),i[t]),e)}(e,t)},e.getElapsedTimeSince=e=>{const t=Date.now();a(e)||(e=t);const n=Math.max(0,t-(c(e)?1e3*e:e));return{hours:Math.floor(n/36e5),minutes:Math.floor(n%36e5/6e4),seconds:Math.floor(n%6e4/1e3)}},e.getUuid=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)})},e.isMillisecondTimestamp=e=>a(e)&&13===e.toString().length,e.isSecondTimestamp=c,e.isValidTimestamp=a,e.jsonToQueryString=e=>new URLSearchParams(e).toString(),e.precisionFormat=function(e,t,n=!0,o=!0){var s=e<0&&o?-1:1;const i=Math.pow(10,t);return n?Math.round(e*i*s)/i*s:Math.floor(e*i*s)/i*s},e.showTip=(e,t=2,n)=>new Promise(o=>{const s=document.getElementById("show_tip");s&&document.body.removeChild(s),window.show_tip_timer&&clearTimeout(window.show_tip_timer);const i=document.createElement("div");if(document.body.appendChild(i),i.id="show_tip",Object.assign(i.style,{position:"fixed",maxWidth:"80vw",top:"50%",left:"50%",transform:"translate(-50%, -50%)",lineHeight:"20px",zIndex:"999999999",color:"#fff",backgroundColor:"#303133",borderRadius:"4px",padding:"10px",textAlign:"center",opacity:"0.9",fontSize:"1em"}),n){const{left:e,top:t,offsetX:o=0,offsetY:s=0}=n;Object.assign(i.style,{top:t+s+"px",left:e+o+"px",transform:"none"})}i.innerText=e,window.show_tip_timer=setTimeout(()=>{const e=document.getElementById("show_tip");e&&(document.body.removeChild(e),o())},1e3*t-100)}),e.sleep=e=>new Promise(t=>{setTimeout(()=>{t(!0)},1e3*e)}),e.xhrInterceptor=d});
@@ -28,3 +28,4 @@ declare const createMaskLoading: (msg?: string, style?: string) => {
28
28
  };
29
29
  export { addStyleStr, createMaskLoading };
30
30
  export * from "./script-dom-builder";
31
+ export * from "./showtip";
@@ -0,0 +1,15 @@
1
+ interface Position {
2
+ left: number;
3
+ top: number;
4
+ offsetX?: number;
5
+ offsetY?: number;
6
+ }
7
+ /**
8
+ * 小提示
9
+ * @param message
10
+ * @param duration
11
+ * @param pos
12
+ * @returns
13
+ */
14
+ declare const showTip: (message: string, duration?: number, pos?: Position) => Promise<void>;
15
+ export { showTip };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * 小提示
3
+ * @param message
4
+ * @param duration
5
+ * @param pos
6
+ * @returns
7
+ */
8
+ const showTip = (message, duration = 2, pos) => {
9
+ return new Promise((resolve) => {
10
+ const show_tip = document.getElementById("show_tip");
11
+ if (show_tip) {
12
+ document.body.removeChild(show_tip);
13
+ }
14
+ if (window.show_tip_timer) {
15
+ clearTimeout(window.show_tip_timer);
16
+ }
17
+ const tipDom = document.createElement("div");
18
+ document.body.appendChild(tipDom);
19
+ tipDom.id = "show_tip";
20
+ Object.assign(tipDom.style, {
21
+ position: "fixed",
22
+ maxWidth: "80vw",
23
+ top: "50%",
24
+ left: "50%",
25
+ transform: "translate(-50%, -50%)",
26
+ lineHeight: "20px",
27
+ zIndex: "999999999",
28
+ color: "#fff",
29
+ backgroundColor: "#303133",
30
+ borderRadius: "4px",
31
+ padding: "10px",
32
+ textAlign: "center",
33
+ opacity: "0.9",
34
+ fontSize: "1em",
35
+ });
36
+ if (pos) {
37
+ const { left, top, offsetX = 0, offsetY = 0 } = pos;
38
+ Object.assign(tipDom.style, {
39
+ top: top + offsetY + "px",
40
+ left: left + offsetX + "px",
41
+ transform: "none",
42
+ });
43
+ }
44
+ tipDom.innerText = message;
45
+ window.show_tip_timer = setTimeout(() => {
46
+ const show_tip = document.getElementById("show_tip");
47
+ if (show_tip) {
48
+ document.body.removeChild(show_tip);
49
+ resolve();
50
+ }
51
+ }, duration * 1000 - 100);
52
+ });
53
+ };
54
+
55
+ export { showTip };
package/es/index.js CHANGED
@@ -10,3 +10,4 @@ export { Lib_Name } from './constant/index.js';
10
10
  export { addStyleStr, createMaskLoading } from './document/index.js';
11
11
  export { createAsyncTask } from './async/index.js';
12
12
  export { ScriptDomBuilder } from './document/script-dom-builder.js';
13
+ export { showTip } from './document/showtip.js';
@@ -28,3 +28,4 @@ declare const createMaskLoading: (msg?: string, style?: string) => {
28
28
  };
29
29
  export { addStyleStr, createMaskLoading };
30
30
  export * from "./script-dom-builder";
31
+ export * from "./showtip";
@@ -0,0 +1,15 @@
1
+ interface Position {
2
+ left: number;
3
+ top: number;
4
+ offsetX?: number;
5
+ offsetY?: number;
6
+ }
7
+ /**
8
+ * 小提示
9
+ * @param message
10
+ * @param duration
11
+ * @param pos
12
+ * @returns
13
+ */
14
+ declare const showTip: (message: string, duration?: number, pos?: Position) => Promise<void>;
15
+ export { showTip };
@@ -0,0 +1,57 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 小提示
5
+ * @param message
6
+ * @param duration
7
+ * @param pos
8
+ * @returns
9
+ */
10
+ const showTip = (message, duration = 2, pos) => {
11
+ return new Promise((resolve) => {
12
+ const show_tip = document.getElementById("show_tip");
13
+ if (show_tip) {
14
+ document.body.removeChild(show_tip);
15
+ }
16
+ if (window.show_tip_timer) {
17
+ clearTimeout(window.show_tip_timer);
18
+ }
19
+ const tipDom = document.createElement("div");
20
+ document.body.appendChild(tipDom);
21
+ tipDom.id = "show_tip";
22
+ Object.assign(tipDom.style, {
23
+ position: "fixed",
24
+ maxWidth: "80vw",
25
+ top: "50%",
26
+ left: "50%",
27
+ transform: "translate(-50%, -50%)",
28
+ lineHeight: "20px",
29
+ zIndex: "999999999",
30
+ color: "#fff",
31
+ backgroundColor: "#303133",
32
+ borderRadius: "4px",
33
+ padding: "10px",
34
+ textAlign: "center",
35
+ opacity: "0.9",
36
+ fontSize: "1em",
37
+ });
38
+ if (pos) {
39
+ const { left, top, offsetX = 0, offsetY = 0 } = pos;
40
+ Object.assign(tipDom.style, {
41
+ top: top + offsetY + "px",
42
+ left: left + offsetX + "px",
43
+ transform: "none",
44
+ });
45
+ }
46
+ tipDom.innerText = message;
47
+ window.show_tip_timer = setTimeout(() => {
48
+ const show_tip = document.getElementById("show_tip");
49
+ if (show_tip) {
50
+ document.body.removeChild(show_tip);
51
+ resolve();
52
+ }
53
+ }, duration * 1000 - 100);
54
+ });
55
+ };
56
+
57
+ exports.showTip = showTip;
package/lib/index.js CHANGED
@@ -12,6 +12,7 @@ var index$8 = require('./constant/index.js');
12
12
  var index$9 = require('./document/index.js');
13
13
  var index$a = require('./async/index.js');
14
14
  var scriptDomBuilder = require('./document/script-dom-builder.js');
15
+ var showtip = require('./document/showtip.js');
15
16
 
16
17
 
17
18
 
@@ -37,3 +38,4 @@ exports.addStyleStr = index$9.addStyleStr;
37
38
  exports.createMaskLoading = index$9.createMaskLoading;
38
39
  exports.createAsyncTask = index$a.createAsyncTask;
39
40
  exports.ScriptDomBuilder = scriptDomBuilder.ScriptDomBuilder;
41
+ exports.showTip = showtip.showTip;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ziya-utils",
3
- "version": "1.1.7",
3
+ "version": "1.1.9",
4
4
  "description": "A javascript tool library.",
5
5
  "main": "./lib/index.js",
6
6
  "browser": "dist/ziya-utils.js",