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