UNPKG

@alessiofrittoli/web-utils

Version:
3 lines (2 loc) 16.2 kB
import {Exception}from'@alessiofrittoli/exception';import {fetch}from'@alessiofrittoli/fetcher/fetch';import {Url}from'@alessiofrittoli/url-utils';import {getNumbersFromString,isNumeric}from'@alessiofrittoli/math-utils';import {ErrorCode}from'@alessiofrittoli/exception/code';import {isValidDate}from'@alessiofrittoli/date-utils';var me=()=>{let{onLine:e}=navigator;return "connection"in navigator?{onLine:e,network:navigator.connection}:{onLine:e}};var U=e=>typeof window<"u"?window.matchMedia(e).matches:false;var Te=(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`);},be=(e=document.documentElement)=>{e.style.removeProperty("overflow"),e.style.removeProperty("padding-right"),e.style.removeProperty("--scrollbar-size");},A=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),S=async e=>{if(!Array.isArray(e))return S([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=>A(o))),n.length>0&&t.push(...A(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",l=!a&&"url"in o&&Url.format(o.url)||Url.format(o);if(!((!a&&"fetch"in o&&o.fetch)??false)){let w=document.createElement("link");return w.rel="stylesheet",w.href=l,t.push(w),w}let{data:h,error:f}=await fetch(l);if(f)throw console.error("Error while fetching the given style URL.",f),f;let T=document.createElement("style");return T.appendChild(document.createTextNode(h)),t.push(T),T})),t};var P=e=>{if(typeof e>"u")return [void 0,void 0];if(typeof e=="string"){let[,i]=getNumbersFromString(e),[o,a]=i||[void 0,void 0];return P([o,a])}if(!Array.isArray(e))return P([e,e]);let[t,r]=e,n=isNaN(t??0)?0:t,s=isNaN(r??0)?0:r;return [n??s,s??n]};var q={DOCUMENT_PIP_NOT_SUPPORTED:"ERR:DOCUMENTPIPNOTSUPPORTED"},R={...ErrorCode,...q};var _=()=>"documentPictureInPicture"in window&&typeof window.documentPictureInPicture.requestWindow=="function",Q=()=>{if(!_())throw new Exception("The Document Picture-in-Picture API is not supported in the current browser.",{code:R.DOCUMENT_PIP_NOT_SUPPORTED})},Ie=async(e={})=>{Q();let{sizes:t,styles:r,onQuit:n,...s}=e,[i=250,o=i]=P(t),a=await S(document.styleSheets).then(async m=>r?m.concat(await S(r)):m),l=await window.documentPictureInPicture.requestWindow({width:i,height:o,...s});return a.map(m=>l.document.head.appendChild(m)),n&&l.addEventListener("pagehide",n,{once:true}),{window:l}};var g=e=>new Map(e);var E=(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),...l}=i,m=g([["popup","yes"],["width",t.toString()],["height",r.toString()],["left",o.toString()],["top",a.toString()]]);Object.entries(l).map(([f,T])=>{m.set(f,T);});let h=Array.from(m).map(f=>f.join("=")).join(",");return window.open(n&&Url.format(n),s,h)};var Be=()=>process.env.NODE_ENV==="development",We=()=>process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID!==void 0,K=e=>e instanceof Promise,Ge=e=>e instanceof Function&&e.constructor.name==="AsyncFunction",V=e=>typeof e=="string"||e instanceof String,Y=e=>!!e&&e.constructor===Array,$e=e=>Y(e)&&e.length<=0,He=e=>!!e&&e.constructor===Object,Ze=e=>Object.keys(e).length===0,qe=e=>{try{JSON.parse(e);}catch{return false}return true},Je=e=>e instanceof NodeList,_e=e=>e instanceof Element,Qe=e=>window.TouchEvent&&e instanceof TouchEvent,Xe=()=>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 ee=e=>e.trim().length>0,I=e=>!ee(e),tt=e=>/^[a-zA-Z0-9]+([._-][a-zA-Z0-9]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z]{2,})+$/.test(e),rt=e=>/^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]{8,14}$/g.test(e),nt=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()),ot=(e,t=0)=>typeof t=="string"?t.trim().length<e:t<e,st=(e,t=0)=>typeof t=="string"?t.trim().length>e:t>e,it=(e,t,r=0)=>typeof r=="string"?r.trim().length>=e&&r.trim().length<=t:+r>=+e&&+r<=+t,at=(e,t)=>e===t,ct=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 b=e=>e.replace(/[-\\^$*+?.()|[\]{}]/g,"\\$&");var L=e=>e.charAt(0).toUpperCase()+e.slice(1),v=e=>e.charAt(0).toLowerCase()+e.slice(1),M=e=>re(e).replace(/[-_\s](.)/g,(t,r)=>r.toUpperCase()),re=e=>e.replace(/\s+/g,"-").replace(/_/g,"-").replace(/([A-Z])/g,"-$1").replace(/[^a-zA-Z0-9-]/g,"-").replace(/--+/g,"-").toLowerCase(),x=e=>K(e)||typeof e=="function"?"":e instanceof Date&&isValidDate(e)?e.toISOString():e instanceof Map||e instanceof Headers?JSON.stringify(Array.from(e.entries())):typeof e=="object"?JSON.stringify(e):e?.toString()||"",y=e=>{if(e&&!(V(e)&&I(e))){if(isNumeric(e))return parseFloat(e);try{let t=new Date(e);return isValidDate(t)?t:JSON.parse(e)}catch{return e}}},yt=(e,t,r=t)=>{if(typeof e!="string")throw new TypeError("Input must be a string.");let n=r instanceof RegExp?r:new RegExp(`^[${b(r)}]?`);return e.replace(n,t)},Tt=(e,t)=>{if(typeof e!="string")throw new TypeError("Input must be a string.");let r=t instanceof RegExp?t:new RegExp(`^[${b(t)}]+`);return e.replace(r,"")},bt=(e,t,r=t)=>{if(typeof e!="string")throw new TypeError("Input must be a string.");let n=r instanceof RegExp?r:new RegExp(`[${b(r)}]?$`);return e.replace(n,t)},wt=(e,t)=>{if(typeof e!="string")throw new TypeError("Input must be a string.");let r=t instanceof RegExp?t:new RegExp(`[${b(t)}]?$`);return e.replace(r,"")},k=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(","):k([e]),j=(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=k(s);a&&o.append("cc",a);}if(i){let a=k(i);a&&o.append("bcc",a);}return ["mailto:",t&&k(t),o.size>0&&`?${o.toString().replace(/\+/g," ")}`].filter(Boolean).join("")},St=(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 ne=()=>typeof navigator<"u"&&typeof navigator.canShare=="function"&&typeof navigator.share=="function",oe=e=>ne()&&navigator.canShare(e),At=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?Url.format(n):void 0,files:s}:{title:t,url:Url.format(location)};return oe(i)?navigator.share(i):false},Rt=(e={})=>{window.location.href=j(e);},u=e=>{let{url:t=location,sharer:r,urlParam:n="url",...s}=e,i=Url.format(t),o=Url.parse(r);return o.searchParams.append(n,i),E({url:o,...s,context:"sharer"})},Kt=(e={})=>{let{title:t=document.title,...r}=e,n=new URL("https://facebook.com/sharer/sharer.php");return t&&n.searchParams.append("t",t),u({...r,sharer:n,urlParam:"u"})},Vt=(e={})=>{let{title:t=document.title,...r}=e,n=new URL("https://work.workplace.com/sharer.php");return t&&n.searchParams.append("t",t),u({...r,sharer:n})},It=(e={})=>{let{title:t=document.title,...r}=e,n=new URL("https://reddit.com/submit");return t&&n.searchParams.append("title",t),u({...r,sharer:n})},Dt=(e={})=>u({...e,sharer:"https://service.weibo.com/share/share.php"}),Lt=(e={})=>u({...e,sharer:"https://vk.com/share.php"}),vt=(e={})=>u({...e,sharer:"https://tumblr.com/widgets/share/tool",urlParam:"canonicalUrl"}),Mt=(e={})=>u({...e,sharer:"https://social-plugins.line.me/lineit/share"}),jt=(e={})=>u({...e,sharer:"https://x.com/intent/tweet"}),Ft=(e={})=>u({...e,sharer:"https://linkedin.com/sharing/share-offsite"}),Nt=(e={})=>u({...e,sharer:"https://telegram.me/share/url"}),zt=(e={})=>{let{url:t=location,media:r,description:n=document.title||document.querySelector('[name="description"]')?.getAttribute("content"),...s}=e,i=Url.format(t),o=new URL("https://pinterest.it/pin-builder");return o.searchParams.append("method","button"),o.searchParams.append("media",r?Url.format(r):i),n&&o.searchParams.append("description",n),u({...s,url:t,sharer:o})},Bt=(e={})=>{let{url:t=location,text:r,...n}=e,s=Url.format(t),i=new URL("https://api.whatsapp.com/send"),o=r?`${r} ${s}`:s;return i.search=new URLSearchParams({text:o}).toString(),E({url:i,...n,context:"sharer"})};var se=(n=>(n.Low="Low",n.Medium="Medium",n.High="High",n))(se||{}),ie=(n=>(n.Strict="Strict",n.Lax="Lax",n.None="None",n))(ie||{}),N=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=g();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?L(o.toString()):o,o==="Expires"&&isValidDate(a)&&(a=a.toUTCString()),o==="MaxAge"&&(o="Max-Age"),[o,x(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[l,m]=a.split("=");if(!l||!l.trim().length)return null;let h=v(M(l)),f=e.parseValue(m,h);return f==null?null:[h,f]}).filter(Boolean);return g([["name",s],["value",e.parseValue(i)],...o])}static fromListString(t){let r=g();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 isValidDate(n)?n:void 0}return r==="httpOnly"||r==="secure"||r==="partitioned"?t!=="false":y(t)}};var z=class e{static get(t){return y(localStorage.getItem(t)||void 0)}static set(t,r){let n=x(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 B=class e{static get(t){return y(sessionStorage.getItem(t)||void 0)}static set(t,r){let n=x(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 rr=e=>e.length<=0?e:[...new Set(e)],nr=(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())},or=e=>e.replace(/\s/g,"").split(",").filter(Boolean);function sr(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 ae=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},ir=e=>ae([...e]),O=(e,t)=>Math.abs((e%t+t)%t),ar=(e,t=0)=>O(t-1,e),cr=(e,t=0)=>O(t+1,e),pr=(e,t,r=-1)=>[...e.slice(0,O(r,e.length)+1),...Array.isArray(t)?t:[t],...e.slice(O(r,e.length)+1)],lr=e=>e.items.findIndex(t=>t[e.field]===e.value);var fr=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 ce="(orientation:portrait)",xr=()=>U(ce);var br=e=>!!e&&(W(e)||G(e)),W=e=>!!e&&(typeof e=="function"||typeof e=="object")&&e.constructor.name==="GeneratorFunction",G=e=>!!e&&(typeof e=="function"||typeof e=="object")&&e.constructor.name==="AsyncGeneratorFunction",wr=e=>!!e&&(pe(e)||le(e)),pe=e=>!!e&&typeof e=="object"&&W(e.constructor),le=e=>!!e&&typeof e=="object"&&G(e.constructor);var kr=e=>{let t={...e};for(let r in t)t[r]==null&&delete t[r];return t},Or=e=>Object.fromEntries(e.entries()),Er=e=>Object.assign(Object.create(Object.getPrototypeOf(e)),e),Ur=(e,t)=>Object.keys(e).find(r=>e[r]===t);var Rr=e=>new Promise(t=>setTimeout(t,e)),ue=(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);}),Kr=e=>((...t)=>ue(e,...t));export{N as Cookie,R as ErrorCode,z as LocalStorage,se as Priority,ie as SameSite,B as SessionStorage,q as WebUtils,yt as addLeadingCharacter,bt as addTrailingCharacter,nr as arrayObjectUnique,rr as arrayUnique,Te as blockScroll,ne as canWebApiShare,oe as canWebApiShareData,sr as chunkInto,Er as cloneObject,A as cloneStyleSheetList,S as cloneStyleSheets,Kr as deferCallback,ue as deferTask,fr as downloadBlob,j as emailDataToString,b as escapeRegExpCharSet,kr as filterObject,lr as findIndexBy,me as getConnection,P as getDimensions,U as getMediaMatches,cr as getNextIndex,Ur as getObjectKey,ar as getPreviousIndex,g as getTypedMap,pr as insertAfter,Y as isArray,Ge as isAsyncFunction,G as isAsyncGeneratorFunction,le as isAsyncGeneratorObject,W as isDefaultGeneratorFunction,pe as isDefaultGeneratorObject,Be as isDev,_ as isDocumentPictureInPictureSupported,I as isEmpty,$e as isEmptyArray,Ze as isEmptyObject,br as isGeneratorFunction,wr as isGeneratorObject,st as isGreaterThan,it as isInRange,qe as isJson,ot as isLessThan,_e as isNodeElement,Je as isNodeList,ee as isNotEmpty,He as isObject,xr as isPortrait,K as isPromise,ct as isSQLStatement,at as isStrictEqual,V as isString,We as isTest,Xe as isTouchDevice,Qe as isTouchEvent,tt as isValidEmail,rt as isValidPhoneNumber,nt as isValidVat,v as lcFirst,or as listToArray,Or as mapToObject,O as normalizeIndex,E as openBrowserPopUp,Ie as openDocumentPictureInPicture,u as openSharerPopUp,St as parameterized,y as parseValue,ce as portraitMediaQuery,k as recipientsToString,Tt as removeLeadingCharacter,wt as removeTrailingCharacter,Q as requiresDocumentPictureInPictureAPI,be as restoreScroll,At as share,Kt as shareOnFacebook,Mt as shareOnLine,Ft as shareOnLinkedIn,zt as shareOnPinterest,It as shareOnReddit,Nt as shareOnTelegram,vt as shareOnTumblr,Lt as shareOnVK,Dt as shareOnWeibo,Bt as shareOnWhatsApp,Vt as shareOnWorkplace,jt as shareOnX,Rt as shareViaEmail,ae as shuffle,ir as shuffleCopy,Rr as sleep,x as stringifyValue,M as toCamelCase,re as toKebabCase,L as ucFirst};