From 2157b8d0cf747949a2fc9fa6bb70f0cc8fd70589 Mon Sep 17 00:00:00 2001 From: Allan Oliveira Date: Tue, 28 Feb 2023 05:36:04 -0300 Subject: [PATCH] feat: add input masker --- package.json | 2 +- src/hooks/useMask.ts | 52 +++++++++++++++++++++++++++++--------------- 2 files changed, 36 insertions(+), 18 deletions(-) diff --git a/package.json b/package.json index 60996c2..651f46f 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "react", "typescript" ], - "version": "2.1.16", + "version": "2.1.17", "main": "./dist/index.cjs.js", "module": "./dist/index.esm.js", "types": "./dist/index.d.ts", diff --git a/src/hooks/useMask.ts b/src/hooks/useMask.ts index 94bfe2a..26fb698 100644 --- a/src/hooks/useMask.ts +++ b/src/hooks/useMask.ts @@ -1,31 +1,46 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable no-param-reassign */ -import { useCallback, useMemo } from 'react' +import { MutableRefObject, useCallback, useRef } from 'react' import VMasker from 'vanilla-masker' -export const useMask = (customPattern: string) => { - const pattern = useMemo(() => customPattern, [customPattern]) +export const useMask = < + CurrentElement extends HTMLInputElement | null = HTMLInputElement | null +>() => { + const maskerRef = useRef | null>(null) + + const assignInstance = useCallback((instance: CurrentElement) => { + if (instance) { + maskerRef.current = VMasker(instance) + } + }, []) const ref = useCallback( - (instance: any) => { - VMasker(instance).maskPattern(pattern) + (instance: CurrentElement) => { + assignInstance(instance) }, - [pattern] + [assignInstance] ) const refWrapper = useCallback( - (currentRef: any) => { + ( + currentRef: + | ((instance: CurrentElement) => void) + | MutableRefObject + | undefined + ) => { if (currentRef && typeof currentRef === 'object') { - return (instance: any) => { + return (instance: CurrentElement) => { + assignInstance(instance) + currentRef.current = instance } } if (currentRef && typeof currentRef === 'function') { - return (instance: any) => { + return (instance: CurrentElement) => { if (instance) { - VMasker(instance).maskPattern(pattern) + assignInstance(instance) currentRef(instance) } @@ -34,21 +49,24 @@ export const useMask = (customPattern: string) => { return undefined }, - [pattern] + [assignInstance] ) const refWrapperFromObject = useCallback( (object: any) => { - const { ref: currentRef, ...rest } = object + if (typeof object === 'object') { + const { ref: currentRef, ...rest } = object + + return { ref: refWrapper(currentRef), ...rest } + } - return { ref: refWrapper(ref), ...rest } + return object }, - [ref, refWrapper] + [refWrapper] ) return { - ref, - refWrapper, - refWrapperFromObject, + masker: maskerRef.current, + connect: { ref, refWrapper, refWrapperFromObject }, } }