react-hook-mask
Version:
React masked input component and hooks
60 lines • 2.85 kB
JavaScript
import React from 'react';
import { useRefMask } from './use-ref-mask';
export var useNativeMask = function (_a) {
var maskGenerator = _a.maskGenerator, value = _a.value, onChange = _a.onChange, keepMask = _a.keepMask, waitToUpdateCursor = _a.waitToUpdateCursor, outerRef = _a.ref;
var selectionRef = React.useRef({ start: 0, end: 0 });
var onSelectionChange = React.useCallback(function (event) {
var selection = event.nativeEvent.selection;
selectionRef.current = selection;
}, []);
var getCursorPosition = React.useCallback(function () {
var _a, _b;
var cursorPosition = (_b = (_a = selectionRef.current) === null || _a === void 0 ? void 0 : _a.start) !== null && _b !== void 0 ? _b : 0;
return cursorPosition;
}, []);
var setCursorPosition = React.useCallback(function (cursorPosition, el) {
if (el === null || el === void 0 ? void 0 : el.setNativeProps) {
var selection_1 = { start: cursorPosition, end: cursorPosition };
selectionRef.current = selection_1;
if (waitToUpdateCursor) {
setTimeout(function () {
selectionRef.current = selection_1;
el.setNativeProps({
selection: selection_1,
});
}, 20);
}
else {
el.setNativeProps({
selection: selection_1,
});
}
}
}, [waitToUpdateCursor]);
var _b = useRefMask({
value: value,
maskGenerator: maskGenerator,
getCursorPosition: getCursorPosition,
setCursorPosition: setCursorPosition,
onChange: onChange,
keepMask: keepMask,
ref: outerRef,
}), displayValue = _b.displayValue, setDisplayValue = _b.setDisplayValue, ref = _b.ref;
var onChangeText = React.useCallback(function (text) {
var _a, _b, _c, _d, _e;
var position = ((_b = (_a = selectionRef.current) === null || _a === void 0 ? void 0 : _a.start) !== null && _b !== void 0 ? _b : 0) +
((_c = text === null || text === void 0 ? void 0 : text.length) !== null && _c !== void 0 ? _c : 0) -
((_d = displayValue === null || displayValue === void 0 ? void 0 : displayValue.length) !== null && _d !== void 0 ? _d : 0);
var selection = { start: position, end: position };
selectionRef.current = selection;
(_e = ref.current) === null || _e === void 0 ? void 0 : _e.setNativeProps({ selection: selection });
return setDisplayValue(text);
}, [setDisplayValue, ref, displayValue]);
return {
value: displayValue,
onChangeText: onChangeText,
onSelectionChange: onSelectionChange,
ref: ref,
};
};
//# sourceMappingURL=use-native-mask.js.map