@maz-ui/utils 5.0.0-canary.ef64a02.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +1 -1
  2. package/dist/helpers/TextareaAutogrow.js +25 -1
  3. package/dist/helpers/camelCase.js +6 -1
  4. package/dist/helpers/capitalize.js +6 -1
  5. package/dist/helpers/checkAvailability.js +16 -1
  6. package/dist/helpers/cookie.d.ts +38 -0
  7. package/dist/helpers/cookie.js +23 -0
  8. package/dist/helpers/countryCodeToUnicodeFlag.js +10 -1
  9. package/dist/helpers/debounce.js +11 -1
  10. package/dist/helpers/debounceCallback.js +7 -1
  11. package/dist/helpers/debounceId.js +24 -1
  12. package/dist/helpers/fetchLocaleIp.js +12 -1
  13. package/dist/helpers/formatCurrency.js +30 -1
  14. package/dist/helpers/formatDate.js +19 -1
  15. package/dist/helpers/formatJson.js +6 -1
  16. package/dist/helpers/formatNumber.js +18 -1
  17. package/dist/helpers/formatPhoneNumber.js +9 -1
  18. package/dist/helpers/getBrowserLocale.js +11 -1
  19. package/dist/helpers/getCountryFlagUrl.js +8 -1
  20. package/dist/helpers/getErrorMessage.js +6 -1
  21. package/dist/helpers/idleTimeout.js +121 -1
  22. package/dist/helpers/index.d.ts +6 -0
  23. package/dist/helpers/index.js +38 -1
  24. package/dist/helpers/isClient.js +6 -1
  25. package/dist/helpers/isEqual.js +21 -1
  26. package/dist/helpers/isIos.d.ts +1 -0
  27. package/dist/helpers/isIos.js +9 -0
  28. package/dist/helpers/isServer.js +6 -1
  29. package/dist/helpers/isStandaloneMode.js +10 -1
  30. package/dist/helpers/kebabCase.js +6 -1
  31. package/dist/helpers/normalizeString.js +87 -1
  32. package/dist/helpers/pascalCase.js +13 -1
  33. package/dist/helpers/preventIosInputZoom.d.ts +12 -0
  34. package/dist/helpers/preventIosInputZoom.js +15 -0
  35. package/dist/helpers/scriptLoader.js +38 -1
  36. package/dist/helpers/sleep.js +6 -1
  37. package/dist/helpers/snakeCase.js +6 -1
  38. package/dist/helpers/swipeHandler.d.ts +21 -13
  39. package/dist/helpers/swipeHandler.js +83 -1
  40. package/dist/helpers/throttle.js +13 -1
  41. package/dist/helpers/throttleId.js +20 -1
  42. package/dist/helpers/truthyFilter.js +6 -1
  43. package/dist/helpers/upperFirst.js +6 -1
  44. package/dist/helpers/userVisibility.js +47 -1
  45. package/dist/index.js +39 -1
  46. package/package.json +12 -4
package/README.md CHANGED
@@ -163,7 +163,7 @@ const phone = formatPhoneNumber('+33123456789', 'international')
163
163
 
164
164
  ## Requirements
165
165
 
166
- - Node.js >= 18.0.0
166
+ - Node.js >= 22.12.0
167
167
  - TypeScript support included
168
168
  - Tree-shakeable for optimal bundle size
169
169
 
@@ -1 +1,25 @@
1
- import{debounce}from"./debounce.js";var TextareaAutogrow=class{element;constructor(element){this.element=element,this.onFocus=this.onFocus.bind(this),this.autogrow=this.autogrow.bind(this),this.onResize=debounce(this.onResize.bind(this),200),this.connect()}connect(){this.element.addEventListener(`focus`,this.onFocus),this.element.style.resize=`none`,this.element.style.boxSizing=`border-box`}disconnect(){window.removeEventListener(`resize`,this.onResize),this.element.removeEventListener(`input`,this.autogrow)}onFocus(){this.autogrow(),this.element.addEventListener(`input`,this.autogrow),window.addEventListener(`resize`,this.onResize),this.element.removeEventListener(`focus`,this.onFocus)}onResize(){this.autogrow()}autogrow(){this.element.style.height=`auto`,this.element.style.overflow=`hidden`,this.element.style.height=`${this.element.scrollHeight}px`}};export{TextareaAutogrow};
1
+ import { debounce } from "./debounce.js";
2
+ //#region src/helpers/TextareaAutogrow.ts
3
+ var TextareaAutogrow = class {
4
+ element;
5
+ constructor(element) {
6
+ this.element = element, this.onFocus = this.onFocus.bind(this), this.autogrow = this.autogrow.bind(this), this.onResize = debounce(this.onResize.bind(this), 200), this.connect();
7
+ }
8
+ connect() {
9
+ this.element.addEventListener("focus", this.onFocus), this.element.style.resize = "none", this.element.style.boxSizing = "border-box";
10
+ }
11
+ disconnect() {
12
+ window.removeEventListener("resize", this.onResize), this.element.removeEventListener("input", this.autogrow);
13
+ }
14
+ onFocus() {
15
+ this.autogrow(), this.element.addEventListener("input", this.autogrow), window.addEventListener("resize", this.onResize), this.element.removeEventListener("focus", this.onFocus);
16
+ }
17
+ onResize() {
18
+ this.autogrow();
19
+ }
20
+ autogrow() {
21
+ this.element.style.height = "auto", this.element.style.overflow = "hidden", this.element.style.height = `${this.element.scrollHeight}px`;
22
+ }
23
+ };
24
+ //#endregion
25
+ export { TextareaAutogrow };
@@ -1 +1,6 @@
1
- function camelCase(str){return str.replaceAll(/-(\w)/g,(_,c)=>c?c.toUpperCase():``)}export{camelCase};
1
+ //#region src/helpers/camelCase.ts
2
+ function camelCase(str) {
3
+ return str.replaceAll(/-(\w)/g, (_, c) => c ? c.toUpperCase() : "");
4
+ }
5
+ //#endregion
6
+ export { camelCase };
@@ -1 +1,6 @@
1
- function capitalize(value){return typeof value==`string`?value.charAt(0).toUpperCase()+value.slice(1):``}export{capitalize};
1
+ //#region src/helpers/capitalize.ts
2
+ function capitalize(value) {
3
+ return typeof value == "string" ? value.charAt(0).toUpperCase() + value.slice(1) : "";
4
+ }
5
+ //#endregion
6
+ export { capitalize };
@@ -1 +1,16 @@
1
- function checkAvailability(getRef,callback,options){let opts={maxAttempts:20,interval:100,...options};let attempts=0;function check(){let ref=getRef();ref==null||opts.expectedValue!==void 0&&ref!==opts.expectedValue?attempts<opts.maxAttempts?(attempts++,setTimeout(check,opts.interval)):opts.onError?.(Error(opts.errorMessage||`[maz-ui](checkAvailability) Nothing found after ${opts.maxAttempts} attempts`)):callback(ref)}check()}export{checkAvailability};
1
+ //#region src/helpers/checkAvailability.ts
2
+ function checkAvailability(getRef, callback, options) {
3
+ let opts = {
4
+ maxAttempts: 20,
5
+ interval: 100,
6
+ ...options
7
+ };
8
+ let attempts = 0;
9
+ function check() {
10
+ let ref = getRef();
11
+ ref == null || opts.expectedValue !== void 0 && ref !== opts.expectedValue ? attempts < opts.maxAttempts ? (attempts++, setTimeout(check, opts.interval)) : opts.onError?.(Error(opts.errorMessage || `[maz-ui](checkAvailability) Nothing found after ${opts.maxAttempts} attempts`)) : callback(ref);
12
+ }
13
+ check();
14
+ }
15
+ //#endregion
16
+ export { checkAvailability };
@@ -0,0 +1,38 @@
1
+ export type CookieSameSite = 'Lax' | 'Strict' | 'None' | 'lax' | 'strict' | 'none';
2
+ export interface CookieOptions {
3
+ /** Path attribute. Defaults to `'/'`. Pass `null` to omit. */
4
+ path?: string | null;
5
+ /** Domain attribute. */
6
+ domain?: string;
7
+ /** Lifetime in seconds. Defaults to one year. Pass `null` to omit (session cookie). */
8
+ maxAge?: number | null;
9
+ /** Explicit expiration date. Takes precedence over `maxAge` when both are set. */
10
+ expires?: Date;
11
+ /** Restrict the cookie to HTTPS connections. */
12
+ secure?: boolean;
13
+ /** Same-site policy. Defaults to `'Lax'`. Pass `null` to omit. */
14
+ sameSite?: CookieSameSite | null;
15
+ /** Mark the cookie as partitioned (CHIPS). */
16
+ partitioned?: boolean;
17
+ }
18
+ /**
19
+ * Read a cookie by key.
20
+ *
21
+ * - On the client, the cookie is read from `document.cookie`.
22
+ * - On the server, pass the raw `Cookie` request header via `cookieHeader`
23
+ * (e.g. from `useSSRContext().event.node.req.headers.cookie` in Nuxt) to
24
+ * resolve the value during SSR. Without it, the function returns `null`.
25
+ */
26
+ export declare function getCookie(key: string, cookieHeader?: string): string | null;
27
+ /**
28
+ * Write a cookie via `document.cookie` with full attribute support.
29
+ *
30
+ * No-op on the server. `HttpOnly` is intentionally omitted as it cannot be set
31
+ * from `document.cookie` (browsers reject it).
32
+ */
33
+ export declare function setCookie(key: string, value: string, options?: CookieOptions): void;
34
+ /**
35
+ * Delete a cookie by writing `max-age=0`. `path` and `domain` must match the
36
+ * cookie's original attributes for the browser to actually drop it.
37
+ */
38
+ export declare function deleteCookie(key: string, options?: Pick<CookieOptions, 'path' | 'domain'>): void;
@@ -0,0 +1,23 @@
1
+ import { isServer } from "./isServer.js";
2
+ //#region src/helpers/cookie.ts
3
+ var ONE_YEAR_SECONDS = 31536e3;
4
+ function getCookie(key, cookieHeader) {
5
+ let source = isServer() ? cookieHeader : document.cookie;
6
+ if (!source) return null;
7
+ let cookie = source.split(";").find((c) => c.trim().startsWith(`${key}=`));
8
+ return cookie ? decodeURIComponent(cookie.split("=")[1]) : null;
9
+ }
10
+ function setCookie(key, value, options = {}) {
11
+ if (isServer()) return;
12
+ let { path = "/", domain, maxAge = ONE_YEAR_SECONDS, expires, secure, sameSite = "Lax", partitioned } = options;
13
+ let parts = [`${key}=${encodeURIComponent(value)}`];
14
+ path != null && parts.push(`path=${path}`), domain && parts.push(`domain=${domain}`), maxAge != null && parts.push(`max-age=${maxAge}`), expires && parts.push(`expires=${expires.toUTCString()}`), secure && parts.push("secure"), sameSite != null && parts.push(`SameSite=${sameSite}`), partitioned && parts.push("partitioned"), document.cookie = parts.join("; ");
15
+ }
16
+ function deleteCookie(key, options = {}) {
17
+ setCookie(key, "", {
18
+ ...options,
19
+ maxAge: 0
20
+ });
21
+ }
22
+ //#endregion
23
+ export { deleteCookie, getCookie, setCookie };
@@ -1 +1,10 @@
1
- import{truthyFilter}from"./truthyFilter.js";function countryCodeToUnicodeFlag(locale){return Array.from(locale,letter=>{let code=letter.codePointAt(0);return code?code%32+127461:void 0}).filter(truthyFilter).map(n=>String.fromCodePoint(n)).join(``)}export{countryCodeToUnicodeFlag};
1
+ import { truthyFilter } from "./truthyFilter.js";
2
+ //#region src/helpers/countryCodeToUnicodeFlag.ts
3
+ function countryCodeToUnicodeFlag(locale) {
4
+ return Array.from(locale, (letter) => {
5
+ let code = letter.codePointAt(0);
6
+ return code ? code % 32 + 127461 : void 0;
7
+ }).filter(truthyFilter).map((n) => String.fromCodePoint(n)).join("");
8
+ }
9
+ //#endregion
10
+ export { countryCodeToUnicodeFlag };
@@ -1 +1,11 @@
1
- function debounce(fn,delay){let timeout;return function(...args){clearTimeout(timeout),timeout=setTimeout(()=>{fn.apply(this,args)},delay)}}export{debounce};
1
+ //#region src/helpers/debounce.ts
2
+ function debounce(fn, delay) {
3
+ let timeout;
4
+ return function(...args) {
5
+ clearTimeout(timeout), timeout = setTimeout(() => {
6
+ fn.apply(this, args);
7
+ }, delay);
8
+ };
9
+ }
10
+ //#endregion
11
+ export { debounce };
@@ -1 +1,7 @@
1
- var timeout=null;function debounceCallback(callback,delay){timeout&&clearTimeout(timeout),timeout=setTimeout(callback,delay)}export{debounceCallback};
1
+ //#region src/helpers/debounceCallback.ts
2
+ var timeout = null;
3
+ function debounceCallback(callback, delay) {
4
+ timeout && clearTimeout(timeout), timeout = setTimeout(callback, delay);
5
+ }
6
+ //#endregion
7
+ export { debounceCallback };
@@ -1 +1,24 @@
1
- function debounceId(identifier,func,delay){let debouncedFunctions={};return function(...args){debouncedFunctions[identifier]||(debouncedFunctions[identifier]={timer:null,promise:null});let debounced=debouncedFunctions[identifier];return debounced.timer&&clearTimeout(debounced.timer),debounced.promise=new Promise((resolve,reject)=>{debounced.timer=setTimeout(async()=>{try{resolve(await func(...args))}catch(error){reject(error)}finally{delete debouncedFunctions[identifier]}},delay)}),debounced.promise}}export{debounceId};
1
+ //#region src/helpers/debounceId.ts
2
+ function debounceId(identifier, func, delay) {
3
+ let debouncedFunctions = {};
4
+ return function(...args) {
5
+ debouncedFunctions[identifier] || (debouncedFunctions[identifier] = {
6
+ timer: null,
7
+ promise: null
8
+ });
9
+ let debounced = debouncedFunctions[identifier];
10
+ return debounced.timer && clearTimeout(debounced.timer), debounced.promise = new Promise((resolve, reject) => {
11
+ debounced.timer = setTimeout(async () => {
12
+ try {
13
+ resolve(await func(...args));
14
+ } catch (error) {
15
+ reject(error);
16
+ } finally {
17
+ delete debouncedFunctions[identifier];
18
+ }
19
+ }, delay);
20
+ }), debounced.promise;
21
+ };
22
+ }
23
+ //#endregion
24
+ export { debounceId };
@@ -1 +1,12 @@
1
- async function fetchLocaleIp(){try{let{country_code}=await(await fetch(`https://ipwho.is`)).json();return country_code}catch(error){console.error(`[maz-ui](fetchLocaleIp) ${error}`);return}}export{fetchLocaleIp};
1
+ //#region src/helpers/fetchLocaleIp.ts
2
+ async function fetchLocaleIp() {
3
+ try {
4
+ let { country_code } = await (await fetch("https://ipwho.is")).json();
5
+ return country_code;
6
+ } catch (error) {
7
+ console.error(`[maz-ui](fetchLocaleIp) ${error}`);
8
+ return;
9
+ }
10
+ }
11
+ //#endregion
12
+ export { fetchLocaleIp };
@@ -1 +1,30 @@
1
- var DEFAULT_OPTIONS={style:`currency`,minimumFractionDigits:2,round:!1};function getFormattedCurrency(number,locale,options){let numberToFormat=+number;return options.round&&(numberToFormat=Math.floor(numberToFormat),options.minimumFractionDigits=0),new Intl.NumberFormat(locale,options).format(numberToFormat)}function validRequiredAttributes(number,locale,options){if(number===void 0)throw TypeError("[maz-ui](FilterCurrency) The `number` attribute is required.");if(locale===void 0)throw TypeError("[maz-ui](FilterCurrency) The `locale` attribute is required.");if(typeof locale!=`string`)throw TypeError("[maz-ui](FilterCurrency) The `locale` attribute must be a string.");if(options.currency===void 0)throw TypeError("[maz-ui](FilterCurrency) The `options.currency` attribute is required.")}function formatCurrency(number,locale,options){let options_={...DEFAULT_OPTIONS,...options};validRequiredAttributes(number,locale,options_);try{return getFormattedCurrency(number,locale,options_)}catch(error){throw Error(`[maz-ui](FilterCurrency) ${error}`,{cause:error})}}export{formatCurrency};
1
+ //#region src/helpers/formatCurrency.ts
2
+ var DEFAULT_OPTIONS = {
3
+ style: "currency",
4
+ minimumFractionDigits: 2,
5
+ round: !1
6
+ };
7
+ function getFormattedCurrency(number, locale, options) {
8
+ let numberToFormat = +number;
9
+ return options.round && (numberToFormat = Math.floor(numberToFormat), options.minimumFractionDigits = 0), new Intl.NumberFormat(locale, options).format(numberToFormat);
10
+ }
11
+ function validRequiredAttributes(number, locale, options) {
12
+ if (number === void 0) throw TypeError("[maz-ui](FilterCurrency) The `number` attribute is required.");
13
+ if (locale === void 0) throw TypeError("[maz-ui](FilterCurrency) The `locale` attribute is required.");
14
+ if (typeof locale != "string") throw TypeError("[maz-ui](FilterCurrency) The `locale` attribute must be a string.");
15
+ if (options.currency === void 0) throw TypeError("[maz-ui](FilterCurrency) The `options.currency` attribute is required.");
16
+ }
17
+ function formatCurrency(number, locale, options) {
18
+ let options_ = {
19
+ ...DEFAULT_OPTIONS,
20
+ ...options
21
+ };
22
+ validRequiredAttributes(number, locale, options_);
23
+ try {
24
+ return getFormattedCurrency(number, locale, options_);
25
+ } catch (error) {
26
+ throw Error(`[maz-ui](FilterCurrency) ${error}`, { cause: error });
27
+ }
28
+ }
29
+ //#endregion
30
+ export { formatCurrency };
@@ -1 +1,19 @@
1
- var DEFAULT_OPTIONS={month:`short`,day:`numeric`,year:`numeric`};function formatDate(date,locale,options){if(locale===void 0)throw TypeError("[maz-ui](FilterDate) The `locale` attribute is required.");if(typeof locale!=`string`)throw TypeError("[maz-ui](FilterDate) The `locale` attribute must be a string.");let opts=options??DEFAULT_OPTIONS;try{let usedDate=date instanceof Date?date:new Date(date);return new Intl.DateTimeFormat(locale,opts).format(usedDate)}catch(error){throw Error(`[maz-ui](FilterDate) ${error}`,{cause:error})}}export{formatDate};
1
+ //#region src/helpers/formatDate.ts
2
+ var DEFAULT_OPTIONS = {
3
+ month: "short",
4
+ day: "numeric",
5
+ year: "numeric"
6
+ };
7
+ function formatDate(date, locale, options) {
8
+ if (locale === void 0) throw TypeError("[maz-ui](FilterDate) The `locale` attribute is required.");
9
+ if (typeof locale != "string") throw TypeError("[maz-ui](FilterDate) The `locale` attribute must be a string.");
10
+ let opts = options ?? DEFAULT_OPTIONS;
11
+ try {
12
+ let usedDate = date instanceof Date ? date : new Date(date);
13
+ return new Intl.DateTimeFormat(locale, opts).format(usedDate);
14
+ } catch (error) {
15
+ throw Error(`[maz-ui](FilterDate) ${error}`, { cause: error });
16
+ }
17
+ }
18
+ //#endregion
19
+ export { formatDate };
@@ -1 +1,6 @@
1
- function formatJson(json,indent=2){return JSON.stringify(json,null,indent)}export{formatJson};
1
+ //#region src/helpers/formatJson.ts
2
+ function formatJson(json, indent = 2) {
3
+ return JSON.stringify(json, null, indent);
4
+ }
5
+ //#endregion
6
+ export { formatJson };
@@ -1 +1,18 @@
1
- var DEFAULT_OPTIONS={minimumFractionDigits:2};function formatNumber(number,locale,options){let filterOptions={...DEFAULT_OPTIONS,...options};if(number===void 0)throw TypeError("[maz-ui](FilterNumber) The `number` attribute is required.");if(locale===void 0)throw TypeError("[maz-ui](FilterNumber) The `locale` attribute is required.");if(typeof locale!=`string`)throw TypeError("[maz-ui](FilterNumber) The `locale` attribute must be a string.");try{return new Intl.NumberFormat(locale,filterOptions).format(Number(number))}catch(error){throw Error(`[maz-ui](FilterNumber) ${error}`,{cause:error})}}export{formatNumber};
1
+ //#region src/helpers/formatNumber.ts
2
+ var DEFAULT_OPTIONS = { minimumFractionDigits: 2 };
3
+ function formatNumber(number, locale, options) {
4
+ let filterOptions = {
5
+ ...DEFAULT_OPTIONS,
6
+ ...options
7
+ };
8
+ if (number === void 0) throw TypeError("[maz-ui](FilterNumber) The `number` attribute is required.");
9
+ if (locale === void 0) throw TypeError("[maz-ui](FilterNumber) The `locale` attribute is required.");
10
+ if (typeof locale != "string") throw TypeError("[maz-ui](FilterNumber) The `locale` attribute must be a string.");
11
+ try {
12
+ return new Intl.NumberFormat(locale, filterOptions).format(Number(number));
13
+ } catch (error) {
14
+ throw Error(`[maz-ui](FilterNumber) ${error}`, { cause: error });
15
+ }
16
+ }
17
+ //#endregion
18
+ export { formatNumber };
@@ -1 +1,9 @@
1
- import{parsePhoneNumberFromString}from"libphonenumber-js";function formatPhoneNumber(phoneNumber){if(!phoneNumber)throw TypeError("[maz-ui](formatPhoneNumber) The `phoneNumber` argument is required.");let parsedPhone=parsePhoneNumberFromString(phoneNumber);return parsedPhone?parsedPhone.formatInternational():phoneNumber}export{formatPhoneNumber};
1
+ import { parsePhoneNumberFromString } from "libphonenumber-js";
2
+ //#region src/helpers/formatPhoneNumber.ts
3
+ function formatPhoneNumber(phoneNumber) {
4
+ if (!phoneNumber) throw TypeError("[maz-ui](formatPhoneNumber) The `phoneNumber` argument is required.");
5
+ let parsedPhone = parsePhoneNumberFromString(phoneNumber);
6
+ return parsedPhone ? parsedPhone.formatInternational() : phoneNumber;
7
+ }
8
+ //#endregion
9
+ export { formatPhoneNumber };
@@ -1 +1,11 @@
1
- import{isServer}from"./isServer.js";function getBrowserLocale(){try{return isServer()?void 0:globalThis.navigator.language}catch(error){throw Error(`[MazInputPhoneNumber] (browserLocale) ${error}`,{cause:error})}}export{getBrowserLocale};
1
+ import { isServer } from "./isServer.js";
2
+ //#region src/helpers/getBrowserLocale.ts
3
+ function getBrowserLocale() {
4
+ try {
5
+ return isServer() ? void 0 : globalThis.navigator.language;
6
+ } catch (error) {
7
+ throw Error(`[MazInputPhoneNumber] (browserLocale) ${error}`, { cause: error });
8
+ }
9
+ }
10
+ //#endregion
11
+ export { getBrowserLocale };
@@ -1 +1,8 @@
1
- var _supportedCodes=`ad.ae.af.ag.ai.al.am.ao.aq.ar.as.at.au.aw.ax.az.ba.bb.bd.be.bf.bg.bh.bi.bj.bl.bm.bn.bo.bq.br.bs.bt.bv.bw.by.bz.ca.cc.cd.cf.cg.ch.ci.ck.cl.cm.cn.co.cr.cu.cv.cw.cx.cy.cz.de.dj.dk.dm.do.dz.ec.ee.eg.eh.er.es.et.eu.fi.fj.fk.fm.fo.fr.ga.gb.gb-eng.gb-nir.gb-sct.gb-wls.gd.ge.gf.gg.gh.gi.gl.gm.gn.gp.gq.gr.gs.gt.gu.gw.gy.hk.hm.hn.hr.ht.hu.id.ie.il.im.in.io.iq.ir.is.it.je.jm.jo.jp.ke.kg.kh.ki.km.kn.kp.kr.kw.ky.kz.la.lb.lc.li.lk.lr.ls.lt.lu.lv.ly.ma.mc.md.me.mf.mg.mh.mk.ml.mm.mn.mo.mp.mq.mr.ms.mt.mu.mv.mw.mx.my.mz.na.nc.ne.nf.ng.ni.nl.no.np.nr.nu.nz.om.pa.pe.pf.pg.ph.pk.pl.pm.pn.pr.ps.pt.pw.py.qa.re.ro.rs.ru.rw.sa.sb.sc.sd.se.sg.sh.si.sj.sk.sl.sm.sn.so.sr.ss.st.sv.sx.sy.sz.tc.td.tf.tg.th.tj.tk.tl.tm.tn.to.tr.tt.tv.tw.tz.ua.ug.um.un.us.us-ak.us-al.us-ar.us-az.us-ca.us-co.us-ct.us-de.us-fl.us-ga.us-hi.us-ia.us-id.us-il.us-in.us-ks.us-ky.us-la.us-ma.us-md.us-me.us-mi.us-mn.us-mo.us-ms.us-mt.us-nc.us-nd.us-ne.us-nh.us-nj.us-nm.us-nv.us-ny.us-oh.us-ok.us-or.us-pa.us-ri.us-sc.us-sd.us-tn.us-tx.us-ut.us-va.us-vt.us-wa.us-wi.us-wv.us-wy.uy.uz.va.vc.ve.vg.vi.vn.vu.wf.ws.xk.ye.yt.za.zm.zw`.split(`.`);function getCountryFlagUrl(countryIsoCode,size){let code=countryIsoCode.toLowerCase();if(_supportedCodes.includes(code))return size?`https://flagcdn.com/${size}/${code}.png`:`https://flagcdn.com/${code}.svg`}export{getCountryFlagUrl};
1
+ //#region src/helpers/getCountryFlagUrl.ts
2
+ var _supportedCodes = /* @__PURE__ */ "ad.ae.af.ag.ai.al.am.ao.aq.ar.as.at.au.aw.ax.az.ba.bb.bd.be.bf.bg.bh.bi.bj.bl.bm.bn.bo.bq.br.bs.bt.bv.bw.by.bz.ca.cc.cd.cf.cg.ch.ci.ck.cl.cm.cn.co.cr.cu.cv.cw.cx.cy.cz.de.dj.dk.dm.do.dz.ec.ee.eg.eh.er.es.et.eu.fi.fj.fk.fm.fo.fr.ga.gb.gb-eng.gb-nir.gb-sct.gb-wls.gd.ge.gf.gg.gh.gi.gl.gm.gn.gp.gq.gr.gs.gt.gu.gw.gy.hk.hm.hn.hr.ht.hu.id.ie.il.im.in.io.iq.ir.is.it.je.jm.jo.jp.ke.kg.kh.ki.km.kn.kp.kr.kw.ky.kz.la.lb.lc.li.lk.lr.ls.lt.lu.lv.ly.ma.mc.md.me.mf.mg.mh.mk.ml.mm.mn.mo.mp.mq.mr.ms.mt.mu.mv.mw.mx.my.mz.na.nc.ne.nf.ng.ni.nl.no.np.nr.nu.nz.om.pa.pe.pf.pg.ph.pk.pl.pm.pn.pr.ps.pt.pw.py.qa.re.ro.rs.ru.rw.sa.sb.sc.sd.se.sg.sh.si.sj.sk.sl.sm.sn.so.sr.ss.st.sv.sx.sy.sz.tc.td.tf.tg.th.tj.tk.tl.tm.tn.to.tr.tt.tv.tw.tz.ua.ug.um.un.us.us-ak.us-al.us-ar.us-az.us-ca.us-co.us-ct.us-de.us-fl.us-ga.us-hi.us-ia.us-id.us-il.us-in.us-ks.us-ky.us-la.us-ma.us-md.us-me.us-mi.us-mn.us-mo.us-ms.us-mt.us-nc.us-nd.us-ne.us-nh.us-nj.us-nm.us-nv.us-ny.us-oh.us-ok.us-or.us-pa.us-ri.us-sc.us-sd.us-tn.us-tx.us-ut.us-va.us-vt.us-wa.us-wi.us-wv.us-wy.uy.uz.va.vc.ve.vg.vi.vn.vu.wf.ws.xk.ye.yt.za.zm.zw".split(".");
3
+ function getCountryFlagUrl(countryIsoCode, size) {
4
+ let code = countryIsoCode.toLowerCase();
5
+ if (_supportedCodes.includes(code)) return size ? `https://flagcdn.com/${size}/${code}.png` : `https://flagcdn.com/${code}.svg`;
6
+ }
7
+ //#endregion
8
+ export { getCountryFlagUrl };
@@ -1 +1,6 @@
1
- function getErrorMessage(error){return error instanceof Error?error.message:typeof error==`string`?error:error&&typeof error==`object`&&`message`in error?String(error.message):error?String(error):`An unexpected error occurred`}export{getErrorMessage};
1
+ //#region src/helpers/getErrorMessage.ts
2
+ function getErrorMessage(error) {
3
+ return error instanceof Error ? error.message : typeof error == "string" ? error : error && typeof error == "object" && "message" in error ? String(error.message) : error ? String(error) : "An unexpected error occurred";
4
+ }
5
+ //#endregion
6
+ export { getErrorMessage };
@@ -1 +1,121 @@
1
- import{isClient}from"./isClient.js";var IdleTimeout=class{defaultOptions={element:void 0,timeout:60*1e3*5,once:!1,immediate:!0};options;timeoutHandler;isIdle=!1;isDestroy=!1;startTime=0;remainingTime=0;lastClientX=-1;lastClientY=-1;eventNames=[`DOMMouseScroll`,`mousedown`,`mousemove`,`mousewheel`,`MSPointerDown`,`MSPointerMove`,`keydown`,`touchmove`,`touchstart`,`wheel`,`click`];constructor(callback,options){this.callback=callback,this.options={...this.defaultOptions,...options},isClient()&&this.start()}get element(){return this.options.element??document.body}start(){if(!isClient()){console.warn(`[IdleTimeout](start) you should run this method on client side`);return}for(let eventName of this.eventNames)this.element.addEventListener(eventName,this.handleEvent);this.resetTimeout(),this.options.immediate&&this.callback({isIdle:!1,instance:this})}pause(){let remainingTime=this.startTime+this.options.timeout-Date.now();remainingTime<=0||(this.remainingTime=remainingTime,this.timeoutHandler&&=(clearTimeout(this.timeoutHandler),void 0))}resume(){this.remainingTime<=0||(this.resetTimeout(),this.callback({isIdle:this.isIdle,instance:this}),this.remainingTime=0)}reset(){this.isDestroy=!1,this.isIdle=!1,this.remainingTime=0,this.resetTimeout(),this.callback({isIdle:this.isIdle,instance:this})}destroy(){if(!isClient()){console.warn(`[IdleTimeout](destroy) you should run this method on client side`);return}this.isDestroy=!0;for(let eventName of this.eventNames)this.element.removeEventListener(eventName,this.handleEvent);this.timeoutHandler&&clearTimeout(this.timeoutHandler)}resetTimeout(){this.isIdle=!1,this.timeoutHandler&&=(clearTimeout(this.timeoutHandler),void 0),this.timeoutHandler=setTimeout(this.handleTimeout.bind(this),this.remainingTime||this.options.timeout),this.startTime=Date.now()}handleEvent=event=>{try{if(this.remainingTime>0)return;if(event.type===`mousemove`){let{clientX,clientY}=event;if(clientX===void 0&&clientY===void 0||clientX===this.lastClientX&&clientY===this.lastClientY)return;this.lastClientX=clientX,this.lastClientY=clientY}this.resetTimeout(),this.callback({isIdle:this.isIdle,eventType:event.type,instance:this})}catch(error){throw Error(`[IdleTimeout](handleEvent) ${error}`,{cause:error})}};handleTimeout(){this.isIdle=!0,this.callback({isIdle:this.isIdle,instance:this}),this.options.once&&this.destroy()}get destroyed(){return this.isDestroy}get timeout(){return this.options.timeout}set timeout(value){this.options.timeout=value}get idle(){return this.isIdle}set idle(value){value?this.handleTimeout():this.reset(),this.callback({isIdle:this.isIdle,instance:this})}};export{IdleTimeout};
1
+ import { isClient } from "./isClient.js";
2
+ //#region src/helpers/idleTimeout.ts
3
+ var IdleTimeout = class {
4
+ callback;
5
+ defaultOptions = {
6
+ element: void 0,
7
+ timeout: 3e5,
8
+ once: !1,
9
+ immediate: !0
10
+ };
11
+ options;
12
+ timeoutHandler;
13
+ isIdle = !1;
14
+ isDestroy = !1;
15
+ startTime = 0;
16
+ remainingTime = 0;
17
+ lastClientX = -1;
18
+ lastClientY = -1;
19
+ eventNames = [
20
+ "DOMMouseScroll",
21
+ "mousedown",
22
+ "mousemove",
23
+ "mousewheel",
24
+ "MSPointerDown",
25
+ "MSPointerMove",
26
+ "keydown",
27
+ "touchmove",
28
+ "touchstart",
29
+ "wheel",
30
+ "click"
31
+ ];
32
+ constructor(callback, options) {
33
+ this.callback = callback, this.options = {
34
+ ...this.defaultOptions,
35
+ ...options
36
+ }, isClient() && this.start();
37
+ }
38
+ get element() {
39
+ return this.options.element ?? document.body;
40
+ }
41
+ start() {
42
+ if (!isClient()) console.warn("[IdleTimeout](start) you should run this method on client side");
43
+ else {
44
+ for (let eventName of this.eventNames) this.element.addEventListener(eventName, this.handleEvent);
45
+ this.resetTimeout(), this.options.immediate && this.callback({
46
+ isIdle: !1,
47
+ instance: this
48
+ });
49
+ }
50
+ }
51
+ pause() {
52
+ let remainingTime = this.startTime + this.options.timeout - Date.now();
53
+ remainingTime <= 0 || (this.remainingTime = remainingTime, this.timeoutHandler &&= (clearTimeout(this.timeoutHandler), void 0));
54
+ }
55
+ resume() {
56
+ this.remainingTime <= 0 || (this.resetTimeout(), this.callback({
57
+ isIdle: this.isIdle,
58
+ instance: this
59
+ }), this.remainingTime = 0);
60
+ }
61
+ reset() {
62
+ this.isDestroy = !1, this.isIdle = !1, this.remainingTime = 0, this.resetTimeout(), this.callback({
63
+ isIdle: this.isIdle,
64
+ instance: this
65
+ });
66
+ }
67
+ destroy() {
68
+ if (!isClient()) console.warn("[IdleTimeout](destroy) you should run this method on client side");
69
+ else {
70
+ this.isDestroy = !0;
71
+ for (let eventName of this.eventNames) this.element.removeEventListener(eventName, this.handleEvent);
72
+ this.timeoutHandler && clearTimeout(this.timeoutHandler);
73
+ }
74
+ }
75
+ resetTimeout() {
76
+ this.isIdle = !1, this.timeoutHandler &&= (clearTimeout(this.timeoutHandler), void 0), this.timeoutHandler = setTimeout(this.handleTimeout.bind(this), this.remainingTime || this.options.timeout), this.startTime = Date.now();
77
+ }
78
+ handleEvent = (event) => {
79
+ try {
80
+ if (this.remainingTime > 0) return;
81
+ if (event.type === "mousemove") {
82
+ let { clientX, clientY } = event;
83
+ if (clientX === void 0 && clientY === void 0 || clientX === this.lastClientX && clientY === this.lastClientY) return;
84
+ this.lastClientX = clientX, this.lastClientY = clientY;
85
+ }
86
+ this.resetTimeout(), this.callback({
87
+ isIdle: this.isIdle,
88
+ eventType: event.type,
89
+ instance: this
90
+ });
91
+ } catch (error) {
92
+ throw Error(`[IdleTimeout](handleEvent) ${error}`, { cause: error });
93
+ }
94
+ };
95
+ handleTimeout() {
96
+ this.isIdle = !0, this.callback({
97
+ isIdle: this.isIdle,
98
+ instance: this
99
+ }), this.options.once && this.destroy();
100
+ }
101
+ get destroyed() {
102
+ return this.isDestroy;
103
+ }
104
+ get timeout() {
105
+ return this.options.timeout;
106
+ }
107
+ set timeout(value) {
108
+ this.options.timeout = value;
109
+ }
110
+ get idle() {
111
+ return this.isIdle;
112
+ }
113
+ set idle(value) {
114
+ value ? this.handleTimeout() : this.reset(), this.callback({
115
+ isIdle: this.isIdle,
116
+ instance: this
117
+ });
118
+ }
119
+ };
120
+ //#endregion
121
+ export { IdleTimeout };
@@ -1,24 +1,30 @@
1
1
  export * from './camelCase';
2
2
  export * from './capitalize';
3
3
  export * from './checkAvailability';
4
+ export * from './cookie';
4
5
  export * from './countryCodeToUnicodeFlag';
5
6
  export * from './debounce';
6
7
  export * from './debounceCallback';
7
8
  export * from './debounceId';
9
+ export * from './fetchLocaleIp';
8
10
  export * from './formatCurrency';
9
11
  export * from './formatDate';
10
12
  export * from './formatJson';
11
13
  export * from './formatNumber';
14
+ export * from './formatPhoneNumber';
15
+ export * from './getBrowserLocale';
12
16
  export * from './getCountryFlagUrl';
13
17
  export * from './getErrorMessage';
14
18
  export * from './idleTimeout';
15
19
  export * from './isClient';
16
20
  export * from './isEqual';
21
+ export * from './isIos';
17
22
  export * from './isServer';
18
23
  export * from './isStandaloneMode';
19
24
  export * from './kebabCase';
20
25
  export * from './normalizeString';
21
26
  export * from './pascalCase';
27
+ export * from './preventIosInputZoom';
22
28
  export * from './scriptLoader';
23
29
  export * from './sleep';
24
30
  export * from './snakeCase';
@@ -1 +1,38 @@
1
- import{camelCase}from"./camelCase.js";import{capitalize}from"./capitalize.js";import{checkAvailability}from"./checkAvailability.js";import{truthyFilter}from"./truthyFilter.js";import{countryCodeToUnicodeFlag}from"./countryCodeToUnicodeFlag.js";import{debounce}from"./debounce.js";import{debounceCallback}from"./debounceCallback.js";import{debounceId}from"./debounceId.js";import{formatCurrency}from"./formatCurrency.js";import{formatDate}from"./formatDate.js";import{formatJson}from"./formatJson.js";import{formatNumber}from"./formatNumber.js";import{getCountryFlagUrl}from"./getCountryFlagUrl.js";import{getErrorMessage}from"./getErrorMessage.js";import{isClient}from"./isClient.js";import{IdleTimeout}from"./idleTimeout.js";import{isEqual}from"./isEqual.js";import{isServer}from"./isServer.js";import{isStandaloneMode}from"./isStandaloneMode.js";import{kebabCase}from"./kebabCase.js";import{pascalCase}from"./pascalCase.js";import{snakeCase}from"./snakeCase.js";import{normalizeString}from"./normalizeString.js";import{ScriptLoader}from"./scriptLoader.js";import{sleep}from"./sleep.js";import{Swipe}from"./swipeHandler.js";import{TextareaAutogrow}from"./TextareaAutogrow.js";import{throttle}from"./throttle.js";import{throttleId}from"./throttleId.js";import{upperFirst}from"./upperFirst.js";import{UserVisibility}from"./userVisibility.js";export{IdleTimeout,ScriptLoader,Swipe,TextareaAutogrow,UserVisibility,camelCase,capitalize,checkAvailability,countryCodeToUnicodeFlag,debounce,debounceCallback,debounceId,formatCurrency,formatDate,formatJson,formatNumber,getCountryFlagUrl,getErrorMessage,isClient,isEqual,isServer,isStandaloneMode,kebabCase,normalizeString,pascalCase,sleep,snakeCase,throttle,throttleId,truthyFilter,upperFirst};
1
+ import { camelCase } from "./camelCase.js";
2
+ import { capitalize } from "./capitalize.js";
3
+ import { checkAvailability } from "./checkAvailability.js";
4
+ import { isServer } from "./isServer.js";
5
+ import { deleteCookie, getCookie, setCookie } from "./cookie.js";
6
+ import { truthyFilter } from "./truthyFilter.js";
7
+ import { countryCodeToUnicodeFlag } from "./countryCodeToUnicodeFlag.js";
8
+ import { debounce } from "./debounce.js";
9
+ import { debounceCallback } from "./debounceCallback.js";
10
+ import { debounceId } from "./debounceId.js";
11
+ import { fetchLocaleIp } from "./fetchLocaleIp.js";
12
+ import { formatCurrency } from "./formatCurrency.js";
13
+ import { formatDate } from "./formatDate.js";
14
+ import { formatJson } from "./formatJson.js";
15
+ import { formatNumber } from "./formatNumber.js";
16
+ import { formatPhoneNumber } from "./formatPhoneNumber.js";
17
+ import { getBrowserLocale } from "./getBrowserLocale.js";
18
+ import { getCountryFlagUrl } from "./getCountryFlagUrl.js";
19
+ import { getErrorMessage } from "./getErrorMessage.js";
20
+ import { isClient } from "./isClient.js";
21
+ import { IdleTimeout } from "./idleTimeout.js";
22
+ import { isEqual } from "./isEqual.js";
23
+ import { isIos } from "./isIos.js";
24
+ import { isStandaloneMode } from "./isStandaloneMode.js";
25
+ import { kebabCase } from "./kebabCase.js";
26
+ import { pascalCase } from "./pascalCase.js";
27
+ import { snakeCase } from "./snakeCase.js";
28
+ import { normalizeString } from "./normalizeString.js";
29
+ import { addViewportMaximumScale, preventIosInputZoom } from "./preventIosInputZoom.js";
30
+ import { ScriptLoader } from "./scriptLoader.js";
31
+ import { sleep } from "./sleep.js";
32
+ import { Swipe } from "./swipeHandler.js";
33
+ import { TextareaAutogrow } from "./TextareaAutogrow.js";
34
+ import { throttle } from "./throttle.js";
35
+ import { throttleId } from "./throttleId.js";
36
+ import { upperFirst } from "./upperFirst.js";
37
+ import { UserVisibility } from "./userVisibility.js";
38
+ export { IdleTimeout, ScriptLoader, Swipe, TextareaAutogrow, UserVisibility, addViewportMaximumScale, camelCase, capitalize, checkAvailability, countryCodeToUnicodeFlag, debounce, debounceCallback, debounceId, deleteCookie, fetchLocaleIp, formatCurrency, formatDate, formatJson, formatNumber, formatPhoneNumber, getBrowserLocale, getCookie, getCountryFlagUrl, getErrorMessage, isClient, isEqual, isIos, isServer, isStandaloneMode, kebabCase, normalizeString, pascalCase, preventIosInputZoom, setCookie, sleep, snakeCase, throttle, throttleId, truthyFilter, upperFirst };
@@ -1 +1,6 @@
1
- function isClient(){return typeof document<`u`}export{isClient};
1
+ //#region src/helpers/isClient.ts
2
+ function isClient() {
3
+ return typeof document < "u";
4
+ }
5
+ //#endregion
6
+ export { isClient };
@@ -1 +1,21 @@
1
- function isPrimitive(value){return value==null||typeof value==`string`||typeof value==`number`||typeof value==`boolean`||typeof value==`symbol`||typeof value==`bigint`}function isEqualArrays(a,b){if(a.length!==b.length)return!1;for(let[i,element]of a.entries())if(!isEqual(element,b[i]))return!1;return!0}function isEqualObjects(a,b){let keysA=Object.keys(a);let keysB=Object.keys(b);if(keysA.length!==keysB.length)return!1;for(let key of keysA)if(!keysB.includes(key)||!isEqual(a[key],b[key]))return!1;return!0}function isEqual(a,b){return isPrimitive(a)||isPrimitive(b)?a===b:a instanceof Date&&b instanceof Date?a.getTime()===b.getTime():typeof a!=typeof b||Array.isArray(a)!==Array.isArray(b)?!1:Array.isArray(a)&&Array.isArray(b)?isEqualArrays(a,b):typeof a==`object`&&typeof b==`object`?isEqualObjects(a,b):!1}export{isEqual};
1
+ //#region src/helpers/isEqual.ts
2
+ function isPrimitive(value) {
3
+ return value == null || typeof value == "string" || typeof value == "number" || typeof value == "boolean" || typeof value == "symbol" || typeof value == "bigint";
4
+ }
5
+ function isEqualArrays(a, b) {
6
+ if (a.length !== b.length) return !1;
7
+ for (let [i, element] of a.entries()) if (!isEqual(element, b[i])) return !1;
8
+ return !0;
9
+ }
10
+ function isEqualObjects(a, b) {
11
+ let keysA = Object.keys(a);
12
+ let keysB = Object.keys(b);
13
+ if (keysA.length !== keysB.length) return !1;
14
+ for (let key of keysA) if (!keysB.includes(key) || !isEqual(a[key], b[key])) return !1;
15
+ return !0;
16
+ }
17
+ function isEqual(a, b) {
18
+ return isPrimitive(a) || isPrimitive(b) ? a === b : a instanceof Date && b instanceof Date ? a.getTime() === b.getTime() : typeof a != typeof b || Array.isArray(a) !== Array.isArray(b) ? !1 : Array.isArray(a) && Array.isArray(b) ? isEqualArrays(a, b) : typeof a == "object" && typeof b == "object" && isEqualObjects(a, b);
19
+ }
20
+ //#endregion
21
+ export { isEqual };
@@ -0,0 +1 @@
1
+ export declare function isIos(): boolean;
@@ -0,0 +1,9 @@
1
+ import { isClient } from "./isClient.js";
2
+ //#region src/helpers/isIos.ts
3
+ function isIos() {
4
+ if (!isClient()) return !1;
5
+ let userAgent = navigator.userAgent;
6
+ return /iPhone|iPad|iPod/.test(userAgent) || /Macintosh/.test(userAgent) && navigator.maxTouchPoints > 1;
7
+ }
8
+ //#endregion
9
+ export { isIos };
@@ -1 +1,6 @@
1
- function isServer(){return typeof document>`u`||globalThis.window===void 0}export{isServer};
1
+ //#region src/helpers/isServer.ts
2
+ function isServer() {
3
+ return typeof document > "u" || globalThis.window === void 0;
4
+ }
5
+ //#endregion
6
+ export { isServer };
@@ -1 +1,10 @@
1
- import{isClient}from"./isClient.js";function isStandaloneMode(){if(!isClient())return!1;let nav=navigator;let isStandalone=globalThis.matchMedia(`(display-mode: standalone)`).matches;return nav.standalone||isStandalone}export{isStandaloneMode};
1
+ import { isClient } from "./isClient.js";
2
+ //#region src/helpers/isStandaloneMode.ts
3
+ function isStandaloneMode() {
4
+ if (!isClient()) return !1;
5
+ let nav = navigator;
6
+ let isStandalone = globalThis.matchMedia("(display-mode: standalone)").matches;
7
+ return nav.standalone || isStandalone;
8
+ }
9
+ //#endregion
10
+ export { isStandaloneMode };
@@ -1 +1,6 @@
1
- function kebabCase(str){return str.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/([A-Z])([A-Z][a-z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase().replace(/-+/g,`-`).replace(/(^-)|(-$)/g,``)}export{kebabCase};
1
+ //#region src/helpers/kebabCase.ts
2
+ function kebabCase(str) {
3
+ return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/([A-Z])([A-Z][a-z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase().replace(/-+/g, "-").replace(/(^-)|(-$)/g, "");
4
+ }
5
+ //#endregion
6
+ export { kebabCase };
@@ -1 +1,87 @@
1
- import{camelCase}from"./camelCase.js";import{kebabCase}from"./kebabCase.js";import{pascalCase}from"./pascalCase.js";import{snakeCase}from"./snakeCase.js";var defaultOptions={removeAccents:!0,caseSensitive:!1,replaceSpaces:!0,removeSpecialCharacters:!1,trim:!0,normalizeSpaces:!0,removeNumbers:!1,case:void 0,customNormalizationForms:[`NFC`,`NFKD`]};function applyCaseTransform(str,caseFormat){switch(caseFormat){case`kebab-case`:return kebabCase(str);case`camelCase`:return camelCase(str);case`PascalCase`:return pascalCase(str);case`snake_case`:return snakeCase(str);case`lowercase`:return str.toLowerCase();case`UPPERCASE`:return str.toUpperCase();default:return str}}function normalizeString(input,options){let finalOptions={...defaultOptions,...options};let accentsMap={À:`A`,Á:`A`,Â:`A`,Ã:`A`,Ä:`A`,Å:`A`,à:`a`,á:`a`,â:`a`,ã:`a`,ä:`a`,å:`a`,È:`E`,É:`E`,Ê:`E`,Ë:`E`,è:`e`,é:`e`,ê:`e`,ë:`e`,Î:`I`,Ï:`I`,í:`I`,î:`i`,ï:`i`,Ô:`O`,Õ:`O`,Ö:`O`,Ø:`O`,ô:`o`,õ:`o`,ö:`o`,ø:`o`,Ù:`U`,Ú:`U`,Û:`U`,Ü:`U`,ù:`u`,ú:`u`,û:`u`,ü:`u`,Ç:`C`,ç:`c`,ÿ:`y`,Ñ:`N`,ñ:`n`,ó:`o`};let result=input.toString();if(finalOptions.trim&&(result=result.trim()),finalOptions.normalizeSpaces&&(result=result.replaceAll(/\s+/g,` `)),finalOptions.replaceSpaces&&(result=result.replaceAll(` `,`-`)),finalOptions.removeNumbers&&(result=result.replaceAll(/\d/g,``)),finalOptions.removeAccents&&(result=result.replaceAll(/[ÀÁÂÃÄÅÇÈÉÊËÎÏÑÔÕÖØÙÚÛÜàáâãäåçèéêëíîïñóôõöøùúûüÿ]/g,char=>accentsMap[char]||char),result=result.replaceAll(/[\u0300-\u036F]/g,``)),finalOptions.case?result=applyCaseTransform(result,finalOptions.case):finalOptions.caseSensitive===!1&&(result=result.toLowerCase()),finalOptions.removeSpecialCharacters&&(result=result.replaceAll(/[^\dA-Z-]/gi,``)),finalOptions.trim&&(result=result.trim()),finalOptions.customNormalizationForms)for(let form of finalOptions.customNormalizationForms)result=result.normalize(form);return result}export{normalizeString};
1
+ import { camelCase } from "./camelCase.js";
2
+ import { kebabCase } from "./kebabCase.js";
3
+ import { pascalCase } from "./pascalCase.js";
4
+ import { snakeCase } from "./snakeCase.js";
5
+ //#region src/helpers/normalizeString.ts
6
+ var defaultOptions = {
7
+ removeAccents: !0,
8
+ caseSensitive: !1,
9
+ replaceSpaces: !0,
10
+ removeSpecialCharacters: !1,
11
+ trim: !0,
12
+ normalizeSpaces: !0,
13
+ removeNumbers: !1,
14
+ case: void 0,
15
+ customNormalizationForms: ["NFC", "NFKD"]
16
+ };
17
+ function applyCaseTransform(str, caseFormat) {
18
+ switch (caseFormat) {
19
+ case "kebab-case": return kebabCase(str);
20
+ case "camelCase": return camelCase(str);
21
+ case "PascalCase": return pascalCase(str);
22
+ case "snake_case": return snakeCase(str);
23
+ case "lowercase": return str.toLowerCase();
24
+ case "UPPERCASE": return str.toUpperCase();
25
+ default: return str;
26
+ }
27
+ }
28
+ function normalizeString(input, options) {
29
+ let finalOptions = {
30
+ ...defaultOptions,
31
+ ...options
32
+ };
33
+ let accentsMap = {
34
+ À: "A",
35
+ Á: "A",
36
+ Â: "A",
37
+ Ã: "A",
38
+ Ä: "A",
39
+ Å: "A",
40
+ à: "a",
41
+ á: "a",
42
+ â: "a",
43
+ ã: "a",
44
+ ä: "a",
45
+ å: "a",
46
+ È: "E",
47
+ É: "E",
48
+ Ê: "E",
49
+ Ë: "E",
50
+ è: "e",
51
+ é: "e",
52
+ ê: "e",
53
+ ë: "e",
54
+ Î: "I",
55
+ Ï: "I",
56
+ í: "I",
57
+ î: "i",
58
+ ï: "i",
59
+ Ô: "O",
60
+ Õ: "O",
61
+ Ö: "O",
62
+ Ø: "O",
63
+ ô: "o",
64
+ õ: "o",
65
+ ö: "o",
66
+ ø: "o",
67
+ Ù: "U",
68
+ Ú: "U",
69
+ Û: "U",
70
+ Ü: "U",
71
+ ù: "u",
72
+ ú: "u",
73
+ û: "u",
74
+ ü: "u",
75
+ Ç: "C",
76
+ ç: "c",
77
+ ÿ: "y",
78
+ Ñ: "N",
79
+ ñ: "n",
80
+ ó: "o"
81
+ };
82
+ let result = input.toString();
83
+ if (finalOptions.trim && (result = result.trim()), finalOptions.normalizeSpaces && (result = result.replaceAll(/\s+/g, " ")), finalOptions.replaceSpaces && (result = result.replaceAll(" ", "-")), finalOptions.removeNumbers && (result = result.replaceAll(/\d/g, "")), finalOptions.removeAccents && (result = result.replaceAll(/[ÀÁÂÃÄÅÇÈÉÊËÎÏÑÔÕÖØÙÚÛÜàáâãäåçèéêëíîïñóôõöøùúûüÿ]/g, (char) => accentsMap[char] || char), result = result.replaceAll(/[\u0300-\u036F]/g, "")), finalOptions.case ? result = applyCaseTransform(result, finalOptions.case) : finalOptions.caseSensitive === !1 && (result = result.toLowerCase()), finalOptions.removeSpecialCharacters && (result = result.replaceAll(/[^\dA-Z-]/gi, "")), finalOptions.trim && (result = result.trim()), finalOptions.customNormalizationForms) for (let form of finalOptions.customNormalizationForms) result = result.normalize(form);
84
+ return result;
85
+ }
86
+ //#endregion
87
+ export { normalizeString };
@@ -1 +1,13 @@
1
- import{camelCase}from"./camelCase.js";import{capitalize}from"./capitalize.js";function pascalCase(str){if(str===str.toUpperCase()){if(str.includes(`-`))return str.toLowerCase().split(`-`).map(capitalize).join(``);if(str.includes(`_`))return str.toLowerCase().split(`_`).map(capitalize).join(``);if(str.includes(` `))return str.toLowerCase().split(` `).map(capitalize).join(``)}return str.includes(`-`)?str.toLowerCase().split(`-`).map(capitalize).join(``):str.includes(`_`)?str.toLowerCase().split(`_`).map(capitalize).join(``):str.includes(` `)?str.toLowerCase().split(` `).map(capitalize).join(``):capitalize(camelCase(str))}export{pascalCase};
1
+ import { camelCase } from "./camelCase.js";
2
+ import { capitalize } from "./capitalize.js";
3
+ //#region src/helpers/pascalCase.ts
4
+ function pascalCase(str) {
5
+ if (str === str.toUpperCase()) {
6
+ if (str.includes("-")) return str.toLowerCase().split("-").map(capitalize).join("");
7
+ if (str.includes("_")) return str.toLowerCase().split("_").map(capitalize).join("");
8
+ if (str.includes(" ")) return str.toLowerCase().split(" ").map(capitalize).join("");
9
+ }
10
+ return str.includes("-") ? str.toLowerCase().split("-").map(capitalize).join("") : str.includes("_") ? str.toLowerCase().split("_").map(capitalize).join("") : str.includes(" ") ? str.toLowerCase().split(" ").map(capitalize).join("") : capitalize(camelCase(str));
11
+ }
12
+ //#endregion
13
+ export { pascalCase };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Returns the viewport content with `maximum-scale=1`, replacing an existing `maximum-scale`.
3
+ */
4
+ export declare function addViewportMaximumScale(content: string): string;
5
+ /**
6
+ * Stops iOS from zooming the page when a form field with a font size below 16px gets the focus.
7
+ * Only applied on iOS, which still lets the user pinch to zoom: Android, which does not zoom
8
+ * on focus but would lose the pinch zoom, is left untouched.
9
+ * Does nothing when the page has no `<meta name="viewport">`.
10
+ * @returns A function restoring the original viewport
11
+ */
12
+ export declare function preventIosInputZoom(): () => void;
@@ -0,0 +1,15 @@
1
+ import { isIos } from "./isIos.js";
2
+ //#region src/helpers/preventIosInputZoom.ts
3
+ var MAXIMUM_SCALE_REGEX = /maximum-scale\s*=\s*[\d.]+/i;
4
+ function addViewportMaximumScale(content) {
5
+ return MAXIMUM_SCALE_REGEX.test(content) ? content.replace(MAXIMUM_SCALE_REGEX, "maximum-scale=1") : content.trim() ? `${content}, maximum-scale=1` : "maximum-scale=1";
6
+ }
7
+ function preventIosInputZoom() {
8
+ if (!isIos()) return () => {};
9
+ let meta = document.querySelector("meta[name=\"viewport\"]");
10
+ if (!meta) return () => {};
11
+ let originalContent = meta.getAttribute("content") ?? "";
12
+ return meta.setAttribute("content", addViewportMaximumScale(originalContent)), () => meta.setAttribute("content", originalContent);
13
+ }
14
+ //#endregion
15
+ export { addViewportMaximumScale, preventIosInputZoom };
@@ -1 +1,38 @@
1
- var ScriptLoader=class{src;script;once;async;defer;identifier;constructor({src,identifier,once=!0,async=!0,defer=!0}){if(globalThis.window===void 0)throw TypeError(`[ScriptLoader]: Is supported only on browser side`);if(!src)throw Error(`[ScriptLoader]: You should provide the attribut "src"`);if(!identifier)throw Error(`[ScriptLoader]: You should provide the attribut "identifier"`);this.src=src,this.identifier=identifier,this.once=once,this.async=async,this.defer=defer}removeTag(tag){typeof tag==`string`?document.head.querySelector(`[data-identifier="${tag}"]`)?.remove():tag.remove()}load(){let windowInstance=globalThis;let scriptTags=document.head.querySelectorAll(`[data-identifier="${this.identifier}"]`);if(this.once&&windowInstance[this.identifier]&&scriptTags.length>0)return this.script=windowInstance[this.identifier],Promise.resolve(this.script);if(!this.once&&scriptTags.length>0)for(let tag of scriptTags)this.removeTag(tag);return this.injectScript()}injectScript(){let windowInstance=globalThis;return new Promise((resolve,reject)=>{try{let script=document.createElement(`script`);script.src=this.src,script.async=this.async,script.defer=this.defer,script.dataset.identifier=this.identifier,script.addEventListener(`error`,error=>reject(Error(`[ScriptLoader](injectScript) ${error.message}`))),script.addEventListener(`load`,success=>(this.script=success,windowInstance[this.identifier]=success,resolve(success))),document.head.append(script)}catch(error){throw Error(`[ScriptLoader](init) ${error}`,{cause:error})}})}};export{ScriptLoader};
1
+ //#region src/helpers/scriptLoader.ts
2
+ var ScriptLoader = class {
3
+ src;
4
+ script;
5
+ once;
6
+ async;
7
+ defer;
8
+ identifier;
9
+ constructor({ src, identifier, once = !0, async = !0, defer = !0 }) {
10
+ if (globalThis.window === void 0) throw TypeError("[ScriptLoader]: Is supported only on browser side");
11
+ if (!src) throw Error("[ScriptLoader]: You should provide the attribut \"src\"");
12
+ if (!identifier) throw Error("[ScriptLoader]: You should provide the attribut \"identifier\"");
13
+ this.src = src, this.identifier = identifier, this.once = once, this.async = async, this.defer = defer;
14
+ }
15
+ removeTag(tag) {
16
+ typeof tag == "string" ? document.head.querySelector(`[data-identifier="${tag}"]`)?.remove() : tag.remove();
17
+ }
18
+ load() {
19
+ let windowInstance = globalThis;
20
+ let scriptTags = document.head.querySelectorAll(`[data-identifier="${this.identifier}"]`);
21
+ if (this.once && windowInstance[this.identifier] && scriptTags.length > 0) return this.script = windowInstance[this.identifier], Promise.resolve(this.script);
22
+ if (!this.once && scriptTags.length > 0) for (let tag of scriptTags) this.removeTag(tag);
23
+ return this.injectScript();
24
+ }
25
+ injectScript() {
26
+ let windowInstance = globalThis;
27
+ return new Promise((resolve, reject) => {
28
+ try {
29
+ let script = document.createElement("script");
30
+ script.src = this.src, script.async = this.async, script.defer = this.defer, script.dataset.identifier = this.identifier, script.addEventListener("error", (error) => reject(/* @__PURE__ */ Error(`[ScriptLoader](injectScript) ${error.message}`))), script.addEventListener("load", (success) => (this.script = success, windowInstance[this.identifier] = success, resolve(success))), document.head.append(script);
31
+ } catch (error) {
32
+ throw Error(`[ScriptLoader](init) ${error}`, { cause: error });
33
+ }
34
+ });
35
+ }
36
+ };
37
+ //#endregion
38
+ export { ScriptLoader };
@@ -1 +1,6 @@
1
- function sleep(duration){return new Promise(resolve=>setTimeout(resolve,duration))}export{sleep};
1
+ //#region src/helpers/sleep.ts
2
+ function sleep(duration) {
3
+ return new Promise((resolve) => setTimeout(resolve, duration));
4
+ }
5
+ //#endregion
6
+ export { sleep };
@@ -1 +1,6 @@
1
- function snakeCase(str){return str.replace(/([a-z])([A-Z])/g,`$1_$2`).replace(/([A-Z])([A-Z][a-z])/g,`$1_$2`).replace(/[\s-]+/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/(^_)|(_$)/g,``)}export{snakeCase};
1
+ //#region src/helpers/snakeCase.ts
2
+ function snakeCase(str) {
3
+ return str.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").replace(/[\s-]+/g, "_").toLowerCase().replace(/_+/g, "_").replace(/(^_)|(_$)/g, "");
4
+ }
5
+ //#endregion
6
+ export { snakeCase };
@@ -6,7 +6,7 @@ export interface SwipeValues {
6
6
  xDiff: number | undefined;
7
7
  yDiff: number | undefined;
8
8
  }
9
- export type SwipeEventCallback = (event: TouchEvent) => void;
9
+ export type SwipeEventCallback = (event: PointerEvent) => void;
10
10
  export type SwipeValuesCallback = (values: SwipeValues) => void;
11
11
  /**
12
12
  * Options for handling swipe events.
@@ -48,28 +48,34 @@ export interface SwipeOptions {
48
48
  */
49
49
  threshold?: number;
50
50
  /**
51
- * Whether to prevent the default behavior of touchmove event.
51
+ * Whether to prevent the default behavior of the pointer move event (the move listener
52
+ * becomes non-passive when enabled).
52
53
  * @default false
53
54
  */
54
- preventDefaultOnTouchMove?: boolean;
55
+ preventDefaultOnMove?: boolean;
55
56
  /**
56
57
  * Whether to prevent the default behavior of mousewheel event.
57
58
  * @default false
58
59
  */
59
60
  preventDefaultOnMouseWheel?: boolean;
60
61
  /**
61
- * Whether to trigger the swipe event immediately on touchstart/mousedown.
62
+ * Pointer types that can trigger the swipe.
63
+ * @default ['mouse', 'touch', 'pen']
64
+ */
65
+ pointerTypes?: ('mouse' | 'touch' | 'pen')[];
66
+ /**
67
+ * Whether to start listening immediately on instantiation.
62
68
  * @default false
63
69
  */
64
70
  immediate?: boolean;
65
71
  /**
66
- * Whether to trigger the swipe event on touchend/mouseup.
67
- * If set to true, the swipe event will be triggered only when the user lifts their finger/mouse.
72
+ * Whether to trigger the swipe event on pointer up.
73
+ * If set to true, the swipe event will be triggered only when the user lifts their finger/pointer.
68
74
  * @default false
69
75
  */
70
76
  triggerOnEnd?: boolean;
71
77
  }
72
- type DefaultSwipeOptions = Required<Pick<SwipeOptions, 'preventDefaultOnTouchMove' | 'preventDefaultOnMouseWheel' | 'threshold' | 'immediate' | 'triggerOnEnd'>>;
78
+ type DefaultSwipeOptions = Required<Pick<SwipeOptions, 'preventDefaultOnMove' | 'preventDefaultOnMouseWheel' | 'threshold' | 'immediate' | 'triggerOnEnd'>>;
73
79
  type SwipeOptionsWithDefaults = SwipeOptions & DefaultSwipeOptions;
74
80
  export declare class Swipe {
75
81
  readonly inputOption: SwipeOptions;
@@ -80,9 +86,10 @@ export declare class Swipe {
80
86
  yEnd: number | undefined;
81
87
  xDiff: number | undefined;
82
88
  yDiff: number | undefined;
83
- private readonly onToucheStartCallback;
84
- private readonly onToucheMoveCallback;
85
- private readonly onToucheEndCallback;
89
+ private pointerDown;
90
+ private readonly onPointerDownCallback;
91
+ private readonly onPointerMoveCallback;
92
+ private readonly onPointerUpCallback;
86
93
  private readonly onMouseWheelCallback;
87
94
  readonly start: (element?: typeof this.options.element) => void;
88
95
  readonly stop: () => void;
@@ -91,11 +98,12 @@ export declare class Swipe {
91
98
  private startListening;
92
99
  private stopListening;
93
100
  private setElement;
101
+ private isPointerAllowed;
94
102
  private handleMouseWheel;
95
- private toucheStartHandler;
103
+ private handlePointerDown;
96
104
  private emitValuesChanged;
97
- private handleTouchMove;
98
- private handleTouchEnd;
105
+ private handlePointerMove;
106
+ private handlePointerUp;
99
107
  private runCallbacks;
100
108
  private resetValues;
101
109
  }
@@ -1 +1,83 @@
1
- var defaultOptions={preventDefaultOnTouchMove:!1,preventDefaultOnMouseWheel:!1,threshold:50,immediate:!1,triggerOnEnd:!1};var Swipe=class{element;xStart;yStart;xEnd;yEnd;xDiff;yDiff;onToucheStartCallback;onToucheMoveCallback;onToucheEndCallback;onMouseWheelCallback;start;stop;options;constructor(inputOption){this.inputOption=inputOption,this.options={...defaultOptions,...inputOption},this.onToucheStartCallback=this.toucheStartHandler.bind(this),this.onToucheMoveCallback=this.handleTouchMove.bind(this),this.onToucheEndCallback=this.handleTouchEnd.bind(this),this.onMouseWheelCallback=this.handleMouseWheel.bind(this),this.start=this.startListening.bind(this),this.stop=this.stopListening.bind(this),this.options.element&&this.setElement(this.options.element),this.options.immediate&&this.start()}startListening(){this.setElement(this.options.element),this.element?.addEventListener(`touchstart`,this.onToucheStartCallback,{passive:!0}),this.element?.addEventListener(`touchmove`,this.onToucheMoveCallback,{passive:!0}),this.options.triggerOnEnd&&this.element?.addEventListener(`touchend`,this.onToucheEndCallback,{passive:!0}),this.options.preventDefaultOnMouseWheel&&this.element?.addEventListener(`mousewheel`,this.onMouseWheelCallback,{passive:!1})}stopListening(){this.element?.removeEventListener(`touchstart`,this.onToucheStartCallback),this.element?.removeEventListener(`touchmove`,this.onToucheMoveCallback),this.element?.removeEventListener(`touchend`,this.onToucheEndCallback),this.options.preventDefaultOnMouseWheel&&this.element?.removeEventListener(`mousewheel`,this.onMouseWheelCallback)}setElement(element){if(!element){console.error(`[maz-ui][SwipeHandler](setElement) Element should be provided. Its can be a string selector or an HTMLElement`);return}if(typeof element==`string`){let foundElement=document.querySelector(element);if(!(foundElement instanceof HTMLElement)){console.error(`[maz-ui][SwipeHandler](setElement) String selector for element is not found`);return}this.element=foundElement}else this.element=element}handleMouseWheel(event){event.preventDefault()}toucheStartHandler(event){this.xStart=event.touches[0].clientX,this.yStart=event.touches[0].clientY,this.emitValuesChanged()}emitValuesChanged(){this.options.onValuesChanged?.({xStart:this.xStart,yStart:this.yStart,xEnd:this.xEnd,yEnd:this.yEnd,xDiff:this.xDiff,yDiff:this.yDiff})}handleTouchMove(event){this.options.preventDefaultOnTouchMove&&event.cancelable&&event.preventDefault(),this.xEnd=event.touches[0].clientX,this.yEnd=event.touches[0].clientY,!(!this.xStart||!this.yStart)&&(this.xDiff=this.xStart-this.xEnd,this.yDiff=this.yStart-this.yEnd,this.emitValuesChanged(),this.options.triggerOnEnd||this.runCallbacks(event))}handleTouchEnd(event){this.runCallbacks(event),this.emitValuesChanged()}runCallbacks(event){typeof this.xDiff!=`number`||typeof this.yDiff!=`number`||Math.abs(this.xDiff)<this.options.threshold&&Math.abs(this.yDiff)<this.options.threshold||(Math.abs(this.xDiff)>Math.abs(this.yDiff)?this.xDiff>0?this.options.onLeft?.(event):this.options.onRight?.(event):this.yDiff>0?this.options.onUp?.(event):this.options.onDown?.(event),this.resetValues())}resetValues(){this.xStart=void 0,this.yStart=void 0,this.xEnd=void 0,this.yEnd=void 0,this.xDiff=void 0,this.yDiff=void 0,this.emitValuesChanged()}};export{Swipe};
1
+ //#region src/helpers/swipeHandler.ts
2
+ var defaultOptions = {
3
+ preventDefaultOnMove: !1,
4
+ preventDefaultOnMouseWheel: !1,
5
+ threshold: 50,
6
+ immediate: !1,
7
+ triggerOnEnd: !1
8
+ };
9
+ var Swipe = class {
10
+ inputOption;
11
+ element;
12
+ xStart;
13
+ yStart;
14
+ xEnd;
15
+ yEnd;
16
+ xDiff;
17
+ yDiff;
18
+ pointerDown = !1;
19
+ onPointerDownCallback;
20
+ onPointerMoveCallback;
21
+ onPointerUpCallback;
22
+ onMouseWheelCallback;
23
+ start;
24
+ stop;
25
+ options;
26
+ constructor(inputOption) {
27
+ this.inputOption = inputOption, this.options = {
28
+ ...defaultOptions,
29
+ ...inputOption
30
+ }, this.onPointerDownCallback = this.handlePointerDown.bind(this), this.onPointerMoveCallback = this.handlePointerMove.bind(this), this.onPointerUpCallback = this.handlePointerUp.bind(this), this.onMouseWheelCallback = this.handleMouseWheel.bind(this), this.start = this.startListening.bind(this), this.stop = this.stopListening.bind(this), this.options.element && this.setElement(this.options.element), this.options.immediate && this.start();
31
+ }
32
+ startListening() {
33
+ this.setElement(this.options.element), this.element?.addEventListener("pointerdown", this.onPointerDownCallback, { passive: !0 }), this.element?.addEventListener("pointermove", this.onPointerMoveCallback, { passive: !this.options.preventDefaultOnMove }), this.element?.addEventListener("pointerup", this.onPointerUpCallback, { passive: !0 }), this.element?.addEventListener("pointercancel", this.onPointerUpCallback, { passive: !0 }), this.options.preventDefaultOnMouseWheel && this.element?.addEventListener("mousewheel", this.onMouseWheelCallback, { passive: !1 });
34
+ }
35
+ stopListening() {
36
+ this.element?.removeEventListener("pointerdown", this.onPointerDownCallback), this.element?.removeEventListener("pointermove", this.onPointerMoveCallback), this.element?.removeEventListener("pointerup", this.onPointerUpCallback), this.element?.removeEventListener("pointercancel", this.onPointerUpCallback), this.options.preventDefaultOnMouseWheel && this.element?.removeEventListener("mousewheel", this.onMouseWheelCallback);
37
+ }
38
+ setElement(element) {
39
+ if (!element) console.error("[maz-ui][SwipeHandler](setElement) Element should be provided. Its can be a string selector or an HTMLElement");
40
+ else if (typeof element == "string") {
41
+ let foundElement = document.querySelector(element);
42
+ if (!(foundElement instanceof HTMLElement)) {
43
+ console.error("[maz-ui][SwipeHandler](setElement) String selector for element is not found");
44
+ return;
45
+ }
46
+ this.element = foundElement;
47
+ } else this.element = element;
48
+ }
49
+ isPointerAllowed(event) {
50
+ let type = event.pointerType;
51
+ return !this.options.pointerTypes || !type || this.options.pointerTypes.includes(type);
52
+ }
53
+ handleMouseWheel(event) {
54
+ event.preventDefault();
55
+ }
56
+ handlePointerDown(event) {
57
+ this.isPointerAllowed(event) && (this.pointerDown = !0, this.xStart = event.clientX, this.yStart = event.clientY, this.emitValuesChanged());
58
+ }
59
+ emitValuesChanged() {
60
+ this.options.onValuesChanged?.({
61
+ xStart: this.xStart,
62
+ yStart: this.yStart,
63
+ xEnd: this.xEnd,
64
+ yEnd: this.yEnd,
65
+ xDiff: this.xDiff,
66
+ yDiff: this.yDiff
67
+ });
68
+ }
69
+ handlePointerMove(event) {
70
+ this.pointerDown && (this.options.preventDefaultOnMove && event.cancelable && event.preventDefault(), this.xEnd = event.clientX, this.yEnd = event.clientY, this.xStart !== void 0 && this.yStart !== void 0 && (this.xDiff = this.xStart - this.xEnd, this.yDiff = this.yStart - this.yEnd, this.emitValuesChanged(), this.options.triggerOnEnd || this.runCallbacks(event)));
71
+ }
72
+ handlePointerUp(event) {
73
+ this.options.triggerOnEnd && (this.runCallbacks(event), this.emitValuesChanged()), this.pointerDown = !1;
74
+ }
75
+ runCallbacks(event) {
76
+ typeof this.xDiff == "number" && typeof this.yDiff == "number" && (Math.abs(this.xDiff) < this.options.threshold && Math.abs(this.yDiff) < this.options.threshold || (Math.abs(this.xDiff) > Math.abs(this.yDiff) ? this.xDiff > 0 ? this.options.onLeft?.(event) : this.options.onRight?.(event) : this.yDiff > 0 ? this.options.onUp?.(event) : this.options.onDown?.(event), this.resetValues()));
77
+ }
78
+ resetValues() {
79
+ this.xStart = void 0, this.yStart = void 0, this.xEnd = void 0, this.yEnd = void 0, this.xDiff = void 0, this.yDiff = void 0, this.emitValuesChanged();
80
+ }
81
+ };
82
+ //#endregion
83
+ export { Swipe };
@@ -1 +1,13 @@
1
- function throttle(func,limit){let inThrottle=!1;let lastFunc;let lastRan;return function(...args){inThrottle?(clearTimeout(lastFunc),lastFunc=setTimeout(()=>{Date.now()-lastRan>=limit&&(func.apply(this,args),lastRan=Date.now())},Math.max(limit-(Date.now()-lastRan),0))):(func.apply(this,args),lastRan=Date.now(),inThrottle=!0)}}export{throttle};
1
+ //#region src/helpers/throttle.ts
2
+ function throttle(func, limit) {
3
+ let inThrottle = !1;
4
+ let lastFunc;
5
+ let lastRan;
6
+ return function(...args) {
7
+ inThrottle ? (clearTimeout(lastFunc), lastFunc = setTimeout(() => {
8
+ Date.now() - lastRan >= limit && (func.apply(this, args), lastRan = Date.now());
9
+ }, Math.max(limit - (Date.now() - lastRan), 0))) : (func.apply(this, args), lastRan = Date.now(), inThrottle = !0);
10
+ };
11
+ }
12
+ //#endregion
13
+ export { throttle };
@@ -1 +1,20 @@
1
- function throttleId(identifier,func,interval){let state={};return async(...args)=>{let now=Date.now();return state[identifier]||(state[identifier]={promise:null,lastCall:0,lastArgs:[]}),now-state[identifier].lastCall>=interval?(state[identifier].lastCall=now,func(...args)):(state[identifier].lastArgs=args,state[identifier].promise||(state[identifier].promise=new Promise(resolve=>{setTimeout(async()=>{state[identifier].lastCall=Date.now();let result=await func(...state[identifier].lastArgs);state[identifier].promise=null,resolve(result)},interval-(now-state[identifier].lastCall))})),state[identifier].promise)}}export{throttleId};
1
+ //#region src/helpers/throttleId.ts
2
+ function throttleId(identifier, func, interval) {
3
+ let state = {};
4
+ return async (...args) => {
5
+ let now = Date.now();
6
+ return state[identifier] || (state[identifier] = {
7
+ promise: null,
8
+ lastCall: 0,
9
+ lastArgs: []
10
+ }), now - state[identifier].lastCall >= interval ? (state[identifier].lastCall = now, func(...args)) : (state[identifier].lastArgs = args, state[identifier].promise || (state[identifier].promise = new Promise((resolve) => {
11
+ setTimeout(async () => {
12
+ state[identifier].lastCall = Date.now();
13
+ let result = await func(...state[identifier].lastArgs);
14
+ state[identifier].promise = null, resolve(result);
15
+ }, interval - (now - state[identifier].lastCall));
16
+ })), state[identifier].promise);
17
+ };
18
+ }
19
+ //#endregion
20
+ export { throttleId };
@@ -1 +1,6 @@
1
- function truthyFilter(value){return!!value}export{truthyFilter};
1
+ //#region src/helpers/truthyFilter.ts
2
+ function truthyFilter(value) {
3
+ return !!value;
4
+ }
5
+ //#endregion
6
+ export { truthyFilter };
@@ -1 +1,6 @@
1
- function upperFirst(value){return value.charAt(0).toUpperCase()+value.slice(1)}export{upperFirst};
1
+ //#region src/helpers/upperFirst.ts
2
+ function upperFirst(value) {
3
+ return value.charAt(0).toUpperCase() + value.slice(1);
4
+ }
5
+ //#endregion
6
+ export { upperFirst };
@@ -1 +1,47 @@
1
- import{isClient}from"./isClient.js";var UserVisibility=class{eventHandlerFunction;event=`visibilitychange`;timeoutHandler;options;defaultOptions={timeout:5e3,once:!1,immediate:!0};isVisible=!1;constructor(callback,options){this.callback=callback,this.options={...this.defaultOptions,...options},this.eventHandlerFunction=this.eventHandler.bind(this),isClient()&&this.start()}start(){if(!isClient()){console.warn(`[UserVisibility](start) you should run this method on client side`);return}this.options.immediate&&this.emitCallback(),this.addEventListener()}emitCallback(){this.isVisible=document.visibilityState===`visible`,this.callback({isVisible:this.isVisible}),this.options.once&&this.destroy()}eventHandler(){document.visibilityState===`visible`&&!this.isVisible?(this.clearTimeout(),this.emitCallback()):document.visibilityState===`hidden`&&this.initTimeout()}clearTimeout(){this.timeoutHandler&&=(clearTimeout(this.timeoutHandler),void 0)}initTimeout(){this.clearTimeout(),this.timeoutHandler=setTimeout(this.emitCallback.bind(this),this.options.timeout)}addEventListener(){document.addEventListener(this.event,this.eventHandlerFunction)}removeEventListener(){document.removeEventListener(this.event,this.eventHandlerFunction)}destroy(){this.removeEventListener(),this.timeoutHandler&&clearTimeout(this.timeoutHandler)}};export{UserVisibility};
1
+ import { isClient } from "./isClient.js";
2
+ //#region src/helpers/userVisibility.ts
3
+ var UserVisibility = class {
4
+ callback;
5
+ eventHandlerFunction;
6
+ event = "visibilitychange";
7
+ timeoutHandler;
8
+ options;
9
+ defaultOptions = {
10
+ timeout: 5e3,
11
+ once: !1,
12
+ immediate: !0
13
+ };
14
+ isVisible = !1;
15
+ constructor(callback, options) {
16
+ this.callback = callback, this.options = {
17
+ ...this.defaultOptions,
18
+ ...options
19
+ }, this.eventHandlerFunction = this.eventHandler.bind(this), isClient() && this.start();
20
+ }
21
+ start() {
22
+ isClient() ? (this.options.immediate && this.emitCallback(), this.addEventListener()) : console.warn("[UserVisibility](start) you should run this method on client side");
23
+ }
24
+ emitCallback() {
25
+ this.isVisible = document.visibilityState === "visible", this.callback({ isVisible: this.isVisible }), this.options.once && this.destroy();
26
+ }
27
+ eventHandler() {
28
+ document.visibilityState === "visible" && !this.isVisible ? (this.clearTimeout(), this.emitCallback()) : document.visibilityState === "hidden" && this.initTimeout();
29
+ }
30
+ clearTimeout() {
31
+ this.timeoutHandler &&= (clearTimeout(this.timeoutHandler), void 0);
32
+ }
33
+ initTimeout() {
34
+ this.clearTimeout(), this.timeoutHandler = setTimeout(this.emitCallback.bind(this), this.options.timeout);
35
+ }
36
+ addEventListener() {
37
+ document.addEventListener(this.event, this.eventHandlerFunction);
38
+ }
39
+ removeEventListener() {
40
+ document.removeEventListener(this.event, this.eventHandlerFunction);
41
+ }
42
+ destroy() {
43
+ this.removeEventListener(), this.timeoutHandler && clearTimeout(this.timeoutHandler);
44
+ }
45
+ };
46
+ //#endregion
47
+ export { UserVisibility };
package/dist/index.js CHANGED
@@ -1 +1,39 @@
1
- import{camelCase}from"./helpers/camelCase.js";import{capitalize}from"./helpers/capitalize.js";import{checkAvailability}from"./helpers/checkAvailability.js";import{truthyFilter}from"./helpers/truthyFilter.js";import{countryCodeToUnicodeFlag}from"./helpers/countryCodeToUnicodeFlag.js";import{debounce}from"./helpers/debounce.js";import{debounceCallback}from"./helpers/debounceCallback.js";import{debounceId}from"./helpers/debounceId.js";import{formatCurrency}from"./helpers/formatCurrency.js";import{formatDate}from"./helpers/formatDate.js";import{formatJson}from"./helpers/formatJson.js";import{formatNumber}from"./helpers/formatNumber.js";import{getCountryFlagUrl}from"./helpers/getCountryFlagUrl.js";import{getErrorMessage}from"./helpers/getErrorMessage.js";import{isClient}from"./helpers/isClient.js";import{IdleTimeout}from"./helpers/idleTimeout.js";import{isEqual}from"./helpers/isEqual.js";import{isServer}from"./helpers/isServer.js";import{isStandaloneMode}from"./helpers/isStandaloneMode.js";import{kebabCase}from"./helpers/kebabCase.js";import{pascalCase}from"./helpers/pascalCase.js";import{snakeCase}from"./helpers/snakeCase.js";import{normalizeString}from"./helpers/normalizeString.js";import{ScriptLoader}from"./helpers/scriptLoader.js";import{sleep}from"./helpers/sleep.js";import{Swipe}from"./helpers/swipeHandler.js";import{TextareaAutogrow}from"./helpers/TextareaAutogrow.js";import{throttle}from"./helpers/throttle.js";import{throttleId}from"./helpers/throttleId.js";import{upperFirst}from"./helpers/upperFirst.js";import{UserVisibility}from"./helpers/userVisibility.js";import"./helpers/index.js";export{IdleTimeout,ScriptLoader,Swipe,TextareaAutogrow,UserVisibility,camelCase,capitalize,checkAvailability,countryCodeToUnicodeFlag,debounce,debounceCallback,debounceId,formatCurrency,formatDate,formatJson,formatNumber,getCountryFlagUrl,getErrorMessage,isClient,isEqual,isServer,isStandaloneMode,kebabCase,normalizeString,pascalCase,sleep,snakeCase,throttle,throttleId,truthyFilter,upperFirst};
1
+ import { camelCase } from "./helpers/camelCase.js";
2
+ import { capitalize } from "./helpers/capitalize.js";
3
+ import { checkAvailability } from "./helpers/checkAvailability.js";
4
+ import { isServer } from "./helpers/isServer.js";
5
+ import { deleteCookie, getCookie, setCookie } from "./helpers/cookie.js";
6
+ import { truthyFilter } from "./helpers/truthyFilter.js";
7
+ import { countryCodeToUnicodeFlag } from "./helpers/countryCodeToUnicodeFlag.js";
8
+ import { debounce } from "./helpers/debounce.js";
9
+ import { debounceCallback } from "./helpers/debounceCallback.js";
10
+ import { debounceId } from "./helpers/debounceId.js";
11
+ import { fetchLocaleIp } from "./helpers/fetchLocaleIp.js";
12
+ import { formatCurrency } from "./helpers/formatCurrency.js";
13
+ import { formatDate } from "./helpers/formatDate.js";
14
+ import { formatJson } from "./helpers/formatJson.js";
15
+ import { formatNumber } from "./helpers/formatNumber.js";
16
+ import { formatPhoneNumber } from "./helpers/formatPhoneNumber.js";
17
+ import { getBrowserLocale } from "./helpers/getBrowserLocale.js";
18
+ import { getCountryFlagUrl } from "./helpers/getCountryFlagUrl.js";
19
+ import { getErrorMessage } from "./helpers/getErrorMessage.js";
20
+ import { isClient } from "./helpers/isClient.js";
21
+ import { IdleTimeout } from "./helpers/idleTimeout.js";
22
+ import { isEqual } from "./helpers/isEqual.js";
23
+ import { isIos } from "./helpers/isIos.js";
24
+ import { isStandaloneMode } from "./helpers/isStandaloneMode.js";
25
+ import { kebabCase } from "./helpers/kebabCase.js";
26
+ import { pascalCase } from "./helpers/pascalCase.js";
27
+ import { snakeCase } from "./helpers/snakeCase.js";
28
+ import { normalizeString } from "./helpers/normalizeString.js";
29
+ import { addViewportMaximumScale, preventIosInputZoom } from "./helpers/preventIosInputZoom.js";
30
+ import { ScriptLoader } from "./helpers/scriptLoader.js";
31
+ import { sleep } from "./helpers/sleep.js";
32
+ import { Swipe } from "./helpers/swipeHandler.js";
33
+ import { TextareaAutogrow } from "./helpers/TextareaAutogrow.js";
34
+ import { throttle } from "./helpers/throttle.js";
35
+ import { throttleId } from "./helpers/throttleId.js";
36
+ import { upperFirst } from "./helpers/upperFirst.js";
37
+ import { UserVisibility } from "./helpers/userVisibility.js";
38
+ import "./helpers/index.js";
39
+ export { IdleTimeout, ScriptLoader, Swipe, TextareaAutogrow, UserVisibility, addViewportMaximumScale, camelCase, capitalize, checkAvailability, countryCodeToUnicodeFlag, debounce, debounceCallback, debounceId, deleteCookie, fetchLocaleIp, formatCurrency, formatDate, formatJson, formatNumber, formatPhoneNumber, getBrowserLocale, getCookie, getCountryFlagUrl, getErrorMessage, isClient, isEqual, isIos, isServer, isStandaloneMode, kebabCase, normalizeString, pascalCase, preventIosInputZoom, setCookie, sleep, snakeCase, throttle, throttleId, truthyFilter, upperFirst };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@maz-ui/utils",
3
3
  "type": "module",
4
- "version": "5.0.0-canary.ef64a02.0",
4
+ "version": "5.0.0",
5
5
  "description": "Utils of maz-ui for JavaScript/TypeScript users",
6
6
  "author": "Louis Mazel <me@loicmazuel.com>",
7
7
  "license": "MIT",
@@ -59,10 +59,19 @@
59
59
  "dist"
60
60
  ],
61
61
  "engines": {
62
- "node": ">=18.0.0"
62
+ "node": ">=22.12.0"
63
+ },
64
+ "peerDependencies": {
65
+ "libphonenumber-js": ">= 1 < 2"
66
+ },
67
+ "peerDependenciesMeta": {
68
+ "libphonenumber-js": {
69
+ "optional": true
70
+ }
63
71
  },
64
72
  "devDependencies": {
65
- "libphonenumber-js": "^1.12.42"
73
+ "@maz-ui/vite-config": "0.0.0",
74
+ "libphonenumber-js": "^1.13.15"
66
75
  },
67
76
  "lint-staged": {
68
77
  "*.{js,jsx,ts,tsx,mjs,mts,cjs,md,yml,json}": [
@@ -70,7 +79,6 @@
70
79
  ]
71
80
  },
72
81
  "scripts": {
73
- "codegen": "nx build",
74
82
  "build": "vite build",
75
83
  "build:watch": "vite build --watch --mode development",
76
84
  "typecheck": "tsc --noEmit --skipLibCheck",