@maz-ui/utils 4.7.4 → 4.7.6-beta.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 (37) hide show
  1. package/dist/helpers/TextareaAutogrow.js +1 -25
  2. package/dist/helpers/camelCase.js +1 -6
  3. package/dist/helpers/capitalize.js +1 -6
  4. package/dist/helpers/checkAvailability.js +1 -16
  5. package/dist/helpers/countryCodeToUnicodeFlag.js +1 -10
  6. package/dist/helpers/debounce.js +1 -11
  7. package/dist/helpers/debounceCallback.js +1 -7
  8. package/dist/helpers/debounceId.js +1 -21
  9. package/dist/helpers/fetchLocaleIp.js +1 -12
  10. package/dist/helpers/formatCurrency.js +1 -34
  11. package/dist/helpers/formatDate.js +1 -21
  12. package/dist/helpers/formatJson.js +1 -6
  13. package/dist/helpers/formatNumber.js +1 -23
  14. package/dist/helpers/formatPhoneNumber.js +1 -10
  15. package/dist/helpers/getBrowserLocale.js +1 -11
  16. package/dist/helpers/getCountryFlagUrl.js +1 -9
  17. package/dist/helpers/getErrorMessage.js +1 -6
  18. package/dist/helpers/idleTimeout.js +1 -111
  19. package/dist/helpers/index.js +1 -64
  20. package/dist/helpers/isClient.js +1 -6
  21. package/dist/helpers/isEqual.js +1 -26
  22. package/dist/helpers/isServer.js +1 -6
  23. package/dist/helpers/isStandaloneMode.js +1 -10
  24. package/dist/helpers/kebabCase.js +1 -6
  25. package/dist/helpers/normalizeString.js +1 -92
  26. package/dist/helpers/pascalCase.js +1 -16
  27. package/dist/helpers/scriptLoader.js +1 -43
  28. package/dist/helpers/sleep.js +1 -6
  29. package/dist/helpers/snakeCase.js +1 -6
  30. package/dist/helpers/swipeHandler.js +1 -80
  31. package/dist/helpers/throttle.js +1 -11
  32. package/dist/helpers/throttleId.js +1 -19
  33. package/dist/helpers/truthyFilter.js +1 -6
  34. package/dist/helpers/upperFirst.js +1 -6
  35. package/dist/helpers/userVisibility.js +1 -50
  36. package/dist/index.js +1 -64
  37. package/package.json +2 -2
@@ -1,25 +1 @@
1
- import { debounce } from "./debounce.js";
2
- class TextareaAutogrow {
3
- element;
4
- constructor(element) {
5
- 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();
6
- }
7
- connect() {
8
- this.element.addEventListener("focus", this.onFocus), this.element.style.resize = "none", this.element.style.boxSizing = "border-box";
9
- }
10
- disconnect() {
11
- window.removeEventListener("resize", this.onResize), this.element.removeEventListener("input", this.autogrow);
12
- }
13
- onFocus() {
14
- this.autogrow(), this.element.addEventListener("input", this.autogrow), window.addEventListener("resize", this.onResize), this.element.removeEventListener("focus", this.onFocus);
15
- }
16
- onResize() {
17
- this.autogrow();
18
- }
19
- autogrow() {
20
- this.element.style.height = "auto", this.element.style.overflow = "hidden", this.element.style.height = `${this.element.scrollHeight}px`;
21
- }
22
- }
23
- export {
24
- TextareaAutogrow
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,6 +1 @@
1
- function camelCase(str) {
2
- return str.replaceAll(/-(\w)/g, (_, c) => c ? c.toUpperCase() : "");
3
- }
4
- export {
5
- camelCase
6
- };
1
+ function camelCase(str){return str.replaceAll(/-(\w)/g,(_,c)=>c?c.toUpperCase():``)}export{camelCase};
@@ -1,6 +1 @@
1
- function capitalize(value) {
2
- return typeof value != "string" ? "" : value.charAt(0).toUpperCase() + value.slice(1);
3
- }
4
- export {
5
- capitalize
6
- };
1
+ function capitalize(value){return typeof value==`string`?value.charAt(0).toUpperCase()+value.slice(1):``}export{capitalize};
@@ -1,16 +1 @@
1
- function checkAvailability(getRef, callback, options) {
2
- const opts = {
3
- maxAttempts: 20,
4
- interval: 100,
5
- ...options
6
- };
7
- let attempts = 0;
8
- function check() {
9
- const ref = getRef();
10
- ref != null ? opts.expectedValue !== void 0 && ref !== opts.expectedValue ? attempts < opts.maxAttempts ? (attempts++, setTimeout(check, opts.interval)) : opts.onError?.(new Error(opts.errorMessage || `[maz-ui](checkAvailability) Nothing found after ${opts.maxAttempts} attempts`)) : callback(ref) : attempts < opts.maxAttempts ? (attempts++, setTimeout(check, opts.interval)) : opts.onError?.(new Error(opts.errorMessage || `[maz-ui](checkAvailability) Nothing found after ${opts.maxAttempts} attempts`));
11
- }
12
- check();
13
- }
14
- export {
15
- checkAvailability
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,10 +1 @@
1
- import { truthyFilter } from "./truthyFilter.js";
2
- function countryCodeToUnicodeFlag(locale) {
3
- return Array.from(locale, (letter) => {
4
- const code = letter.codePointAt(0);
5
- return code ? code % 32 + 127461 : void 0;
6
- }).filter(truthyFilter).map((n) => String.fromCodePoint(n)).join("");
7
- }
8
- export {
9
- countryCodeToUnicodeFlag
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,11 +1 @@
1
- function debounce(fn, delay) {
2
- let timeout;
3
- return function(...args) {
4
- clearTimeout(timeout), timeout = setTimeout(() => {
5
- fn.apply(this, args);
6
- }, delay);
7
- };
8
- }
9
- export {
10
- debounce
11
- };
1
+ function debounce(fn,delay){let timeout;return function(...args){clearTimeout(timeout),timeout=setTimeout(()=>{fn.apply(this,args)},delay)}}export{debounce};
@@ -1,7 +1 @@
1
- let timeout = null;
2
- function debounceCallback(callback, delay) {
3
- timeout && clearTimeout(timeout), timeout = setTimeout(callback, delay);
4
- }
5
- export {
6
- debounceCallback
7
- };
1
+ var timeout=null;function debounceCallback(callback,delay){timeout&&clearTimeout(timeout),timeout=setTimeout(callback,delay)}export{debounceCallback};
@@ -1,21 +1 @@
1
- function debounceId(identifier, func, delay) {
2
- const debouncedFunctions = {};
3
- return function(...args) {
4
- debouncedFunctions[identifier] || (debouncedFunctions[identifier] = { timer: null, promise: null });
5
- const debounced = debouncedFunctions[identifier];
6
- return debounced.timer && clearTimeout(debounced.timer), debounced.promise = new Promise((resolve, reject) => {
7
- debounced.timer = setTimeout(async () => {
8
- try {
9
- resolve(await func(...args));
10
- } catch (error) {
11
- reject(error);
12
- } finally {
13
- delete debouncedFunctions[identifier];
14
- }
15
- }, delay);
16
- }), debounced.promise;
17
- };
18
- }
19
- export {
20
- debounceId
21
- };
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,12 +1 @@
1
- async function fetchLocaleIp() {
2
- try {
3
- const reponse = await fetch("https://ipwho.is"), { country_code } = await reponse.json();
4
- return country_code;
5
- } catch (error) {
6
- console.error(`[maz-ui](fetchLocaleIp) ${error}`);
7
- return;
8
- }
9
- }
10
- export {
11
- fetchLocaleIp
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,34 +1 @@
1
- const DEFAULT_OPTIONS = {
2
- style: "currency",
3
- minimumFractionDigits: 2,
4
- round: !1
5
- };
6
- function getFormattedCurrency(number, locale, options) {
7
- let numberToFormat = +number;
8
- return options.round && (numberToFormat = Math.floor(numberToFormat), options.minimumFractionDigits = 0), new Intl.NumberFormat(locale, options).format(numberToFormat);
9
- }
10
- function validRequiredAttributes(number, locale, options) {
11
- if (number === void 0)
12
- throw new TypeError("[maz-ui](FilterCurrency) The `number` attribute is required.");
13
- if (locale === void 0)
14
- throw new TypeError("[maz-ui](FilterCurrency) The `locale` attribute is required.");
15
- if (typeof locale != "string")
16
- throw new TypeError("[maz-ui](FilterCurrency) The `locale` attribute must be a string.");
17
- if (options.currency === void 0)
18
- throw new TypeError("[maz-ui](FilterCurrency) The `options.currency` attribute is required.");
19
- }
20
- function formatCurrency(number, locale, options) {
21
- const options_ = {
22
- ...DEFAULT_OPTIONS,
23
- ...options
24
- };
25
- validRequiredAttributes(number, locale, options_);
26
- try {
27
- return getFormattedCurrency(number, locale, options_);
28
- } catch (error) {
29
- throw new Error(`[maz-ui](FilterCurrency) ${error}`, { cause: error });
30
- }
31
- }
32
- export {
33
- formatCurrency
34
- };
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,21 +1 @@
1
- const DEFAULT_OPTIONS = {
2
- month: "short",
3
- day: "numeric",
4
- year: "numeric"
5
- };
6
- function formatDate(date, locale, options) {
7
- if (locale === void 0)
8
- throw new TypeError("[maz-ui](FilterDate) The `locale` attribute is required.");
9
- if (typeof locale != "string")
10
- throw new TypeError("[maz-ui](FilterDate) The `locale` attribute must be a string.");
11
- const opts = options ?? DEFAULT_OPTIONS;
12
- try {
13
- const usedDate = date instanceof Date ? date : new Date(date);
14
- return new Intl.DateTimeFormat(locale, opts).format(usedDate);
15
- } catch (error) {
16
- throw new Error(`[maz-ui](FilterDate) ${error}`, { cause: error });
17
- }
18
- }
19
- export {
20
- formatDate
21
- };
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,6 +1 @@
1
- function formatJson(json, indent = 2) {
2
- return JSON.stringify(json, null, indent);
3
- }
4
- export {
5
- formatJson
6
- };
1
+ function formatJson(json,indent=2){return JSON.stringify(json,null,indent)}export{formatJson};
@@ -1,23 +1 @@
1
- const DEFAULT_OPTIONS = {
2
- minimumFractionDigits: 2
3
- };
4
- function formatNumber(number, locale, options) {
5
- const filterOptions = {
6
- ...DEFAULT_OPTIONS,
7
- ...options
8
- };
9
- if (number === void 0)
10
- throw new TypeError("[maz-ui](FilterNumber) The `number` attribute is required.");
11
- if (locale === void 0)
12
- throw new TypeError("[maz-ui](FilterNumber) The `locale` attribute is required.");
13
- if (typeof locale != "string")
14
- throw new TypeError("[maz-ui](FilterNumber) The `locale` attribute must be a string.");
15
- try {
16
- return new Intl.NumberFormat(locale, filterOptions).format(Number(number));
17
- } catch (error) {
18
- throw new Error(`[maz-ui](FilterNumber) ${error}`, { cause: error });
19
- }
20
- }
21
- export {
22
- formatNumber
23
- };
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,10 +1 @@
1
- import { parsePhoneNumberFromString } from "libphonenumber-js";
2
- function formatPhoneNumber(phoneNumber) {
3
- if (!phoneNumber)
4
- throw new TypeError("[maz-ui](formatPhoneNumber) The `phoneNumber` argument is required.");
5
- const parsedPhone = parsePhoneNumberFromString(phoneNumber);
6
- return parsedPhone ? parsedPhone.formatInternational() : phoneNumber;
7
- }
8
- export {
9
- formatPhoneNumber
10
- };
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,11 +1 @@
1
- import { isServer } from "./isServer.js";
2
- function getBrowserLocale() {
3
- try {
4
- return isServer() ? void 0 : globalThis.navigator.language;
5
- } catch (error) {
6
- throw new Error(`[MazInputPhoneNumber] (browserLocale) ${error}`, { cause: error });
7
- }
8
- }
9
- export {
10
- getBrowserLocale
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,9 +1 @@
1
- const _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"];
2
- function getCountryFlagUrl(countryIsoCode, size) {
3
- const code = countryIsoCode.toLowerCase();
4
- if (_supportedCodes.includes(code))
5
- return size ? `https://flagcdn.com/${size}/${code}.png` : `https://flagcdn.com/${code}.svg`;
6
- }
7
- export {
8
- getCountryFlagUrl
9
- };
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,6 +1 @@
1
- function getErrorMessage(error) {
2
- 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";
3
- }
4
- export {
5
- getErrorMessage
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,111 +1 @@
1
- import { isClient } from "./isClient.js";
2
- class IdleTimeout {
3
- constructor(callback, options) {
4
- this.callback = callback, this.options = {
5
- ...this.defaultOptions,
6
- ...options
7
- }, isClient() && this.start();
8
- }
9
- defaultOptions = {
10
- element: void 0,
11
- timeout: 60 * 1e3 * 5,
12
- // 5 minutes
13
- once: !1,
14
- immediate: !0
15
- };
16
- options;
17
- timeoutHandler;
18
- isIdle = !1;
19
- isDestroy = !1;
20
- startTime = 0;
21
- remainingTime = 0;
22
- lastClientX = -1;
23
- lastClientY = -1;
24
- eventNames = [
25
- "DOMMouseScroll",
26
- "mousedown",
27
- "mousemove",
28
- "mousewheel",
29
- "MSPointerDown",
30
- "MSPointerMove",
31
- "keydown",
32
- "touchmove",
33
- "touchstart",
34
- "wheel",
35
- "click"
36
- ];
37
- get element() {
38
- return this.options.element ?? document.body;
39
- }
40
- start() {
41
- if (!isClient()) {
42
- console.warn("[IdleTimeout](start) you should run this method on client side");
43
- return;
44
- }
45
- for (const eventName of this.eventNames)
46
- this.element.addEventListener(eventName, this.handleEvent);
47
- this.resetTimeout(), this.options.immediate && this.callback({ isIdle: !1, instance: this });
48
- }
49
- pause() {
50
- const remainingTime = this.startTime + this.options.timeout - Date.now();
51
- remainingTime <= 0 || (this.remainingTime = remainingTime, this.timeoutHandler && (clearTimeout(this.timeoutHandler), this.timeoutHandler = void 0));
52
- }
53
- resume() {
54
- this.remainingTime <= 0 || (this.resetTimeout(), this.callback({ isIdle: this.isIdle, instance: this }), this.remainingTime = 0);
55
- }
56
- reset() {
57
- this.isDestroy = !1, this.isIdle = !1, this.remainingTime = 0, this.resetTimeout(), this.callback({ isIdle: this.isIdle, instance: this });
58
- }
59
- destroy() {
60
- if (!isClient()) {
61
- console.warn("[IdleTimeout](destroy) you should run this method on client side");
62
- return;
63
- }
64
- this.isDestroy = !0;
65
- for (const eventName of this.eventNames)
66
- this.element.removeEventListener(eventName, this.handleEvent);
67
- this.timeoutHandler && clearTimeout(this.timeoutHandler);
68
- }
69
- resetTimeout() {
70
- this.isIdle = !1, this.timeoutHandler && (clearTimeout(this.timeoutHandler), this.timeoutHandler = void 0), this.timeoutHandler = setTimeout(
71
- this.handleTimeout.bind(this),
72
- this.remainingTime || this.options.timeout
73
- ), this.startTime = Date.now();
74
- }
75
- handleEvent = (event) => {
76
- try {
77
- if (this.remainingTime > 0)
78
- return;
79
- if (event.type === "mousemove") {
80
- const { clientX, clientY } = event;
81
- if (clientX === void 0 && clientY === void 0 || clientX === this.lastClientX && clientY === this.lastClientY)
82
- return;
83
- this.lastClientX = clientX, this.lastClientY = clientY;
84
- }
85
- this.resetTimeout(), this.callback({ isIdle: this.isIdle, eventType: event.type, instance: this });
86
- } catch (error) {
87
- throw new Error(`[IdleTimeout](handleEvent) ${error}`, { cause: error });
88
- }
89
- };
90
- handleTimeout() {
91
- this.isIdle = !0, this.callback({ isIdle: this.isIdle, instance: this }), this.options.once && this.destroy();
92
- }
93
- get destroyed() {
94
- return this.isDestroy;
95
- }
96
- get timeout() {
97
- return this.options.timeout;
98
- }
99
- set timeout(value) {
100
- this.options.timeout = value;
101
- }
102
- get idle() {
103
- return this.isIdle;
104
- }
105
- set idle(value) {
106
- value ? this.handleTimeout() : this.reset(), this.callback({ isIdle: this.isIdle, instance: this });
107
- }
108
- }
109
- export {
110
- IdleTimeout
111
- };
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,64 +1 @@
1
- import { camelCase } from "./camelCase.js";
2
- import { capitalize } from "./capitalize.js";
3
- import { checkAvailability } from "./checkAvailability.js";
4
- import { countryCodeToUnicodeFlag } from "./countryCodeToUnicodeFlag.js";
5
- import { debounce } from "./debounce.js";
6
- import { debounceCallback } from "./debounceCallback.js";
7
- import { debounceId } from "./debounceId.js";
8
- import { formatCurrency } from "./formatCurrency.js";
9
- import { formatDate } from "./formatDate.js";
10
- import { formatJson } from "./formatJson.js";
11
- import { formatNumber } from "./formatNumber.js";
12
- import { getCountryFlagUrl } from "./getCountryFlagUrl.js";
13
- import { getErrorMessage } from "./getErrorMessage.js";
14
- import { IdleTimeout } from "./idleTimeout.js";
15
- import { isClient } from "./isClient.js";
16
- import { isEqual } from "./isEqual.js";
17
- import { isServer } from "./isServer.js";
18
- import { isStandaloneMode } from "./isStandaloneMode.js";
19
- import { kebabCase } from "./kebabCase.js";
20
- import { normalizeString } from "./normalizeString.js";
21
- import { pascalCase } from "./pascalCase.js";
22
- import { ScriptLoader } from "./scriptLoader.js";
23
- import { sleep } from "./sleep.js";
24
- import { snakeCase } from "./snakeCase.js";
25
- import { Swipe } from "./swipeHandler.js";
26
- import { TextareaAutogrow } from "./TextareaAutogrow.js";
27
- import { throttle } from "./throttle.js";
28
- import { throttleId } from "./throttleId.js";
29
- import { truthyFilter } from "./truthyFilter.js";
30
- import { upperFirst } from "./upperFirst.js";
31
- import { UserVisibility } from "./userVisibility.js";
32
- export {
33
- IdleTimeout,
34
- ScriptLoader,
35
- Swipe,
36
- TextareaAutogrow,
37
- UserVisibility,
38
- camelCase,
39
- capitalize,
40
- checkAvailability,
41
- countryCodeToUnicodeFlag,
42
- debounce,
43
- debounceCallback,
44
- debounceId,
45
- formatCurrency,
46
- formatDate,
47
- formatJson,
48
- formatNumber,
49
- getCountryFlagUrl,
50
- getErrorMessage,
51
- isClient,
52
- isEqual,
53
- isServer,
54
- isStandaloneMode,
55
- kebabCase,
56
- normalizeString,
57
- pascalCase,
58
- sleep,
59
- snakeCase,
60
- throttle,
61
- throttleId,
62
- truthyFilter,
63
- upperFirst
64
- };
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,6 +1 @@
1
- function isClient() {
2
- return typeof document < "u";
3
- }
4
- export {
5
- isClient
6
- };
1
+ function isClient(){return typeof document<`u`}export{isClient};
@@ -1,26 +1 @@
1
- function isPrimitive(value) {
2
- return value == null || typeof value == "string" || typeof value == "number" || typeof value == "boolean" || typeof value == "symbol" || typeof value == "bigint";
3
- }
4
- function isEqualArrays(a, b) {
5
- if (a.length !== b.length)
6
- return !1;
7
- for (const [i, element] of a.entries())
8
- if (!isEqual(element, b[i]))
9
- return !1;
10
- return !0;
11
- }
12
- function isEqualObjects(a, b) {
13
- const keysA = Object.keys(a), keysB = Object.keys(b);
14
- if (keysA.length !== keysB.length)
15
- return !1;
16
- for (const key of keysA)
17
- if (!keysB.includes(key) || !isEqual(a[key], b[key]))
18
- return !1;
19
- return !0;
20
- }
21
- function isEqual(a, b) {
22
- 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;
23
- }
24
- export {
25
- isEqual
26
- };
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,6 +1 @@
1
- function isServer() {
2
- return typeof document > "u" || typeof globalThis.window > "u";
3
- }
4
- export {
5
- isServer
6
- };
1
+ function isServer(){return typeof document>`u`||globalThis.window===void 0}export{isServer};
@@ -1,10 +1 @@
1
- import { isClient } from "./isClient.js";
2
- function isStandaloneMode() {
3
- if (!isClient())
4
- return !1;
5
- const nav = navigator, isStandalone = globalThis.matchMedia("(display-mode: standalone)").matches;
6
- return nav.standalone || isStandalone;
7
- }
8
- export {
9
- isStandaloneMode
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,6 +1 @@
1
- function kebabCase(str) {
2
- 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, "");
3
- }
4
- export {
5
- kebabCase
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,92 +1 @@
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
- const defaultOptions = {
6
- removeAccents: !0,
7
- caseSensitive: !1,
8
- replaceSpaces: !0,
9
- removeSpecialCharacters: !1,
10
- trim: !0,
11
- normalizeSpaces: !0,
12
- removeNumbers: !1,
13
- case: void 0,
14
- customNormalizationForms: ["NFC", "NFKD"]
15
- };
16
- function applyCaseTransform(str, caseFormat) {
17
- switch (caseFormat) {
18
- case "kebab-case":
19
- return kebabCase(str);
20
- case "camelCase":
21
- return camelCase(str);
22
- case "PascalCase":
23
- return pascalCase(str);
24
- case "snake_case":
25
- return snakeCase(str);
26
- case "lowercase":
27
- return str.toLowerCase();
28
- case "UPPERCASE":
29
- return str.toUpperCase();
30
- default:
31
- return str;
32
- }
33
- }
34
- function normalizeString(input, options) {
35
- const finalOptions = { ...defaultOptions, ...options }, accentsMap = {
36
- À: "A",
37
- Á: "A",
38
- Â: "A",
39
- Ã: "A",
40
- Ä: "A",
41
- Å: "A",
42
- à: "a",
43
- á: "a",
44
- â: "a",
45
- ã: "a",
46
- ä: "a",
47
- å: "a",
48
- È: "E",
49
- É: "E",
50
- Ê: "E",
51
- Ë: "E",
52
- è: "e",
53
- é: "e",
54
- ê: "e",
55
- ë: "e",
56
- Î: "I",
57
- Ï: "I",
58
- í: "I",
59
- î: "i",
60
- ï: "i",
61
- Ô: "O",
62
- Õ: "O",
63
- Ö: "O",
64
- Ø: "O",
65
- ô: "o",
66
- õ: "o",
67
- ö: "o",
68
- ø: "o",
69
- Ù: "U",
70
- Ú: "U",
71
- Û: "U",
72
- Ü: "U",
73
- ù: "u",
74
- ú: "u",
75
- û: "u",
76
- ü: "u",
77
- Ç: "C",
78
- ç: "c",
79
- ÿ: "y",
80
- Ñ: "N",
81
- ñ: "n",
82
- ó: "o"
83
- };
84
- let result = input.toString();
85
- 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)
86
- for (const form of finalOptions.customNormalizationForms)
87
- result = result.normalize(form);
88
- return result;
89
- }
90
- export {
91
- normalizeString
92
- };
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,16 +1 @@
1
- import { camelCase } from "./camelCase.js";
2
- import { capitalize } from "./capitalize.js";
3
- function pascalCase(str) {
4
- if (str === str.toUpperCase()) {
5
- if (str.includes("-"))
6
- return str.toLowerCase().split("-").map(capitalize).join("");
7
- if (str.includes("_"))
8
- return str.toLowerCase().split("_").map(capitalize).join("");
9
- if (str.includes(" "))
10
- return str.toLowerCase().split(" ").map(capitalize).join("");
11
- }
12
- 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));
13
- }
14
- export {
15
- pascalCase
16
- };
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,43 +1 @@
1
- class ScriptLoader {
2
- src;
3
- script;
4
- once;
5
- async;
6
- defer;
7
- identifier;
8
- constructor({ src, identifier, once = !0, async = !0, defer = !0 }) {
9
- if (typeof globalThis.window > "u")
10
- throw new TypeError("[ScriptLoader]: Is supported only on browser side");
11
- if (!src)
12
- throw new Error('[ScriptLoader]: You should provide the attribut "src"');
13
- if (!identifier)
14
- throw new Error('[ScriptLoader]: You should provide the attribut "identifier"');
15
- this.src = src, this.identifier = identifier, this.once = once, this.async = async, this.defer = defer;
16
- }
17
- removeTag(tag) {
18
- typeof tag == "string" ? document.head.querySelector(`[data-identifier="${tag}"]`)?.remove() : tag.remove();
19
- }
20
- load() {
21
- const windowInstance = globalThis, scriptTags = document.head.querySelectorAll(`[data-identifier="${this.identifier}"]`);
22
- if (this.once && windowInstance[this.identifier] && scriptTags.length > 0)
23
- return this.script = windowInstance[this.identifier], Promise.resolve(this.script);
24
- if (!this.once && scriptTags.length > 0)
25
- for (const tag of scriptTags)
26
- this.removeTag(tag);
27
- return this.injectScript();
28
- }
29
- injectScript() {
30
- const windowInstance = globalThis;
31
- return new Promise((resolve, reject) => {
32
- try {
33
- const script = document.createElement("script");
34
- script.src = this.src, script.async = this.async, script.defer = this.defer, script.dataset.identifier = this.identifier, script.addEventListener("error", (error) => reject(new Error(`[ScriptLoader](injectScript) ${error.message}`))), script.addEventListener("load", (success) => (this.script = success, windowInstance[this.identifier] = success, resolve(success))), document.head.append(script);
35
- } catch (error) {
36
- throw new Error(`[ScriptLoader](init) ${error}`, { cause: error });
37
- }
38
- });
39
- }
40
- }
41
- export {
42
- ScriptLoader
43
- };
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,6 +1 @@
1
- function sleep(duration) {
2
- return new Promise((resolve) => setTimeout(resolve, duration));
3
- }
4
- export {
5
- sleep
6
- };
1
+ function sleep(duration){return new Promise(resolve=>setTimeout(resolve,duration))}export{sleep};
@@ -1,6 +1 @@
1
- function snakeCase(str) {
2
- 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, "");
3
- }
4
- export {
5
- snakeCase
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,80 +1 @@
1
- const defaultOptions = {
2
- preventDefaultOnTouchMove: !1,
3
- preventDefaultOnMouseWheel: !1,
4
- threshold: 50,
5
- immediate: !1,
6
- triggerOnEnd: !1
7
- };
8
- class Swipe {
9
- constructor(inputOption) {
10
- 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();
11
- }
12
- element;
13
- xStart;
14
- yStart;
15
- xEnd;
16
- yEnd;
17
- xDiff;
18
- yDiff;
19
- onToucheStartCallback;
20
- onToucheMoveCallback;
21
- onToucheEndCallback;
22
- onMouseWheelCallback;
23
- start;
24
- stop;
25
- options;
26
- startListening() {
27
- 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 });
28
- }
29
- stopListening() {
30
- 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);
31
- }
32
- setElement(element) {
33
- if (!element) {
34
- console.error(
35
- "[maz-ui][SwipeHandler](setElement) Element should be provided. Its can be a string selector or an HTMLElement"
36
- );
37
- return;
38
- }
39
- if (typeof element == "string") {
40
- const foundElement = document.querySelector(element);
41
- if (!(foundElement instanceof HTMLElement)) {
42
- console.error("[maz-ui][SwipeHandler](setElement) String selector for element is not found");
43
- return;
44
- }
45
- this.element = foundElement;
46
- } else
47
- this.element = element;
48
- }
49
- handleMouseWheel(event) {
50
- event.preventDefault();
51
- }
52
- toucheStartHandler(event) {
53
- this.xStart = event.touches[0].clientX, this.yStart = event.touches[0].clientY, this.emitValuesChanged();
54
- }
55
- emitValuesChanged() {
56
- this.options.onValuesChanged?.({
57
- xStart: this.xStart,
58
- yStart: this.yStart,
59
- xEnd: this.xEnd,
60
- yEnd: this.yEnd,
61
- xDiff: this.xDiff,
62
- yDiff: this.yDiff
63
- });
64
- }
65
- handleTouchMove(event) {
66
- 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));
67
- }
68
- handleTouchEnd(event) {
69
- this.runCallbacks(event), this.emitValuesChanged();
70
- }
71
- runCallbacks(event) {
72
- 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());
73
- }
74
- resetValues() {
75
- 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();
76
- }
77
- }
78
- export {
79
- Swipe
80
- };
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,11 +1 @@
1
- function throttle(func, limit) {
2
- let inThrottle = !1, lastFunc, lastRan;
3
- return function(...args) {
4
- inThrottle ? (clearTimeout(lastFunc), lastFunc = setTimeout(() => {
5
- Date.now() - lastRan >= limit && (func.apply(this, args), lastRan = Date.now());
6
- }, Math.max(limit - (Date.now() - lastRan), 0))) : (func.apply(this, args), lastRan = Date.now(), inThrottle = !0);
7
- };
8
- }
9
- export {
10
- throttle
11
- };
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,19 +1 @@
1
- function throttleId(identifier, func, interval) {
2
- const state = {};
3
- return async (...args) => {
4
- const now = Date.now();
5
- 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) => {
6
- setTimeout(
7
- async () => {
8
- state[identifier].lastCall = Date.now();
9
- const result = await func(...state[identifier].lastArgs);
10
- state[identifier].promise = null, resolve(result);
11
- },
12
- interval - (now - state[identifier].lastCall)
13
- );
14
- })), state[identifier].promise);
15
- };
16
- }
17
- export {
18
- throttleId
19
- };
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,6 +1 @@
1
- function truthyFilter(value) {
2
- return !!value;
3
- }
4
- export {
5
- truthyFilter
6
- };
1
+ function truthyFilter(value){return!!value}export{truthyFilter};
@@ -1,6 +1 @@
1
- function upperFirst(value) {
2
- return value.charAt(0).toUpperCase() + value.slice(1);
3
- }
4
- export {
5
- upperFirst
6
- };
1
+ function upperFirst(value){return value.charAt(0).toUpperCase()+value.slice(1)}export{upperFirst};
@@ -1,50 +1 @@
1
- import { isClient } from "./isClient.js";
2
- class UserVisibility {
3
- constructor(callback, options) {
4
- this.callback = callback, this.options = {
5
- ...this.defaultOptions,
6
- ...options
7
- }, this.eventHandlerFunction = this.eventHandler.bind(this), isClient() && this.start();
8
- }
9
- eventHandlerFunction;
10
- event = "visibilitychange";
11
- timeoutHandler;
12
- options;
13
- defaultOptions = {
14
- timeout: 5e3,
15
- once: !1,
16
- immediate: !0
17
- };
18
- isVisible = !1;
19
- start() {
20
- if (!isClient()) {
21
- console.warn("[UserVisibility](start) you should run this method on client side");
22
- return;
23
- }
24
- this.options.immediate && this.emitCallback(), this.addEventListener();
25
- }
26
- emitCallback() {
27
- this.isVisible = document.visibilityState === "visible", this.callback({ isVisible: this.isVisible }), this.options.once && this.destroy();
28
- }
29
- eventHandler() {
30
- document.visibilityState === "visible" && !this.isVisible ? (this.clearTimeout(), this.emitCallback()) : document.visibilityState === "hidden" && this.initTimeout();
31
- }
32
- clearTimeout() {
33
- this.timeoutHandler && (clearTimeout(this.timeoutHandler), this.timeoutHandler = void 0);
34
- }
35
- initTimeout() {
36
- this.clearTimeout(), this.timeoutHandler = setTimeout(this.emitCallback.bind(this), this.options.timeout);
37
- }
38
- addEventListener() {
39
- document.addEventListener(this.event, this.eventHandlerFunction);
40
- }
41
- removeEventListener() {
42
- document.removeEventListener(this.event, this.eventHandlerFunction);
43
- }
44
- destroy() {
45
- this.removeEventListener(), this.timeoutHandler && clearTimeout(this.timeoutHandler);
46
- }
47
- }
48
- export {
49
- UserVisibility
50
- };
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};
package/dist/index.js CHANGED
@@ -1,64 +1 @@
1
- import { IdleTimeout } from "./helpers/idleTimeout.js";
2
- import { ScriptLoader } from "./helpers/scriptLoader.js";
3
- import { Swipe } from "./helpers/swipeHandler.js";
4
- import { TextareaAutogrow } from "./helpers/TextareaAutogrow.js";
5
- import { UserVisibility } from "./helpers/userVisibility.js";
6
- import { camelCase } from "./helpers/camelCase.js";
7
- import { capitalize } from "./helpers/capitalize.js";
8
- import { checkAvailability } from "./helpers/checkAvailability.js";
9
- import { countryCodeToUnicodeFlag } from "./helpers/countryCodeToUnicodeFlag.js";
10
- import { debounce } from "./helpers/debounce.js";
11
- import { debounceCallback } from "./helpers/debounceCallback.js";
12
- import { debounceId } from "./helpers/debounceId.js";
13
- import { formatCurrency } from "./helpers/formatCurrency.js";
14
- import { formatDate } from "./helpers/formatDate.js";
15
- import { formatJson } from "./helpers/formatJson.js";
16
- import { formatNumber } from "./helpers/formatNumber.js";
17
- import { getCountryFlagUrl } from "./helpers/getCountryFlagUrl.js";
18
- import { getErrorMessage } from "./helpers/getErrorMessage.js";
19
- import { isClient } from "./helpers/isClient.js";
20
- import { isEqual } from "./helpers/isEqual.js";
21
- import { isServer } from "./helpers/isServer.js";
22
- import { isStandaloneMode } from "./helpers/isStandaloneMode.js";
23
- import { kebabCase } from "./helpers/kebabCase.js";
24
- import { normalizeString } from "./helpers/normalizeString.js";
25
- import { pascalCase } from "./helpers/pascalCase.js";
26
- import { sleep } from "./helpers/sleep.js";
27
- import { snakeCase } from "./helpers/snakeCase.js";
28
- import { throttle } from "./helpers/throttle.js";
29
- import { throttleId } from "./helpers/throttleId.js";
30
- import { truthyFilter } from "./helpers/truthyFilter.js";
31
- import { upperFirst } from "./helpers/upperFirst.js";
32
- export {
33
- IdleTimeout,
34
- ScriptLoader,
35
- Swipe,
36
- TextareaAutogrow,
37
- UserVisibility,
38
- camelCase,
39
- capitalize,
40
- checkAvailability,
41
- countryCodeToUnicodeFlag,
42
- debounce,
43
- debounceCallback,
44
- debounceId,
45
- formatCurrency,
46
- formatDate,
47
- formatJson,
48
- formatNumber,
49
- getCountryFlagUrl,
50
- getErrorMessage,
51
- isClient,
52
- isEqual,
53
- isServer,
54
- isStandaloneMode,
55
- kebabCase,
56
- normalizeString,
57
- pascalCase,
58
- sleep,
59
- snakeCase,
60
- throttle,
61
- throttleId,
62
- truthyFilter,
63
- upperFirst
64
- };
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};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@maz-ui/utils",
3
3
  "type": "module",
4
- "version": "4.7.4",
4
+ "version": "4.7.6-beta.0",
5
5
  "description": "Utils of maz-ui for JavaScript/TypeScript users",
6
6
  "author": "Louis Mazel <me@loicmazuel.com>",
7
7
  "license": "MIT",
@@ -53,7 +53,7 @@
53
53
  "node": ">=18.0.0"
54
54
  },
55
55
  "devDependencies": {
56
- "libphonenumber-js": "^1.12.38"
56
+ "libphonenumber-js": "^1.12.40"
57
57
  },
58
58
  "lint-staged": {
59
59
  "*.{js,jsx,ts,tsx,mjs,mts,cjs,md,yml,json}": [