UNPKG

jsfast

Version:

Fastjs(jsfast) is a useful, lightweight JavaScript library for any types of project.

2 lines (1 loc) 17.3 kB
async function e(e,t,n=!1,r=!1){return new Promise(((o,s)=>{let l=!1;const c=()=>l;setTimeout((async function n(){try{let r=e(c);r instanceof Promise&&(r=await r),l||!r?setTimeout(n,t):o()}catch(e){r?(setTimeout(n,t),console.error(e)):(s(e),l=!0)}}),n?0:t)}))}function t(e,t){const n=e=>(t?t(e):console.error(e),e);try{const t=e();return t instanceof Promise?t.then((e=>e)).catch(n):t}catch(e){return n(e)}}function n(e){try{const t=e();return t instanceof Promise?new Promise(((e,n)=>{t.then((t=>e([t,null]))).catch((t=>e([void 0,t])))})):[t,null]}catch(e){return[void 0,e]}}async function r(e){try{const t=await async function(e){const{createFastjsDom:t}=await Promise.resolve().then((function(){return h}));let n=t("span");return n.html(r(e)).push(document.body,"lastElementChild"),n.el();function r(e){return e.replace(/\n/g,"<br>").replace(/ /g,"&nbsp;")}}(e);!function(e){if(!e)return;document.execCommand("copy")}(function(e){const t=document.createRange();t.setStart(e,0),t.setEnd(e,e.childNodes.length);const n=window.getSelection();return n?(n.removeAllRanges(),n.addRange(t),n):null}(t)),t.remove()}catch(e){}}function o(e,t,n=0){const r=10*n||1;return[e,t]=[e*r,t*r],(Math.floor(Math.pow(10,14)*Math.random()*Math.random())%(t-e+1)+e)/r}function s(e,t={}){const n="abcdefghijklmnopqrstuvwxyz";let r="";t.number&&(r+="0123456789"),!1!==t.letter&&(t.upper&&(r+=n.toUpperCase()),!1!==t.lower&&(r+=n)),Array.isArray(t.custom)?r+=t.custom.join(""):t?.custom&&(r+=t.custom),t.max&&(e=o(e,t.max));let s="";for(let t=0;t<e;t++)s+=r.charAt(o(0,r.length-1));return s}function l(){const e=e=>s(e,{number:!0});return`${e(8)}-${e(4)}-4${e(3)}-${e(4)}-${e(12)}`}var c={...Object.freeze({__proto__:null,callUntilEnd:e,catchError:t,secureCall:n}),...Object.freeze({__proto__:null,copy:r}),...Object.freeze({__proto__:null,rand:o,randString:s,uuid:l})};function i(e,t=document){const n=[];function r(e,t){return e.set?e.get("querySelectorAll")(t):e.querySelectorAll(t)}if("FastjsDom"===t?.construct&&(t=t._el),"FastjsDomList"===t?.construct&&(t=t._list),Array.isArray(t)?t.forEach((t=>{n.push(...s(r(t,e)))})):n.push(...s(r(t,e))),0===n.length)return null;if(n[0].id&&e.includes(`#${n[0].id}`)||["body","head"].includes(e))return n[0];const o=[];return n.forEach((e=>{o.push(e)})),o;function s(e){const t=[];return e.forEach((e=>{t.push(e)})),t}}function a(e){return void 0===e}function u(e){const t=[];for(const n of e)null!=n&&("FastjsDom"===n.construct?t.push(n):Array.isArray(n)?t.push(...n):t.push(d(n)));const n=function(e){return{construct:"FastjsDomList",get length(){return e.length},set length(t){e.length=t}}}(t),r=new Proxy(n,{get(e,t){if(t in e)return e[t];if(t in e._list)return e._list[t];if(t in e._list[0]){const n=e._list[0][t];return"function"==typeof n?function(){for(const n of e._list){const e=n[t];if("function"==typeof e){const t=e.bind(n,...arguments)();if(!a(t)&&"FastjsDom"!==t.construct)return t}}return e}:n}return e[t]},set:(e,t,r)=>(e[t]=r,Number.isInteger(Number(t))&&(n._list[t]=r,e[t]=r),!0)});return r._list=new Proxy(t,{set:(e,t,r)=>(e[Number(t)]=r,n[Number(t)]=r,!0)}),t.forEach(((e,t)=>{r[t]=e})),Object.assign(r,function(e){return{add:t=>(e.push(t),e),delete:(t,n=!0)=>(n&&e[t].remove(),e.splice(t,1),e),each:t=>(e.forEach(((e,n)=>t(e,e.el(),n))),e),el:(t=0)=>e[t].el(),getElement(e=0){return this.el(e)},getDom:(t=0)=>e[t],next(e="*"){const t=i(e,this.toElArray());return Array.isArray(t)?u(t):null===t?null:d(t)},toArray:()=>e,toElArray:()=>e.map((e=>e.el()))}}(r))}function f(e){return{...e(),setCustomProp(e,t){return this[String(e)]=t,this},setCustomProps(e){for(const t in e)this[t]=e[t];return this},getCustomProp(e){return this[String(e)]},setCustomEvent(e,t,n=!1){return this[e]=t,n&&t(this,this),this},callCustomEvent(e,...t){return this[e](this,...t),this},then(e,t=0){const n=()=>e(this);return 0===t?n():setTimeout(n,t),this}}}function d(e=document.body,t){"string"==typeof e?e=document.createElement(e):"construct"in e&&"FastjsDom"===e.construct&&(e=e._el);const n=f((()=>({construct:"FastjsDom",_events:[],_el:e}))),r=Object.assign(n,function(e){function t(t,n){return(r(e._el?.constructor.prototype,t)?.writable||r(e._el?.constructor.prototype,t)?.set)&&(e._el[t]=n),e;function r(e,t){for(;null!==e;){const n=Object.getOwnPropertyDescriptor(e,t);if(n)return n;e=Object.getPrototypeOf(e)}return null}}const n=(t,n)=>{t.forEach((t=>{t.split(" ").forEach((t=>{e.setClass(t,n)}))}))};return{get:function(t){return e._el[t]},set:t,text:function(t){return void 0===t?e._el.textContent||"":(e._el.textContent=t,e)},html:function(t){return void 0===t?e._el.innerHTML:(e._el.innerHTML=t,e)},val:function(n){const r="TEXTAREA"===e._el.tagName?"textContent":"value";return void 0===n?e._el[r]:(t(r,n),e)},el:()=>e._el,remove:()=>(e._el.remove(),e),focus:()=>(e._el.focus(),e),first:()=>e._el.firstElementChild?d(e._el.firstElementChild):null,last:()=>e._el.lastElementChild?d(e._el.lastElementChild):null,father:()=>{const t=e._el.parentElement;return t?d(t):null},children:()=>u([...e._el.children]),next:(t="*")=>{const n=i(t,e._el);return Array.isArray(n)?u(n):null===n?null:d(n)},each:(t,n=!1)=>([...e._el.children].forEach(((e,r)=>{t(d(e),e,r),n&&d(e).each(t,n)})),e),addEvent:function(t,n){let r=t=>n(e,t);return e._events.push({type:t,callback:n,trigger:r,remove:()=>{e.removeEvent(n)}}),e._el.addEventListener(t,r),e},removeEvent:function(t,n){const r={type:"string"==typeof t?t:void 0,callback:"function"==typeof t?t:void 0,key:n};return r.callback?e._events.forEach(((t,n)=>{t.callback===r.callback&&(e._el.removeEventListener(t.type,t.trigger),e._events.splice(n,1))})):r.type&&(void 0!==r.key?(e._el.removeEventListener(e._events[r.key].type,e._events[r.key].trigger),e._events.splice(r.key,1)):e._events.forEach((t=>{t.type===r.type&&(e._el.removeEventListener(t.type,t.trigger),e._events.splice(e._events.indexOf(t),1))}))),e},getStyle:function(t){const n=()=>new Proxy(o,{get:(e,t)=>e.getPropertyValue(t)||e[t]||null,set:(t,n,r)=>(e.setStyle(n,r),Reflect.set(t,n,r))}),r=window.getComputedStyle(e._el),o=Object.assign(r,e._el.style);return"string"==typeof t?o.getPropertyValue(t.replace(/[A-Z]/g,(e=>"-"+e.toLowerCase()))):"function"!=typeof t?n():(t(n(),e),e)},setStyle:function(t,n,r){if(n)e._el.style.setProperty(t.replace(/[A-Z]/g,(e=>"-"+e.toLowerCase())),n,r?"important":"");else if("string"==typeof t)e._el.style.cssText=t;else{let n;for(n in t)e.setStyle(n,t[n])}return e},getClass:function(t){const n=[...e._el.classList];if(!t)return n;t(n)},setClass:function(t,n=!0){if("string"==typeof t)e._el.classList[n?"add":"remove"](t);else for(const n in t)e.setClass(n,t[n]);return e},addClass:function(t){return"string"==typeof t?n([...arguments],!0):t.forEach((t=>e.addClass(t))),e},removeClass:function(t){return"string"==typeof t?n([...arguments],!1):t.forEach((t=>e.removeClass(t))),e},clearClass:()=>(e._el.className="",e),getAttr:function(t){const n=()=>{const t=[...e._el.attributes],n={};return t.forEach((e=>{n[e.name]=e.value})),new Proxy(n,{set:(t,n,r)=>(e.setAttr(n,r),Reflect.set(t,n,r))})};switch(typeof t){case"string":return e._el.getAttribute(t);case"function":return t(n(),e),e;default:return n()}},setAttr:function(t,n){const r=(t,n)=>{null===n?e._el.removeAttribute(t):e._el.setAttribute(t,n)};if("string"==typeof t)r(t,n);else for(const e in t)r(e,t[e]);return e},push:function(t=document.body,n="lastElementChild",r){t=t.tagName?t:t.el();const s="replaceElement"===n,l=d(r?e._el.cloneNode(!0):e._el);if(s){const t=d(e._el.parentElement);if(null===t)throw new Error("father is null");t._el.replaceChild(l._el,e._el)}else if("number"==typeof n)e._el.insertBefore(l._el,e._el.children[n]);else{({firstElementChild:()=>t.prepend(l._el),lastElementChild:()=>t.append(l._el),randomElementChild:function(){const n=[...t.children];0===n.length||o(0,n.length)===n.length?t.appendChild(e._el):t.insertBefore(e._el,n[o(0,n.length-1)])},beforeElement:()=>t.before(l._el),afterElement:()=>t.after(l._el)})[n]()}return{isReplace:s,newElement:s&&l,oldElement:s&&e,index:[...t.children].indexOf(l._el),el:l,origin:e,father:l.father()}},insert:function(t,n="last",r){t=t.tagName?t:t.el();const s=d(r?t.cloneNode(!0):t);if("number"==typeof n)t.insertBefore(s._el,e._el.children[n]);else{({first:()=>e._el.prepend(s._el),last:()=>e._el.append(s._el),random:function(){const t=[...e._el.children];0===t.length?e._el.appendChild(s._el):e._el.insertBefore(s._el,t[o(0,t.length-1)])},before:()=>e._el.before(s._el),after:()=>e._el.after(s._el)})[n]()}return{index:Array.from(t.children).indexOf(s._el),added:s,origin:e}}}}(n));return t&&function(e,t){let n;for(n in t)"html"===n?e.html(t.html):"text"===n?e.text(t.text):"css"===n?e.setStyle(t.css):"class"===n?e.addClass(t.class):"attr"===n?e.setAttr(t.attr):"val"===n?e.val(t.val):n in e._el&&e.set(n,t[n])}(r,t),r}var h=Object.freeze({__proto__:null,createFastjsDom:d});function m(e="body",t=document){const n=i(e,t);return Array.isArray(n)?u(n):null===n?null:d(n)}const p=function(e="body",t=document){return m(e,t)};p.select=m,p.newEl=d,p.newElList=u;var g=p;function y(e=new Date){return[["Y",e.getFullYear()],["M",e.getMonth()+1],["D",e.getDate()],["H",e.getHours()%12],["hh",e.getHours()],["h",e.getHours()],["mm",e.getMinutes()],["m",e.getMinutes()],["ss",e.getSeconds()],["s",e.getSeconds()],["S",e.getMilliseconds()],["A",e.getHours()>=12?"PM":"AM"],["a",e.getHours()>=12?"pm":"am"]].map((e=>{return 1===e[0].length&&"number"==typeof e[1]?[e[0],(t=e[1],t<10?"0"+t:t.toString())]:e;var t}))}function _(e,t){let n=!1,r=new Date;r.setMilliseconds(0);let o="",s=null,l=!1,c=-1;const i=y().map((e=>e[0]));for(let a=0;a<e.length;a++){c++;const u=e[a];if("<"!==u&&">"!==u){if(!n)if(i.includes(u)){if(l)throw"fg3j";switch(u){case"Y":r.setFullYear(Number(t.slice(c,c+4))),c+=3;break;case"M":r.setMonth(Number(t.slice(c,c+2))-1),c+=1;break;case"D":r.setDate(Number(t.slice(c,c+2))),c+=1;break;case"H":o=t.slice(c,c+2),c+=1;break;case"A":s="AM"===t.slice(c,c+2),c+=1;break;case"a":s="am"===t.slice(c,c+2),c+=1;break;case"h":r.setHours(Number(t.slice(c,c+2))),c+=1;break;case"m":r.setMinutes(Number(t.slice(c,c+2))),c+=1;break;case"s":r.setSeconds(Number(t.slice(c,c+2))),c+=1;break;case"S":r.setMilliseconds(Number(t.slice(c,c+3))),c+=2}l=!0}else l=!1}else n="<"===u,l=!1,c--}if(o){if(null===s)throw"2b5s";s?r.setHours(Number(o)):r.setHours(Number(o)+12)}return r.getTime()}function b(e="Y-M-D h:m:s",t=Date.now(),n=!1){"string"==typeof t?t=_(e,t):t instanceof Date&&(t=t.getTime());const r=f((()=>({construct:"FastjsDate",format:e,_date:t,_createAt:Date.now(),timezoneDiff:60*(new Date).getTimezoneOffset()*1e3})));n&&(r._date+=r.timezoneDiff);const o=Object.assign(r,function(e){const t=(t=!0)=>t?e._date:e._date-e.timezoneDiff,n=(n=!0)=>t(n)+Date.now()-e._createAt;return{changeDate:function(t){return"string"==typeof t&&(t=_(e.format,t)),e._date=t,e._createAt=Date.now(),e},changeFormat:t=>(e.format=t,e),setZone:t=>(e.timezoneDiff=3600*t*1e3,e),refresh:()=>(e._createAt=Date.now(),e),toNumber:t,toActiveNumber:n,toString:function(t,n){const r={format:n};t?"number"==typeof t||["utc","local"].includes(t)?r.show=t:r.format=t:r.show="utc";const[o,s]=function(e){const t=[];let n="",r="",o=0;for(const s of e){if("<"===s){if(1==++o)continue}else if(">"===s&&(o--,0===o)){t.push(r),n+=`{{*${t.length-1}}}`,r="";continue}o>0?r+=s:n+=s}return o>0&&(n+=`<${r}`),[n,t]}(r.format||e.format);let l=e._date;"number"==typeof r.show?l-=3600*r.show*1e3:"local"===r.show&&(l-=e.timezoneDiff);let c=o;for(const e of y(new Date(l))){const t=e[0],n=e[1];c=c.replace(new RegExp(t,"g"),String(n))}return s.forEach(((e,t)=>{c=c.replace(`{{*${t}}}`,`${e}`)})),c},toActiveString:function(t,r){return"string"!=typeof t||["utc","local"].includes(t)||(r=t),b(r||e.format,n()).toString()}}}(r));return o}const w=(e,t="Y-M-D h:m:s")=>{const n=b(t,e),r=n.toString(),o=n.toNumber(),s=o+60*(new Date).getTimezoneOffset()*1e3;return{format:t,date:new Date(o),string:r,dateString:r,timestamp:o,utcDate:new Date(s),utcTimestamp:s,utcDateString:b(t,s).toString()}};var v={parse:w,parseTime:(e,t)=>w(e,t),parseDate:(e,t)=>w(e,t),string:(e,t=Date.now())=>w(t,e).string,reformat:(e,t,n="Y-M-D h:m:s")=>b(e,t).toString(n),now:e=>w(Date.now(),e),create:b};const E={timeout:5e3,hooks:{runAll:!1},handler:{handleResponse:async(e,t)=>e.headers.get("Content-Type")?.includes("application/json")?await e.json():await e.text(),responseCode:e=>e>=200&&e<300},check:{ignoreFormatWarning:!1,stringBodyWarning:!0,unrecommendedMethodWarning:!0}};function k(e={}){return{timeout:e.timeout||E.timeout,headers:e.headers||{},wait:e.wait||0,failed:e.failed||(()=>0),callback:e.callback||(()=>0),query:e.query||null,body:e.body||null,hooks:function(){const t={before:[],init:[],success:[],failed:[]};let n;for(n in t){const r=e=>{e&&t[n].push(...Array.isArray(e)?e:[e])};e.hooks?.[n]&&r(e.hooks[n]),E.hooks[n]&&r(E.hooks[n])}return Object.assign(t,{runAll:e.hooks?.runAll||E.hooks.runAll})}()}}function A(e,t){if(!t||0===Object.keys(t).length)return e;const n=function(e){if("string"!=typeof e)return new URLSearchParams(e);"?"===e[0]&&(e=e.slice(1));const t=new URLSearchParams;return e.split("&").forEach((e=>{const[n,r]=e.split("=");t.set(n,r)})),t}(t);return n.size>0&&(e=e+(e.includes("?")?"&":"?")+n.toString()),e}function D(e){try{return JSON.parse(e)}catch(t){return e}}function C(e,t,n=e.url){const r={body:o(t)?e.data:null,query:(o(t)?null:e.data)||e.config.query};return e.config.wait?(e.wait&&clearTimeout(e.wait),e.wait=setTimeout((()=>{s(),e.wait=null}),e.config.wait)):s(),e;function o(e){return!["GET","HEAD","OPTIONS"].includes(e)}async function s(){const o=e.config.hooks;if(!x(o.before,[e]))return j("before",e,null);let s=[];[n,s]=function(e,t){const n=e.split("/"),r=/^:/,o=[];return[n.map((e=>{const n=e.replace(":","");if(r.test(e)&&t[n]){o.push(n);const e=t[n];return delete t[n],e}return e})).join("/"),o]}(n,e.data);for(const t of s)delete e.data[t];if(e.request=new Request(A(n,r.query),{method:t,headers:e.config.headers,body:r.body?JSON.stringify(r.body):void 0}),!x(o.init,[e]))return j("init",e,null);fetch(e.request).then((async n=>{const r=await E.handler.handleResponse(n,e),s={headers:[...n.headers.entries()],headersObj:Object.fromEntries(n.headers.entries()),response:n,data:D(r),status:n.status,request:e,resend:()=>C(e,t)};return E.handler.responseCode(n.status,e)?x(o.success,[s,e])?(S(e.callback.success,[r,s],t),void S(e.callback.finally,[e],t)):j("success",e,s):function(e,t,n){let r=e?.status;if(e.data,!x(t.config.hooks.failed,[r,t]))return j("failed",t,null);const o={error:r,request:t,intercept:!1,hook:null,response:e};t.config.failed(o),S(t.callback.failed,[o],null),S(t.callback.finally,[t],null)}(s,e)})).catch((n=>{if(!x(o.failed,[n,e]))return j("failed",e,null);const r={error:n,request:e,intercept:!1,hook:null,response:null};e.config.failed(r),S(e.callback.failed,[r],t),S(e.callback.finally,[e],t)}))}}function S(e,t,n){for(let r=0;r<e.length;r++){const o=e[r];o.method&&o.method!==n||(o.func(...t),o.once&&(e.splice(r,1),r--))}}function j(e,t,n){const r={error:new Error(`Request interrupted by ${e}`),request:t,intercept:!0,hook:e,response:n};t.config.failed(r),S(t.callback.failed,[r],null),S(t.callback.finally,[t],null)}function x(e,t){if(!e)return!0;if("function"==typeof e)return e(t[0],t[1]);let n=!0;for(const r of e)if(!r(t[0],t[1])&&(n=!1,!E.hooks.runAll))break;return n}function O(e,t=null,n){const r=f((()=>({construct:"FastjsRequest",url:e,data:t||{},config:k(n),callback:{success:[],failed:[],finally:[]}}))),o=Object.assign(r,function(e){const t=(t,n={},r)=>(e.data=Object.assign(e.data,n),C(e,t,r));return{send:t,get:(e,n)=>t("GET",e,n),post:(e,n)=>t("POST",e,n),put:(e,n)=>t("PUT",e,n),delete:(e,n)=>t("DELETE",e,n),patch:(e,n)=>t("PATCH",e,n),head:(e,n)=>t("HEAD",e,n),options:(e,n)=>t("OPTIONS",e,n),then:(t,n=!1,r)=>(e.callback.success.push({func:t,once:!n,method:r}),e),catch:(t,n=!1,r)=>(e.callback.failed.push({func:t,once:!n,method:r}),e),finally:(t,n=!1,r)=>(e.callback.finally.push({func:t,once:!n,method:r}),e)}}(r));return o}var T={get:(e,t,n)=>O(e,t,n).get(),post:(e,t,n)=>O(e,t,n).post(),put:(e,t,n)=>O(e,t,n).put(),delete:(e,t,n)=>O(e,t,n).delete(),patch:(e,t,n)=>O(e,t,n).patch(),head:(e,t,n)=>O(e,t,n).head(),create:(e,t,n)=>O(e,t,n),request:k,config:E};function N(){return"undefined"!=typeof document}function P(e,t){const n=f((()=>({construct:"FastjsCookie",path:e,domain:t})));var r;return Object.assign(n,(r=n,{get:function(e){if(!N())return null;const t=document.cookie.match(new RegExp(`(^| )${e}=([^;]+)`));return t?decodeURIComponent(t[2]):null},set:function(e,t,n={}){if(!N())return r;let o=`${e}=${encodeURIComponent(t)}`;if(n.expires){let e=new Date;"number"==typeof n.expires?e.setTime(e.getTime()+n.expires):e=n.expires,o+=`; expires=${e.toUTCString()}`}return n.path&&(o+=`; path=${n.path}`),n.domain&&(o+=`; domain=${n.domain}`),n.secure&&(o+="; secure"),document.cookie=o,r},remove:function(e){return N()?(document.cookie=`${e}=; expires=Thu, 01 Jan 1970 00:00:00 GMT`,r):r}}))}const M=e=>P().get(e);var q={get:M,exists:e=>null!==M(e),set:(e,t,n={})=>P().set(e,t,n),remove:e=>P().remove(e),create:P};export{e as callUntilEnd,t as catchError,q as cookie,r as copy,v as date,g as dom,o as rand,s as randString,T as request,n as secureCall,c as utils,l as uuid};