UNPKG

react-hook-mask

Version:
67 lines 3.22 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.useNativeMask = void 0; var react_1 = __importDefault(require("react")); var use_ref_mask_1 = require("./use-ref-mask"); 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_1.default.useRef({ start: 0, end: 0 }); var onSelectionChange = react_1.default.useCallback(function (event) { var selection = event.nativeEvent.selection; selectionRef.current = selection; }, []); var getCursorPosition = react_1.default.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_1.default.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 = (0, use_ref_mask_1.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_1.default.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, }; }; exports.useNativeMask = useNativeMask; //# sourceMappingURL=use-native-mask.js.map