@maz-ui/utils 5.0.0-canary.ef64a02.0 → 5.2.0-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 (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 +24 -4
@@ -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.2.0-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",
@@ -59,10 +59,31 @@
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
+ "@codecov/vite-plugin": "^2.0.1",
74
+ "@maz-ui/vite-config": "^0.0.0",
75
+ "@types/node": "^22.20.5",
76
+ "@vitejs/plugin-vue": "^6.0.10",
77
+ "@vitest/coverage-v8": "^5.0.5",
78
+ "cross-env": "^10.1.0",
79
+ "eslint": "^10.13.0",
80
+ "glob": "^13.0.6",
81
+ "libphonenumber-js": "^1.13.15",
82
+ "typescript": "^6.0.3",
83
+ "vite": "^8.3.4",
84
+ "vite-plugin-dts": "^5.1.2",
85
+ "vitest": "5.0.5",
86
+ "vue": "^3.5.44"
66
87
  },
67
88
  "lint-staged": {
68
89
  "*.{js,jsx,ts,tsx,mjs,mts,cjs,md,yml,json}": [
@@ -70,7 +91,6 @@
70
91
  ]
71
92
  },
72
93
  "scripts": {
73
- "codegen": "nx build",
74
94
  "build": "vite build",
75
95
  "build:watch": "vite build --watch --mode development",
76
96
  "typecheck": "tsc --noEmit --skipLibCheck",