ziya-utils 1.1.9 → 1.1.10

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,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});
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 d=new l({enableLogging:!0}),u="ziya-utils",h=999999999;e.Global_Mask_Zindex=h,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.compelSetInputValue=(e,t)=>{var n;const o=null===(n=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value"))||void 0===n?void 0:n.set;o&&o.call(e,t);const s=new Event("input",{bubbles:!0});e.dispatchEvent(s)},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 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)}});r&&r>0&&(l=setTimeout(()=>{d(),a(new Error(`${r} 秒后任务将会超时。`))},1e3*r)),i&&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 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: 999999999;\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.generateNumberRange=(e,t,n=.005)=>{const o=[];if(e===t)return[e];e>t&&([e,t]=[t,e]);if(n<=0||n>=t-e)return[e,t];const s=1/n;for(let n=Math.round(e*s);n<=Math.round(t*s);n++)o.push(n/s);return o},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.getFromLocalStorage=e=>{try{return localStorage.getItem(e)}catch(e){return console.warn("无法从本地存储读取:",e),null}},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=(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.saveToLocalStorage=(e,t)=>{try{localStorage.setItem(e,t)}catch(e){console.warn("无法保存到本地存储:",e)}},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 r=document.createElement("div");if(document.body.appendChild(r),r.id="show_tip",Object.assign(r.style,{position:"fixed",maxWidth:"80vw",top:"50%",left:"50%",transform:"translate(-50%, -50%)",lineHeight:"20px",zIndex:h,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(r.style,{top:t+s+"px",left:e+o+"px",transform:"none"})}r.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.waitForCondition=function(e,t=10){return new Promise(n=>{const o=()=>{e()?n():setTimeout(o,t)};o()})},e.xhrInterceptor=d});
@@ -16,5 +16,12 @@ interface AsyncTaskOptions {
16
16
  * @returns Promise,resolve 初始化函数的返回值
17
17
  */
18
18
  declare function createAsyncTask<T, R>(checkFun?: CheckFunction<T>, initFun?: InitFunction<T, R>, options?: AsyncTaskOptions): Promise<R>;
19
- export { createAsyncTask };
19
+ /**
20
+ * 等待一个条件满足
21
+ * @param conditionFn 条件
22
+ * @param interval 检查间隔
23
+ * @returns
24
+ */
25
+ declare function waitForCondition(conditionFn: () => boolean, interval?: number): Promise<void>;
26
+ export { createAsyncTask, waitForCondition };
20
27
  export type { CheckFunction, InitFunction, AsyncTaskOptions };
package/es/async/index.js CHANGED
@@ -53,5 +53,24 @@ function createAsyncTask(checkFun = () => null, initFun = () => undefined, optio
53
53
  timer = setInterval(check, duration * 1000);
54
54
  });
55
55
  }
56
+ /**
57
+ * 等待一个条件满足
58
+ * @param conditionFn 条件
59
+ * @param interval 检查间隔
60
+ * @returns
61
+ */
62
+ function waitForCondition(conditionFn, interval = 10) {
63
+ return new Promise((resolve) => {
64
+ const check = () => {
65
+ if (conditionFn()) {
66
+ resolve();
67
+ }
68
+ else {
69
+ setTimeout(check, interval);
70
+ }
71
+ };
72
+ check();
73
+ });
74
+ }
56
75
 
57
- export { createAsyncTask };
76
+ export { createAsyncTask, waitForCondition };
@@ -1,3 +1,5 @@
1
1
  /** 工具名称 */
2
2
  declare const Lib_Name = "ziya-utils";
3
- export { Lib_Name };
3
+ /** 全局用到的遮罩层级 */
4
+ declare const Global_Mask_Zindex = 999999999;
5
+ export { Lib_Name, Global_Mask_Zindex };
@@ -1,4 +1,6 @@
1
1
  /** 工具名称 */
2
2
  const Lib_Name = "ziya-utils";
3
+ /** 全局用到的遮罩层级 */
4
+ const Global_Mask_Zindex = 999999999;
3
5
 
4
- export { Lib_Name };
6
+ export { Global_Mask_Zindex, Lib_Name };
@@ -21,5 +21,13 @@
21
21
  * formatDecimals(-0.15, 1, true, false) // -0.1
22
22
  * @returns
23
23
  */
24
- declare function precisionFormat(num: number, count: number, round?: boolean, consistent?: boolean): number;
25
- export { precisionFormat };
24
+ declare const precisionFormat: (num: number, count: number, round?: boolean, consistent?: boolean) => number;
25
+ /**
26
+ * 根据最大值最小值和步长生成指定区间的数值序列
27
+ * @param min 最小值
28
+ * @param max 最大值
29
+ * @param step 步长,默认1
30
+ * @returns
31
+ */
32
+ declare const generateNumberRange: (min: number, max: number, step?: number) => number[];
33
+ export { precisionFormat, generateNumberRange };
package/es/count/index.js CHANGED
@@ -21,10 +21,38 @@
21
21
  * formatDecimals(-0.15, 1, true, false) // -0.1
22
22
  * @returns
23
23
  */
24
- function precisionFormat(num, count, round = true, consistent = true) {
24
+ const precisionFormat = (num, count, round = true, consistent = true) => {
25
25
  var sign = num < 0 ? (consistent ? -1 : 1) : 1;
26
26
  const val = Math.pow(10, count);
27
27
  return round ? (Math.round(num * val * sign) / val) * sign : (Math.floor(num * val * sign) / val) * sign;
28
- }
28
+ };
29
+ /**
30
+ * 根据最大值最小值和步长生成指定区间的数值序列
31
+ * @param min 最小值
32
+ * @param max 最大值
33
+ * @param step 步长,默认1
34
+ * @returns
35
+ */
36
+ const generateNumberRange = (min, max, step = 0.005) => {
37
+ const result = [];
38
+ // 如果 min 和 max 相等
39
+ if (min === max) {
40
+ return [min];
41
+ }
42
+ // 如果 min > max,就交换
43
+ if (min > max) {
44
+ [min, max] = [max, min];
45
+ }
46
+ // 步长检查
47
+ const diff = max - min;
48
+ if (step <= 0 || step >= diff) {
49
+ return [min, max];
50
+ }
51
+ const factor = 1 / step;
52
+ for (let i = Math.round(min * factor); i <= Math.round(max * factor); i++) {
53
+ result.push(i / factor);
54
+ }
55
+ return result;
56
+ };
29
57
 
30
- export { precisionFormat };
58
+ export { generateNumberRange, precisionFormat };
@@ -26,6 +26,12 @@ declare const createMaskLoading: (msg?: string, style?: string) => {
26
26
  */
27
27
  updateMsg: (msg: string) => void;
28
28
  };
29
- export { addStyleStr, createMaskLoading };
29
+ /**
30
+ * 强制设置input的value值
31
+ * @param inputElement 目标input
32
+ * @param value 设置的值
33
+ */
34
+ declare const compelSetInputValue: (inputElement: HTMLInputElement, value: string) => void;
35
+ export { addStyleStr, createMaskLoading, compelSetInputValue };
30
36
  export * from "./script-dom-builder";
31
37
  export * from "./showtip";
@@ -1,4 +1,4 @@
1
- import { Lib_Name } from '../constant/index.js';
1
+ import { Global_Mask_Zindex, Lib_Name } from '../constant/index.js';
2
2
  import '../node_modules/tslib/tslib.es6.js';
3
3
 
4
4
  /**
@@ -41,7 +41,7 @@ const createMaskLoading = (msg = "加载中...", style = "") => {
41
41
  left: 0;
42
42
  width: 100%;
43
43
  height: 100%;
44
- z-index: 9999;
44
+ z-index: ${Global_Mask_Zindex};
45
45
  transition: opacity 0.3s;
46
46
  }
47
47
  #${Container_Id} .mask {
@@ -80,5 +80,19 @@ const createMaskLoading = (msg = "加载中...", style = "") => {
80
80
  },
81
81
  };
82
82
  };
83
+ /**
84
+ * 强制设置input的value值
85
+ * @param inputElement 目标input
86
+ * @param value 设置的值
87
+ */
88
+ const compelSetInputValue = (inputElement, value) => {
89
+ var _a;
90
+ const nativeInputValueSetter = (_a = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")) === null || _a === void 0 ? void 0 : _a.set;
91
+ if (nativeInputValueSetter) {
92
+ nativeInputValueSetter.call(inputElement, value);
93
+ }
94
+ const event = new Event("input", { bubbles: true });
95
+ inputElement.dispatchEvent(event);
96
+ };
83
97
 
84
- export { addStyleStr, createMaskLoading };
98
+ export { addStyleStr, compelSetInputValue, createMaskLoading };
@@ -1,3 +1,5 @@
1
+ import { Global_Mask_Zindex } from '../constant/index.js';
2
+
1
3
  /**
2
4
  * 小提示
3
5
  * @param message
@@ -24,7 +26,7 @@ const showTip = (message, duration = 2, pos) => {
24
26
  left: "50%",
25
27
  transform: "translate(-50%, -50%)",
26
28
  lineHeight: "20px",
27
- zIndex: "999999999",
29
+ zIndex: Global_Mask_Zindex,
28
30
  color: "#fff",
29
31
  backgroundColor: "#303133",
30
32
  borderRadius: "4px",
package/es/index.d.ts CHANGED
@@ -9,3 +9,4 @@ export * from "./xhr";
9
9
  export * from "./constant";
10
10
  export * from "./document";
11
11
  export * from "./async";
12
+ export * from "./localstorage";
package/es/index.js CHANGED
@@ -4,10 +4,11 @@ export { formatDateTypeSafe, getElapsedTimeSince, isMillisecondTimestamp, isSeco
4
4
  export { copyToClipboard, getUuid } from './security/index.js';
5
5
  export { RegexPatterns, RegexValidator } from './regexp/index.js';
6
6
  export { createFormData, jsonToQueryString } from './form/index.js';
7
- export { precisionFormat } from './count/index.js';
7
+ export { generateNumberRange, precisionFormat } from './count/index.js';
8
8
  export { XHRInterceptor, xhrInterceptor } from './xhr/index.js';
9
- export { Lib_Name } from './constant/index.js';
10
- export { addStyleStr, createMaskLoading } from './document/index.js';
11
- export { createAsyncTask } from './async/index.js';
9
+ export { Global_Mask_Zindex, Lib_Name } from './constant/index.js';
10
+ export { addStyleStr, compelSetInputValue, createMaskLoading } from './document/index.js';
11
+ export { createAsyncTask, waitForCondition } from './async/index.js';
12
+ export { getFromLocalStorage, saveToLocalStorage } from './localstorage/index.js';
12
13
  export { ScriptDomBuilder } from './document/script-dom-builder.js';
13
14
  export { showTip } from './document/showtip.js';
@@ -0,0 +1,3 @@
1
+ declare const saveToLocalStorage: (key: string, value: string) => void;
2
+ declare const getFromLocalStorage: (key: string) => string | null;
3
+ export { saveToLocalStorage, getFromLocalStorage };
@@ -0,0 +1,19 @@
1
+ const saveToLocalStorage = (key, value) => {
2
+ try {
3
+ localStorage.setItem(key, value);
4
+ }
5
+ catch (e) {
6
+ console.warn("无法保存到本地存储:", e);
7
+ }
8
+ };
9
+ const getFromLocalStorage = (key) => {
10
+ try {
11
+ return localStorage.getItem(key);
12
+ }
13
+ catch (e) {
14
+ console.warn("无法从本地存储读取:", e);
15
+ return null;
16
+ }
17
+ };
18
+
19
+ export { getFromLocalStorage, saveToLocalStorage };
@@ -16,5 +16,12 @@ interface AsyncTaskOptions {
16
16
  * @returns Promise,resolve 初始化函数的返回值
17
17
  */
18
18
  declare function createAsyncTask<T, R>(checkFun?: CheckFunction<T>, initFun?: InitFunction<T, R>, options?: AsyncTaskOptions): Promise<R>;
19
- export { createAsyncTask };
19
+ /**
20
+ * 等待一个条件满足
21
+ * @param conditionFn 条件
22
+ * @param interval 检查间隔
23
+ * @returns
24
+ */
25
+ declare function waitForCondition(conditionFn: () => boolean, interval?: number): Promise<void>;
26
+ export { createAsyncTask, waitForCondition };
20
27
  export type { CheckFunction, InitFunction, AsyncTaskOptions };
@@ -55,5 +55,25 @@ function createAsyncTask(checkFun = () => null, initFun = () => undefined, optio
55
55
  timer = setInterval(check, duration * 1000);
56
56
  });
57
57
  }
58
+ /**
59
+ * 等待一个条件满足
60
+ * @param conditionFn 条件
61
+ * @param interval 检查间隔
62
+ * @returns
63
+ */
64
+ function waitForCondition(conditionFn, interval = 10) {
65
+ return new Promise((resolve) => {
66
+ const check = () => {
67
+ if (conditionFn()) {
68
+ resolve();
69
+ }
70
+ else {
71
+ setTimeout(check, interval);
72
+ }
73
+ };
74
+ check();
75
+ });
76
+ }
58
77
 
59
78
  exports.createAsyncTask = createAsyncTask;
79
+ exports.waitForCondition = waitForCondition;
@@ -1,3 +1,5 @@
1
1
  /** 工具名称 */
2
2
  declare const Lib_Name = "ziya-utils";
3
- export { Lib_Name };
3
+ /** 全局用到的遮罩层级 */
4
+ declare const Global_Mask_Zindex = 999999999;
5
+ export { Lib_Name, Global_Mask_Zindex };
@@ -2,5 +2,8 @@
2
2
 
3
3
  /** 工具名称 */
4
4
  const Lib_Name = "ziya-utils";
5
+ /** 全局用到的遮罩层级 */
6
+ const Global_Mask_Zindex = 999999999;
5
7
 
8
+ exports.Global_Mask_Zindex = Global_Mask_Zindex;
6
9
  exports.Lib_Name = Lib_Name;
@@ -21,5 +21,13 @@
21
21
  * formatDecimals(-0.15, 1, true, false) // -0.1
22
22
  * @returns
23
23
  */
24
- declare function precisionFormat(num: number, count: number, round?: boolean, consistent?: boolean): number;
25
- export { precisionFormat };
24
+ declare const precisionFormat: (num: number, count: number, round?: boolean, consistent?: boolean) => number;
25
+ /**
26
+ * 根据最大值最小值和步长生成指定区间的数值序列
27
+ * @param min 最小值
28
+ * @param max 最大值
29
+ * @param step 步长,默认1
30
+ * @returns
31
+ */
32
+ declare const generateNumberRange: (min: number, max: number, step?: number) => number[];
33
+ export { precisionFormat, generateNumberRange };
@@ -23,10 +23,39 @@
23
23
  * formatDecimals(-0.15, 1, true, false) // -0.1
24
24
  * @returns
25
25
  */
26
- function precisionFormat(num, count, round = true, consistent = true) {
26
+ const precisionFormat = (num, count, round = true, consistent = true) => {
27
27
  var sign = num < 0 ? (consistent ? -1 : 1) : 1;
28
28
  const val = Math.pow(10, count);
29
29
  return round ? (Math.round(num * val * sign) / val) * sign : (Math.floor(num * val * sign) / val) * sign;
30
- }
30
+ };
31
+ /**
32
+ * 根据最大值最小值和步长生成指定区间的数值序列
33
+ * @param min 最小值
34
+ * @param max 最大值
35
+ * @param step 步长,默认1
36
+ * @returns
37
+ */
38
+ const generateNumberRange = (min, max, step = 0.005) => {
39
+ const result = [];
40
+ // 如果 min 和 max 相等
41
+ if (min === max) {
42
+ return [min];
43
+ }
44
+ // 如果 min > max,就交换
45
+ if (min > max) {
46
+ [min, max] = [max, min];
47
+ }
48
+ // 步长检查
49
+ const diff = max - min;
50
+ if (step <= 0 || step >= diff) {
51
+ return [min, max];
52
+ }
53
+ const factor = 1 / step;
54
+ for (let i = Math.round(min * factor); i <= Math.round(max * factor); i++) {
55
+ result.push(i / factor);
56
+ }
57
+ return result;
58
+ };
31
59
 
60
+ exports.generateNumberRange = generateNumberRange;
32
61
  exports.precisionFormat = precisionFormat;
@@ -26,6 +26,12 @@ declare const createMaskLoading: (msg?: string, style?: string) => {
26
26
  */
27
27
  updateMsg: (msg: string) => void;
28
28
  };
29
- export { addStyleStr, createMaskLoading };
29
+ /**
30
+ * 强制设置input的value值
31
+ * @param inputElement 目标input
32
+ * @param value 设置的值
33
+ */
34
+ declare const compelSetInputValue: (inputElement: HTMLInputElement, value: string) => void;
35
+ export { addStyleStr, createMaskLoading, compelSetInputValue };
30
36
  export * from "./script-dom-builder";
31
37
  export * from "./showtip";
@@ -43,7 +43,7 @@ const createMaskLoading = (msg = "加载中...", style = "") => {
43
43
  left: 0;
44
44
  width: 100%;
45
45
  height: 100%;
46
- z-index: 9999;
46
+ z-index: ${index.Global_Mask_Zindex};
47
47
  transition: opacity 0.3s;
48
48
  }
49
49
  #${Container_Id} .mask {
@@ -82,6 +82,21 @@ const createMaskLoading = (msg = "加载中...", style = "") => {
82
82
  },
83
83
  };
84
84
  };
85
+ /**
86
+ * 强制设置input的value值
87
+ * @param inputElement 目标input
88
+ * @param value 设置的值
89
+ */
90
+ const compelSetInputValue = (inputElement, value) => {
91
+ var _a;
92
+ const nativeInputValueSetter = (_a = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")) === null || _a === void 0 ? void 0 : _a.set;
93
+ if (nativeInputValueSetter) {
94
+ nativeInputValueSetter.call(inputElement, value);
95
+ }
96
+ const event = new Event("input", { bubbles: true });
97
+ inputElement.dispatchEvent(event);
98
+ };
85
99
 
86
100
  exports.addStyleStr = addStyleStr;
101
+ exports.compelSetInputValue = compelSetInputValue;
87
102
  exports.createMaskLoading = createMaskLoading;
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ var index = require('../constant/index.js');
4
+
3
5
  /**
4
6
  * 小提示
5
7
  * @param message
@@ -26,7 +28,7 @@ const showTip = (message, duration = 2, pos) => {
26
28
  left: "50%",
27
29
  transform: "translate(-50%, -50%)",
28
30
  lineHeight: "20px",
29
- zIndex: "999999999",
31
+ zIndex: index.Global_Mask_Zindex,
30
32
  color: "#fff",
31
33
  backgroundColor: "#303133",
32
34
  borderRadius: "4px",
package/lib/index.d.ts CHANGED
@@ -9,3 +9,4 @@ export * from "./xhr";
9
9
  export * from "./constant";
10
10
  export * from "./document";
11
11
  export * from "./async";
12
+ export * from "./localstorage";
package/lib/index.js CHANGED
@@ -11,6 +11,7 @@ var index$7 = require('./xhr/index.js');
11
11
  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
+ var index$b = require('./localstorage/index.js');
14
15
  var scriptDomBuilder = require('./document/script-dom-builder.js');
15
16
  var showtip = require('./document/showtip.js');
16
17
 
@@ -30,12 +31,18 @@ exports.RegexPatterns = index$4.RegexPatterns;
30
31
  exports.RegexValidator = index$4.RegexValidator;
31
32
  exports.createFormData = index$5.createFormData;
32
33
  exports.jsonToQueryString = index$5.jsonToQueryString;
34
+ exports.generateNumberRange = index$6.generateNumberRange;
33
35
  exports.precisionFormat = index$6.precisionFormat;
34
36
  exports.XHRInterceptor = index$7.XHRInterceptor;
35
37
  exports.xhrInterceptor = index$7.xhrInterceptor;
38
+ exports.Global_Mask_Zindex = index$8.Global_Mask_Zindex;
36
39
  exports.Lib_Name = index$8.Lib_Name;
37
40
  exports.addStyleStr = index$9.addStyleStr;
41
+ exports.compelSetInputValue = index$9.compelSetInputValue;
38
42
  exports.createMaskLoading = index$9.createMaskLoading;
39
43
  exports.createAsyncTask = index$a.createAsyncTask;
44
+ exports.waitForCondition = index$a.waitForCondition;
45
+ exports.getFromLocalStorage = index$b.getFromLocalStorage;
46
+ exports.saveToLocalStorage = index$b.saveToLocalStorage;
40
47
  exports.ScriptDomBuilder = scriptDomBuilder.ScriptDomBuilder;
41
48
  exports.showTip = showtip.showTip;
@@ -0,0 +1,3 @@
1
+ declare const saveToLocalStorage: (key: string, value: string) => void;
2
+ declare const getFromLocalStorage: (key: string) => string | null;
3
+ export { saveToLocalStorage, getFromLocalStorage };
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+
3
+ const saveToLocalStorage = (key, value) => {
4
+ try {
5
+ localStorage.setItem(key, value);
6
+ }
7
+ catch (e) {
8
+ console.warn("无法保存到本地存储:", e);
9
+ }
10
+ };
11
+ const getFromLocalStorage = (key) => {
12
+ try {
13
+ return localStorage.getItem(key);
14
+ }
15
+ catch (e) {
16
+ console.warn("无法从本地存储读取:", e);
17
+ return null;
18
+ }
19
+ };
20
+
21
+ exports.getFromLocalStorage = getFromLocalStorage;
22
+ exports.saveToLocalStorage = saveToLocalStorage;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ziya-utils",
3
- "version": "1.1.9",
3
+ "version": "1.1.10",
4
4
  "description": "A javascript tool library.",
5
5
  "main": "./lib/index.js",
6
6
  "browser": "dist/ziya-utils.js",