Skip to content

Commit

Permalink
feat: add input masker
Browse files Browse the repository at this point in the history
  • Loading branch information
AllanOliveiraM committed Feb 28, 2023
1 parent 27f39de commit 2157b8d
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 18 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
52 changes: 35 additions & 17 deletions src/hooks/useMask.ts
Original file line number Diff line number Diff line change
@@ -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<ReturnType<typeof VMasker> | 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<CurrentElement>
| 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)
}
Expand All @@ -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 },
}
}

0 comments on commit 2157b8d

Please sign in to comment.