util-helpers
Version:
34 lines (31 loc) • 1.42 kB
JavaScript
import { toString, isArray } from 'ut2';
function calculateCursorPosition(prevPos, prevCtrlValue, rawValue, ctrlValue, options) {
if (options === void 0) { options = {}; }
var _a = options.placeholderChar, placeholderChar = _a === void 0 ? ' ' : _a, _b = options.maskReg, maskReg = _b === void 0 ? /\D/g : _b, type = options.type;
var realCtrlValue = toString(prevCtrlValue);
var realRawValue = toString(rawValue);
var placeholderChars = isArray(placeholderChar) ? placeholderChar : [placeholderChar];
var editLength = realRawValue.length - realCtrlValue.length;
var isAddition = editLength > 0;
var pos = prevPos;
if (isAddition) {
var additionStr = realRawValue.substring(pos - editLength, pos);
var ctrlCharCount = additionStr.replace(maskReg, '').length;
pos -= editLength - ctrlCharCount;
var placeholderCharCount = 0;
while (ctrlCharCount > 0) {
if (placeholderChars.indexOf(ctrlValue.charAt(pos - ctrlCharCount + placeholderCharCount)) !== -1) {
placeholderCharCount++;
}
else {
ctrlCharCount--;
}
}
pos += placeholderCharCount;
}
if ((type === 'mobile' && (pos === 4 || pos === 9)) || (type === 'bankCard' && pos > 0 && pos % 5 === 0)) {
pos -= 1;
}
return pos;
}
export { calculateCursorPosition as default };