-
Notifications
You must be signed in to change notification settings - Fork 0
/
use-web-mask.ts
53 lines (48 loc) · 1.18 KB
/
use-web-mask.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import React from 'react';
import { useRefMask } from './use-ref-mask';
import type { MaskGenerator } from '../types/mask-generator';
export const useWebMask = ({
maskGenerator,
value,
onChange,
keepMask,
ref: outerRef,
}: {
maskGenerator?: MaskGenerator;
value?: string;
onChange?: (value: string) => void;
keepMask?: boolean;
ref?: React.ForwardedRef<HTMLInputElement>;
}) => {
const getCursorPosition = React.useCallback(
(el: HTMLInputElement | undefined) => {
const cursorPosition = el?.selectionStart ?? 0;
return cursorPosition;
},
[],
);
const setCursorPosition = React.useCallback(
(cursorPosition: number, el: HTMLInputElement | undefined) => {
if (el) {
el.selectionStart = cursorPosition;
el.selectionEnd = cursorPosition;
}
},
[],
);
const { displayValue, setDisplayValue, ref } = useRefMask({
value,
maskGenerator,
getCursorPosition,
setCursorPosition,
onChange,
keepMask,
ref: outerRef,
});
const handleOnChange: React.ChangeEventHandler<HTMLInputElement> =
React.useCallback(
(e) => setDisplayValue(e?.target?.value ?? ''),
[setDisplayValue],
);
return { value: displayValue, onChange: handleOnChange, ref };
};