@alessiofrittoli/web-utils
Version:
Common TypeScript web utilities
3 lines (2 loc) • 16.9 kB
JavaScript
;var exception=require('@alessiofrittoli/exception'),fetch=require('@alessiofrittoli/fetcher/fetch'),urlUtils=require('@alessiofrittoli/url-utils'),mathUtils=require('@alessiofrittoli/math-utils'),code=require('@alessiofrittoli/exception/code'),dateUtils=require('@alessiofrittoli/date-utils');var ue=()=>{let{onLine:e}=navigator;return "connection"in navigator?{onLine:e,network:navigator.connection}:{onLine:e}};var E=e=>typeof window<"u"?window.matchMedia(e).matches:false;var ye=(e=document.documentElement)=>{let{width:t}=e.getBoundingClientRect();e.style.overflow="hidden";let r=Math.max(0,e.clientWidth-t);e.style.paddingRight=`${r}px`,e.style.setProperty("--scrollbar-size",`${r}px`);},Te=(e=document.documentElement)=>{e.style.removeProperty("overflow"),e.style.removeProperty("padding-right"),e.style.removeProperty("--scrollbar-size");},C=e=>[...e].map(({cssRules:t})=>{try{if(t.length<=0)return;let r=document.createElement("style");return Array.from(t).forEach(n=>{r.appendChild(document.createTextNode(n.cssText));}),r}catch(r){console.error("Error while cloning styles.",r);}}).filter(Boolean),w=async e=>{if(!Array.isArray(e))return w([e]);let t=[],r=[],n=[],s=[],i=[];return e.forEach(o=>{if(o instanceof StyleSheetList){r.push(o);return}if(o instanceof CSSStyleSheet){n.push(o);return}if(o instanceof HTMLStyleElement){s.push(o);return}i.push(o);}),r.length>0&&t.push(...r.flatMap(o=>C(o))),n.length>0&&t.push(...C(n)),s.length>0&&t.push(...s.map(o=>{let a=document.createElement("style");return a.appendChild(document.createTextNode(o.textContent||o.innerText||o.innerHTML)),a})),await Promise.allSettled(i.map(async o=>{let a=typeof o=="string",p=!a&&"url"in o&&urlUtils.Url.format(o.url)||urlUtils.Url.format(o);if(!((!a&&"fetch"in o&&o.fetch)??false)){let b=document.createElement("link");return b.rel="stylesheet",b.href=p,t.push(b),b}let{data:d,error:m}=await fetch.fetch(p);if(m)throw console.error("Error while fetching the given style URL.",m),m;let y=document.createElement("style");return y.appendChild(document.createTextNode(d)),t.push(y),y})),t};var S=e=>{if(typeof e>"u")return [void 0,void 0];if(typeof e=="string"){let[,i]=mathUtils.getNumbersFromString(e),[o,a]=i||[void 0,void 0];return S([o,a])}if(!Array.isArray(e))return S([e,e]);let[t,r]=e,n=isNaN(t??0)?0:t,s=isNaN(r??0)?0:r;return [n??s,s??n]};var Z={DOCUMENT_PIP_NOT_SUPPORTED:"ERR:DOCUMENTPIPNOTSUPPORTED"},A={...code.ErrorCode,...Z};var J=()=>"documentPictureInPicture"in window&&typeof window.documentPictureInPicture.requestWindow=="function",_=()=>{if(!J())throw new exception.Exception("The Document Picture-in-Picture API is not supported in the current browser.",{code:A.DOCUMENT_PIP_NOT_SUPPORTED})},Ve=async(e={})=>{_();let{sizes:t,styles:r,onQuit:n,...s}=e,[i=250,o=i]=S(t),a=await w(document.styleSheets).then(async u=>r?u.concat(await w(r)):u),p=await window.documentPictureInPicture.requestWindow({width:i,height:o,...s});return a.map(u=>p.document.head.appendChild(u)),n&&p.addEventListener("pagehide",n,{once:true}),{window:p}};var h=e=>new Map(e);var O=(e={})=>{let t=Math.max(100,e.width||600),r=Math.max(100,e.height||800),{url:n,context:s}=e,{features:i={}}=e,{left:o=window.screen.width/2-(t/2+10),top:a=window.screen.height/2-(r/2+50),...p}=i,u=h([["popup","yes"],["width",t.toString()],["height",r.toString()],["left",o.toString()],["top",a.toString()]]);Object.entries(p).map(([m,y])=>{u.set(m,y);});let d=Array.from(u).map(m=>m.join("=")).join(",");return window.open(n&&urlUtils.Url.format(n),s,d)};var ze=()=>process.env.NODE_ENV==="development",Be=()=>process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID!==void 0,R=e=>e instanceof Promise,We=e=>e instanceof Function&&e.constructor.name==="AsyncFunction",K=e=>typeof e=="string"||e instanceof String,X=e=>!!e&&e.constructor===Array,Ge=e=>X(e)&&e.length<=0,$e=e=>!!e&&e.constructor===Object,He=e=>Object.keys(e).length===0,Ze=e=>{try{JSON.parse(e);}catch{return false}return true},qe=e=>e instanceof NodeList,Je=e=>e instanceof Element,_e=e=>window.TouchEvent&&e instanceof TouchEvent,Qe=()=>typeof window<"u"&&"ontouchstart"in window&&typeof window.ontouchstart=="function"||typeof navigator<"u"&&navigator.maxTouchPoints>0||typeof navigator<"u"&&"msMaxTouchPoints"in navigator&&navigator.msMaxTouchPoints>0;var Y=e=>e.trim().length>0,V=e=>!Y(e),et=e=>/^[a-zA-Z0-9]+([._-][a-zA-Z0-9]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z]{2,})+$/.test(e),tt=e=>/^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]{8,14}$/g.test(e),rt=e=>/^(ATU[0-9]{8}|BE[01][0-9]{9}|BG[0-9]{9,10}|HR[0-9]{11}|CY[A-Z0-9]{9}|CZ[0-9]{8,10}|DK[0-9]{8}|EE[0-9]{9}|FI[0-9]{8}|FR[0-9A-Z]{2}[0-9]{9}|DE[0-9]{9}|EL[0-9]{9}|HU[0-9]{8}|IE([0-9]{7}[A-Z]{1,2}|[0-9][A-Z][0-9]{5}[A-Z])|IT[0-9]{11}|LV[0-9]{11}|LT([0-9]{9}|[0-9]{12})|LU[0-9]{8}|MT[0-9]{8}|NL[0-9]{9}B[0-9]{2}|PL[0-9]{10}|PT[0-9]{9}|RO[0-9]{2,10}|SK[0-9]{10}|SI[0-9]{8}|ES[A-Z]([0-9]{8}|[0-9]{7}[A-Z])|SE[0-9]{12}|GB([0-9]{9}|[0-9]{12}|GD[0-4][0-9]{2}|HA[5-9][0-9]{2}))$/g.test(e.trim()),nt=(e,t=0)=>typeof t=="string"?t.trim().length<e:t<e,ot=(e,t=0)=>typeof t=="string"?t.trim().length>e:t>e,st=(e,t,r=0)=>typeof r=="string"?r.trim().length>=e&&r.trim().length<=t:+r>=+e&&+r<=+t,it=(e,t)=>e===t,at=e=>typeof e=="string"&&[/\bselect\b\s+.*?\bfrom\b/,/\bdelete\b\s+.*?\bfrom\b/,/\binsert\b\s+.*?\binto\b/,/\bupdate\b\s+.*?\bset\b/,/\bunion\b\s+.*?\bselect\b/,/\breplace\b\s+.*?\binto\b/,/\bcreate\b\s+.*?\b(table|view|index|database)\b/,/\bdrop\b\s+.*?\b(table|view|index|database)\b/,/\balter\b\s+.*?\b(table|view|index|database)\b/,/\brename\b\s+.*?\b(table|view|index|database)\b/,/;\s*--/].some(t=>t.test(e.toLowerCase()));var T=e=>e.replace(/[-\\^$*+?.()|[\]{}]/g,"\\$&");var D=e=>e.charAt(0).toUpperCase()+e.slice(1),L=e=>e.charAt(0).toLowerCase()+e.slice(1),v=e=>te(e).replace(/[-_\s](.)/g,(t,r)=>r.toUpperCase()),te=e=>e.replace(/\s+/g,"-").replace(/_/g,"-").replace(/([A-Z])/g,"-$1").replace(/[^a-zA-Z0-9-]/g,"-").replace(/--+/g,"-").toLowerCase(),g=e=>R(e)||typeof e=="function"?"":e instanceof Date&&dateUtils.isValidDate(e)?e.toISOString():e instanceof Map||e instanceof Headers?JSON.stringify(Array.from(e.entries())):typeof e=="object"?JSON.stringify(e):e?.toString()||"",x=e=>{if(e&&!(K(e)&&V(e))){if(mathUtils.isNumeric(e))return parseFloat(e);try{let t=new Date(e);return dateUtils.isValidDate(t)?t:JSON.parse(e)}catch{return e}}},xt=(e,t,r=t)=>{if(typeof e!="string")throw new TypeError("Input must be a string.");let n=r instanceof RegExp?r:new RegExp(`^[${T(r)}]?`);return e.replace(n,t)},yt=(e,t)=>{if(typeof e!="string")throw new TypeError("Input must be a string.");let r=t instanceof RegExp?t:new RegExp(`^[${T(t)}]+`);return e.replace(r,"")},Tt=(e,t,r=t)=>{if(typeof e!="string")throw new TypeError("Input must be a string.");let n=r instanceof RegExp?r:new RegExp(`[${T(r)}]?$`);return e.replace(n,t)},bt=(e,t)=>{if(typeof e!="string")throw new TypeError("Input must be a string.");let r=t instanceof RegExp?t:new RegExp(`[${T(t)}]?$`);return e.replace(r,"")},P=e=>Array.isArray(e)?e.filter(Boolean).map(t=>{if(typeof t!="string"){if(!t.email)return null;let r=t.name?.trim(),n=t.email.trim();return r?`${r}<${n}>`:n}return t.trim()}).filter(Boolean).join(","):P([e]),M=(e={})=>{let{to:t,body:r,subject:n,cc:s,bcc:i}=e,o=new URLSearchParams;if(r&&o.append("body",r),n&&o.append("subject",n),s){let a=P(s);a&&o.append("cc",a);}if(i){let a=P(i);a&&o.append("bcc",a);}return ["mailto:",t&&P(t),o.size>0&&`?${o.toString().replace(/\+/g," ")}`].filter(Boolean).join("")},wt=(e,...t)=>{let r=[],n="";return e.forEach((s,i)=>{if(n+=s,i>=t.length)return;let o=t[i];if(!(typeof o>"u")){if(Array.isArray(o)){let a=o.map(()=>"?").join(", ");n+=a,r.push(...o);return}n+="?",r.push(o);}}),[n.replace(/\s+/g," ").trim(),r]};var re=()=>typeof navigator<"u"&&typeof navigator.canShare=="function"&&typeof navigator.share=="function",ne=e=>re()&&navigator.canShare(e),Ct=async(e={})=>{let{title:t=document.title,text:r,url:n,files:s}=e,i=Object.keys(e).length>0?{title:t,text:r,url:n?urlUtils.Url.format(n):void 0,files:s}:{title:t,url:urlUtils.Url.format(location)};return ne(i)?navigator.share(i):false},At=(e={})=>{window.location.href=M(e);},l=e=>{let{url:t=location,sharer:r,urlParam:n="url",...s}=e,i=urlUtils.Url.format(t),o=urlUtils.Url.parse(r);return o.searchParams.append(n,i),O({url:o,...s,context:"sharer"})},Rt=(e={})=>{let{title:t=document.title,...r}=e,n=new URL("https://facebook.com/sharer/sharer.php");return t&&n.searchParams.append("t",t),l({...r,sharer:n,urlParam:"u"})},Kt=(e={})=>{let{title:t=document.title,...r}=e,n=new URL("https://work.workplace.com/sharer.php");return t&&n.searchParams.append("t",t),l({...r,sharer:n})},Vt=(e={})=>{let{title:t=document.title,...r}=e,n=new URL("https://reddit.com/submit");return t&&n.searchParams.append("title",t),l({...r,sharer:n})},It=(e={})=>l({...e,sharer:"https://service.weibo.com/share/share.php"}),Dt=(e={})=>l({...e,sharer:"https://vk.com/share.php"}),Lt=(e={})=>l({...e,sharer:"https://tumblr.com/widgets/share/tool",urlParam:"canonicalUrl"}),vt=(e={})=>l({...e,sharer:"https://social-plugins.line.me/lineit/share"}),Mt=(e={})=>l({...e,sharer:"https://x.com/intent/tweet"}),jt=(e={})=>l({...e,sharer:"https://linkedin.com/sharing/share-offsite"}),Ft=(e={})=>l({...e,sharer:"https://telegram.me/share/url"}),Nt=(e={})=>{let{url:t=location,media:r,description:n=document.title||document.querySelector('[name="description"]')?.getAttribute("content"),...s}=e,i=urlUtils.Url.format(t),o=new URL("https://pinterest.it/pin-builder");return o.searchParams.append("method","button"),o.searchParams.append("media",r?urlUtils.Url.format(r):i),n&&o.searchParams.append("description",n),l({...s,url:t,sharer:o})},zt=(e={})=>{let{url:t=location,text:r,...n}=e,s=urlUtils.Url.format(t),i=new URL("https://api.whatsapp.com/send"),o=r?`${r}
${s}`:s;return i.search=new URLSearchParams({text:o}).toString(),O({url:i,...n,context:"sharer"})};var oe=(n=>(n.Low="Low",n.Medium="Medium",n.High="High",n))(oe||{}),se=(n=>(n.Strict="Strict",n.Lax="Lax",n.None="None",n))(se||{}),F=class e{static get(t){return e.fromListString(document.cookie).get(t)}static getAll(){return e.fromListString(document.cookie)}static set(t){let r=e.parse(t);return r.has("path")||r.set("path","/"),typeof document<"u"?(document.cookie=e.toString(r),r):false}static delete(t){return !!e.set({name:t,maxAge:0})}static parse(t){if(t instanceof Map)return t;let r=typeof t.expires<"u"?new Date(t.expires):void 0,n=h();return n.set("name",t.name).set("value",t.value),r&&n.set("expires",r),typeof t.maxAge<"u"&&n.set("maxAge",t.maxAge),t.path&&n.set("path",t.path),t.priority&&n.set("priority",t.priority),t.domain&&n.set("domain",t.domain),typeof t.httpOnly<"u"&&n.set("httpOnly",t.httpOnly),typeof t.secure<"u"&&n.set("secure",t.secure),t.sameSite&&n.set("sameSite",t.sameSite),typeof t.partitioned<"u"&&n.set("partitioned",t.partitioned),n}static toString(t){let r=e.parse(t),n=Array.from(r).filter(([o])=>o!=="name"&&o!=="value").filter(([,o])=>typeof o!="boolean"||!!o),s=r.get("name");return [[s,r.get("value")],...n].map(([o,a])=>(o=o!==s?D(o.toString()):o,o==="Expires"&&dateUtils.isValidDate(a)&&(a=a.toUTCString()),o==="MaxAge"&&(o="Max-Age"),[o,g(a)].join("="))).filter(Boolean).join(";")}static fromString(t){let[r,...n]=t.split(";");if(!r)return null;let[s,i]=r.split("="),o=n.map(a=>{let[p,u]=a.split("=");if(!p||!p.trim().length)return null;let d=L(v(p)),m=e.parseValue(u,d);return m==null?null:[d,m]}).filter(Boolean);return h([["name",s],["value",e.parseValue(i)],...o])}static fromListString(t){let r=h();return t.split("; ").map(n=>{let s=e.fromString(n);if(!s)return null;r.set(s.get("name"),s);}),r}static parseValue(t,r){if(r==="expires"&&t){let n=new Date(t);return dateUtils.isValidDate(n)?n:void 0}return r==="httpOnly"||r==="secure"||r==="partitioned"?t!=="false":x(t)}};var N=class e{static get(t){return x(localStorage.getItem(t)||void 0)}static set(t,r){let n=g(r);return r==null||!n?e.delete(t):localStorage.setItem(t,n)}static delete(t){return localStorage.removeItem(t)}static clear(){return localStorage.clear()}static key(t){return localStorage.key(t)}static getLength(){return localStorage.length}};var z=class e{static get(t){return x(sessionStorage.getItem(t)||void 0)}static set(t,r){let n=g(r);return r==null||!n?e.delete(t):sessionStorage.setItem(t,n)}static delete(t){return sessionStorage.removeItem(t)}static clear(){return sessionStorage.clear()}static key(t){return sessionStorage.key(t)}static getLength(){return sessionStorage.length}};var tr=e=>e.length<=0?e:[...new Set(e)],rr=(e,t)=>{if(e.length<=0)return e;let r=new Map;return e.map(n=>{r.has(n[t])||r.set(n[t],n);}),Array.from(r.values())},nr=e=>e.replace(/\s/g,"").split(",").filter(Boolean);function or(e,t){let r=t&&"size"in t&&t.size,n=t&&"count"in t&&t.count,s=n?Math.ceil(e.length/n):r||1,i=n||Math.ceil(e.length/s);return Array.from({length:i},(o,a)=>e.slice(a*s,a*s+s)).filter(o=>o.length>0)}var ie=e=>{for(let t=e.length-1;t>0;t--){let r=Math.floor(Math.random()*(t+1));[e[t],e[r]]=[e[r],e[t]];}return e},sr=e=>ie([...e]),k=(e,t)=>Math.abs((e%t+t)%t),ir=(e,t=0)=>k(t-1,e),ar=(e,t=0)=>k(t+1,e),cr=(e,t,r=-1)=>[...e.slice(0,k(r,e.length)+1),...Array.isArray(t)?t:[t],...e.slice(k(r,e.length)+1)],pr=e=>e.items.findIndex(t=>t[e.field]===e.value);var mr=async(e,t,r)=>{let s=await new Response(t,r).blob(),i=document.createElement("a");i.href=URL.createObjectURL(s),i.download=e,i.click(),URL.revokeObjectURL(i.href),i.remove();};var ae="(orientation:portrait)",gr=()=>E(ae);var Tr=e=>!!e&&(B(e)||W(e)),B=e=>!!e&&(typeof e=="function"||typeof e=="object")&&e.constructor.name==="GeneratorFunction",W=e=>!!e&&(typeof e=="function"||typeof e=="object")&&e.constructor.name==="AsyncGeneratorFunction",br=e=>!!e&&(ce(e)||pe(e)),ce=e=>!!e&&typeof e=="object"&&B(e.constructor),pe=e=>!!e&&typeof e=="object"&&W(e.constructor);var Pr=e=>{let t={...e};for(let r in t)t[r]==null&&delete t[r];return t},kr=e=>Object.fromEntries(e.entries()),Or=e=>Object.assign(Object.create(Object.getPrototypeOf(e)),e),Er=(e,t)=>Object.keys(e).find(r=>e[r]===t);var Ar=e=>new Promise(t=>setTimeout(t,e)),le=(e,...t)=>new Promise((r,n)=>{let s=()=>{setTimeout(async()=>{try{r(await e(...t));}catch(i){n(i);}},0);};if(typeof requestAnimationFrame!="function")return s();requestAnimationFrame(s);}),Rr=e=>((...t)=>le(e,...t));exports.Cookie=F;exports.ErrorCode=A;exports.LocalStorage=N;exports.Priority=oe;exports.SameSite=se;exports.SessionStorage=z;exports.WebUtils=Z;exports.addLeadingCharacter=xt;exports.addTrailingCharacter=Tt;exports.arrayObjectUnique=rr;exports.arrayUnique=tr;exports.blockScroll=ye;exports.canWebApiShare=re;exports.canWebApiShareData=ne;exports.chunkInto=or;exports.cloneObject=Or;exports.cloneStyleSheetList=C;exports.cloneStyleSheets=w;exports.deferCallback=Rr;exports.deferTask=le;exports.downloadBlob=mr;exports.emailDataToString=M;exports.escapeRegExpCharSet=T;exports.filterObject=Pr;exports.findIndexBy=pr;exports.getConnection=ue;exports.getDimensions=S;exports.getMediaMatches=E;exports.getNextIndex=ar;exports.getObjectKey=Er;exports.getPreviousIndex=ir;exports.getTypedMap=h;exports.insertAfter=cr;exports.isArray=X;exports.isAsyncFunction=We;exports.isAsyncGeneratorFunction=W;exports.isAsyncGeneratorObject=pe;exports.isDefaultGeneratorFunction=B;exports.isDefaultGeneratorObject=ce;exports.isDev=ze;exports.isDocumentPictureInPictureSupported=J;exports.isEmpty=V;exports.isEmptyArray=Ge;exports.isEmptyObject=He;exports.isGeneratorFunction=Tr;exports.isGeneratorObject=br;exports.isGreaterThan=ot;exports.isInRange=st;exports.isJson=Ze;exports.isLessThan=nt;exports.isNodeElement=Je;exports.isNodeList=qe;exports.isNotEmpty=Y;exports.isObject=$e;exports.isPortrait=gr;exports.isPromise=R;exports.isSQLStatement=at;exports.isStrictEqual=it;exports.isString=K;exports.isTest=Be;exports.isTouchDevice=Qe;exports.isTouchEvent=_e;exports.isValidEmail=et;exports.isValidPhoneNumber=tt;exports.isValidVat=rt;exports.lcFirst=L;exports.listToArray=nr;exports.mapToObject=kr;exports.normalizeIndex=k;exports.openBrowserPopUp=O;exports.openDocumentPictureInPicture=Ve;exports.openSharerPopUp=l;exports.parameterized=wt;exports.parseValue=x;exports.portraitMediaQuery=ae;exports.recipientsToString=P;exports.removeLeadingCharacter=yt;exports.removeTrailingCharacter=bt;exports.requiresDocumentPictureInPictureAPI=_;exports.restoreScroll=Te;exports.share=Ct;exports.shareOnFacebook=Rt;exports.shareOnLine=vt;exports.shareOnLinkedIn=jt;exports.shareOnPinterest=Nt;exports.shareOnReddit=Vt;exports.shareOnTelegram=Ft;exports.shareOnTumblr=Lt;exports.shareOnVK=Dt;exports.shareOnWeibo=It;exports.shareOnWhatsApp=zt;exports.shareOnWorkplace=Kt;exports.shareOnX=Mt;exports.shareViaEmail=At;exports.shuffle=ie;exports.shuffleCopy=sr;exports.sleep=Ar;exports.stringifyValue=g;exports.toCamelCase=v;exports.toKebabCase=te;exports.ucFirst=D;