UNPKG

@alessiofrittoli/web-utils

Version:
3 lines (2 loc) 13.5 kB
'use strict';var urlUtils=require('@alessiofrittoli/url-utils'),dateUtils=require('@alessiofrittoli/date-utils'),mathUtils=require('@alessiofrittoli/math-utils');var w=e=>typeof window<"u"?window.matchMedia(e).matches:false;var m=e=>new Map(e);var b=(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:p=window.screen.height/2-(r/2+50),...g}=i,x=m([["popup","yes"],["width",t.toString()],["height",r.toString()],["left",o.toString()],["top",p.toString()]]);Object.entries(g).map(([u,L])=>{x.set(u,L);});let y=Array.from(x).map(u=>u.join("=")).join(",");return window.open(n&&urlUtils.Url.format(n),s,y)};var se=()=>process.env.NODE_ENV==="development",ie=()=>process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID!==void 0,k=e=>e instanceof Promise,ae=e=>e instanceof Function&&e.constructor.name==="AsyncFunction",P=e=>typeof e=="string"||e instanceof String,D=e=>!!e&&e.constructor===Array,pe=e=>D(e)&&e.length<=0,ce=e=>!!e&&e.constructor===Object,le=e=>Object.keys(e).length===0,ue=e=>{try{JSON.parse(e);}catch{return false}return true},me=e=>e instanceof NodeList,fe=e=>e instanceof Element,de=e=>window.TouchEvent&&e instanceof TouchEvent,ge=()=>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 I=e=>e.trim().length>0,S=e=>!I(e),ye=e=>/^[a-zA-Z0-9]+([._-][a-zA-Z0-9]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z]{2,})+$/.test(e),Te=e=>/^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]{8,14}$/g.test(e),be=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()),we=(e,t=0)=>typeof t=="string"?t.trim().length<e:t<e,ke=(e,t=0)=>typeof t=="string"?t.trim().length>e:t>e,Pe=(e,t,r=0)=>typeof r=="string"?r.trim().length>=e&&r.trim().length<=t:+r>=+e&&+r<=+t,Se=(e,t)=>e===t,Oe=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 h=e=>e.replace(/[-\\^$*+?.()|[\]{}]/g,"\\$&");var E=e=>e.charAt(0).toUpperCase()+e.slice(1),K=e=>e.charAt(0).toLowerCase()+e.slice(1),U=e=>G(e).replace(/[-_\s](.)/g,(t,r)=>r.toUpperCase()),G=e=>e.replace(/\s+/g,"-").replace(/_/g,"-").replace(/([A-Z])/g,"-$1").replace(/[^a-zA-Z0-9-]/g,"-").replace(/--+/g,"-").toLowerCase(),f=e=>k(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()||"",d=e=>{if(e&&!(P(e)&&S(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}}},je=(e,t,r=t)=>{if(typeof e!="string")throw new TypeError("Input must be a string.");let n=r instanceof RegExp?r:new RegExp(`^[${h(r)}]?`);return e.replace(n,t)},Le=(e,t)=>{if(typeof e!="string")throw new TypeError("Input must be a string.");let r=t instanceof RegExp?t:new RegExp(`^[${h(t)}]+`);return e.replace(r,"")},Fe=(e,t,r=t)=>{if(typeof e!="string")throw new TypeError("Input must be a string.");let n=r instanceof RegExp?r:new RegExp(`[${h(r)}]?$`);return e.replace(n,t)},De=(e,t)=>{if(typeof e!="string")throw new TypeError("Input must be a string.");let r=t instanceof RegExp?t:new RegExp(`[${h(t)}]?$`);return e.replace(r,"")},T=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(","):T([e]),A=(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 p=T(s);p&&o.append("cc",p);}if(i){let p=T(i);p&&o.append("bcc",p);}return ["mailto:",t&&T(t),o.size>0&&`?${o.toString().replace(/\+/g," ")}`].filter(Boolean).join("")};var $=()=>typeof navigator<"u"&&typeof navigator.canShare=="function"&&typeof navigator.share=="function",N=e=>$()&&navigator.canShare(e),We=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 N(i)?navigator.share(i):false},Ze=(e={})=>{window.location.href=A(e);},c=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),b({url:o,...s,context:"sharer"})},He=(e={})=>{let{title:t=document.title,...r}=e,n=new URL("https://facebook.com/sharer/sharer.php");return t&&n.searchParams.append("t",t),c({...r,sharer:n,urlParam:"u"})},qe=(e={})=>{let{title:t=document.title,...r}=e,n=new URL("https://work.workplace.com/sharer.php");return t&&n.searchParams.append("t",t),c({...r,sharer:n})},Je=(e={})=>{let{title:t=document.title,...r}=e,n=new URL("https://reddit.com/submit");return t&&n.searchParams.append("title",t),c({...r,sharer:n})},Qe=(e={})=>c({...e,sharer:"https://service.weibo.com/share/share.php"}),Xe=(e={})=>c({...e,sharer:"https://vk.com/share.php"}),Ye=(e={})=>c({...e,sharer:"https://tumblr.com/widgets/share/tool",urlParam:"canonicalUrl"}),_e=(e={})=>c({...e,sharer:"https://social-plugins.line.me/lineit/share"}),et=(e={})=>c({...e,sharer:"https://x.com/intent/tweet"}),tt=(e={})=>c({...e,sharer:"https://linkedin.com/sharing/share-offsite"}),rt=(e={})=>c({...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),c({...s,url:t,sharer:o})},ot=(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(),b({url:i,...n,context:"sharer"})};var z="(orientation:portrait)",pt=()=>w(z);var W=(n=>(n.Low="Low",n.Medium="Medium",n.High="High",n))(W||{}),Z=(n=>(n.Strict="Strict",n.Lax="Lax",n.None="None",n))(Z||{}),C=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=m();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,p])=>(o=o!==s?E(o.toString()):o,o==="Expires"&&dateUtils.isValidDate(p)&&(p=p.toUTCString()),o==="MaxAge"&&(o="Max-Age"),[o,f(p)].join("="))).filter(Boolean).join(";")}static fromString(t){let[r,...n]=t.split(";");if(!r)return null;let[s,i]=r.split("="),o=n.map(p=>{let[g,x]=p.split("=");if(!g||!g.trim().length)return null;let y=K(U(g)),u=e.parseValue(x,y);return u==null?null:[y,u]}).filter(Boolean);return m([["name",s],["value",e.parseValue(i)],...o])}static fromListString(t){let r=m();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":d(t)}};var V=class e{static get(t){return d(localStorage.getItem(t)||void 0)}static set(t,r){let n=f(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 v=class e{static get(t){return d(sessionStorage.getItem(t)||void 0)}static set(t,r){let n=f(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 kt=e=>e.length<=0?e:[...new Set(e)],Pt=(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())},St=e=>e.replace(/\s/g,"").split(",").filter(Boolean);function Ot(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,p)=>e.slice(p*s,p*s+s)).filter(o=>o.length>0)}var H=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},Et=e=>H([...e]);var At=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 Vt=(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`);},vt=(e=document.documentElement)=>{e.style.removeProperty("overflow"),e.style.removeProperty("padding-right"),e.style.removeProperty("--scrollbar-size");};var Lt=e=>!!e&&(M(e)||j(e)),M=e=>!!e&&(typeof e=="function"||typeof e=="object")&&e.constructor.name==="GeneratorFunction",j=e=>!!e&&(typeof e=="function"||typeof e=="object")&&e.constructor.name==="AsyncGeneratorFunction",Ft=e=>!!e&&(q(e)||J(e)),q=e=>!!e&&typeof e=="object"&&M(e.constructor),J=e=>!!e&&typeof e=="object"&&j(e.constructor);var Bt=e=>{let t={...e};for(let r in t)t[r]==null&&delete t[r];return t},Gt=e=>Object.fromEntries(e.entries()),$t=e=>Object.assign(Object.create(Object.getPrototypeOf(e)),e),Nt=(e,t)=>Object.keys(e).find(r=>e[r]===t);var Zt=e=>new Promise(t=>setTimeout(t,e)),Q=(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);}),Ht=e=>((...t)=>Q(e,...t));exports.Cookie=C;exports.LocalStorage=V;exports.Priority=W;exports.SameSite=Z;exports.SessionStorage=v;exports.addLeadingCharacter=je;exports.addTrailingCharacter=Fe;exports.arrayObjectUnique=Pt;exports.arrayUnique=kt;exports.blockScroll=Vt;exports.canWebApiShare=$;exports.canWebApiShareData=N;exports.chunkInto=Ot;exports.cloneObject=$t;exports.deferCallback=Ht;exports.deferTask=Q;exports.downloadBlob=At;exports.emailDataToString=A;exports.escapeRegExpCharSet=h;exports.filterObject=Bt;exports.getMediaMatches=w;exports.getObjectKey=Nt;exports.getTypedMap=m;exports.isArray=D;exports.isAsyncFunction=ae;exports.isAsyncGeneratorFunction=j;exports.isAsyncGeneratorObject=J;exports.isDefaultGeneratorFunction=M;exports.isDefaultGeneratorObject=q;exports.isDev=se;exports.isEmpty=S;exports.isEmptyArray=pe;exports.isEmptyObject=le;exports.isGeneratorFunction=Lt;exports.isGeneratorObject=Ft;exports.isGreaterThan=ke;exports.isInRange=Pe;exports.isJson=ue;exports.isLessThan=we;exports.isNodeElement=fe;exports.isNodeList=me;exports.isNotEmpty=I;exports.isObject=ce;exports.isPortrait=pt;exports.isPromise=k;exports.isSQLStatement=Oe;exports.isStrictEqual=Se;exports.isString=P;exports.isTest=ie;exports.isTouchDevice=ge;exports.isTouchEvent=de;exports.isValidEmail=ye;exports.isValidPhoneNumber=Te;exports.isValidVat=be;exports.lcFirst=K;exports.listToArray=St;exports.mapToObject=Gt;exports.openBrowserPopUp=b;exports.openSharerPopUp=c;exports.parseValue=d;exports.portraitMediaQuery=z;exports.recipientsToString=T;exports.removeLeadingCharacter=Le;exports.removeTrailingCharacter=De;exports.restoreScroll=vt;exports.share=We;exports.shareOnFacebook=He;exports.shareOnLine=_e;exports.shareOnLinkedIn=tt;exports.shareOnPinterest=nt;exports.shareOnReddit=Je;exports.shareOnTelegram=rt;exports.shareOnTumblr=Ye;exports.shareOnVK=Xe;exports.shareOnWeibo=Qe;exports.shareOnWhatsApp=ot;exports.shareOnWorkplace=qe;exports.shareOnX=et;exports.shareViaEmail=Ze;exports.shuffle=H;exports.shuffleCopy=Et;exports.sleep=Zt;exports.stringifyValue=f;exports.toCamelCase=U;exports.toKebabCase=G;exports.ucFirst=E;