@i-novus/ui-core
Version:
Базовые UI компоненты
48 lines (47 loc) • 1.9 kB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
import { forwardRef, useRef, useEffect, memo } from 'react';
import { IMask, useIMask } from 'react-imask';
import { useComposeRef, useMemoFunction } from '../core';
import { Input } from './Input';
const InputMaskForwarded = forwardRef((props, ref) => {
const { value: outValue, maskConfig, onChange, onComplete, onBlur, onReset: onResetExternal, ...restProps } = props;
const lastCompletedValueRef = useRef(outValue || '');
const handlerAccept = useMemoFunction((value, mask, event) => {
onChange?.(value, event);
if (!value) {
lastCompletedValueRef.current = '';
onComplete?.(value, event);
}
});
const handleComplete = useMemoFunction((value, mask, event) => {
lastCompletedValueRef.current = value;
onComplete?.(value, event);
});
const { ref: internalRef, value: maskedValue, setValue, } = useIMask(maskConfig, {
onAccept: handlerAccept,
onComplete: handleComplete,
});
const onReset = useMemoFunction((event) => {
lastCompletedValueRef.current = '';
setValue('');
onResetExternal?.(event);
});
const handleBlur = useMemoFunction((event) => {
setValue(lastCompletedValueRef.current);
onBlur?.(event, setValue);
});
useEffect(() => {
if (outValue && typeof outValue === 'string') {
lastCompletedValueRef.current = outValue;
setValue(outValue);
}
else {
lastCompletedValueRef.current = '';
setValue('');
}
}, [setValue, outValue]);
return (_jsx(Input, { ...restProps, ref: useComposeRef(internalRef, ref), onReset: onReset, onBlur: handleBlur, value: maskedValue }));
});
export const Mask = IMask;
export const InputMask = memo(InputMaskForwarded);
InputMask.displayName = 'InputMask';