@ebay/ebayui-core
Version:
Collection of core eBay components; considered to be the building blocks for all composite structures, pages & apps.
87 lines (86 loc) • 2.84 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_1;
exports.stripNonDigits = stripNonDigits;
function default_1(input, initialMask) {
let mask = initialMask;
const onInput = (ev) => {
updateInputValue(input, mask, input.value, ev.inputType);
};
input.addEventListener("input", onInput);
return {
update(newValue, newMask) {
mask = newMask;
updateInputValue(input, mask, newValue, "");
},
destroy() {
input.removeEventListener("input", onInput);
},
get value() {
return input.value;
},
};
}
function updateInputValue(input, mask, value, inputType) {
const isDelete = /delete.*Backwards/.test(inputType);
const initialPos = input.selectionStart || 0;
const newValue = applyMask(value, mask);
if (value !== newValue) {
input.value = newValue;
const newPosition = resolveCursorPosition(newValue, value, initialPos, isDelete);
if (newPosition !== undefined) {
input.setSelectionRange(newPosition, newPosition);
}
}
}
function stripNonDigits(value) {
return value.replace(/\D+/g, "");
}
function applyMask(value, mask) {
const digits = stripNonDigits(value);
let maskedValue = "";
let currentDigit = 0;
if (digits.length) {
for (const char of mask) {
if (char === "0") {
maskedValue += digits[currentDigit++];
if (currentDigit === digits.length) {
break;
}
}
else
maskedValue += char;
}
if (currentDigit < digits.length) {
maskedValue += " " + digits.slice(currentDigit);
}
}
return maskedValue;
}
function resolveCursorPosition(updatedValue, initialValue, initialPosition, isDelete) {
const cursorAtEnd = initialPosition === initialValue.length;
if (isDelete || !cursorAtEnd) {
const before = initialValue.slice(0, initialPosition);
const after = initialValue.slice(initialPosition);
if (updatedValue.startsWith(before)) {
return initialPosition;
}
else if (updatedValue.endsWith(after)) {
return updatedValue.length - after.length;
}
else {
const relevantChars = stripSpacesAndPunctuation(before);
let pos = 0;
let relevantIndex = 0;
while (relevantIndex < relevantChars.length) {
if (stripSpacesAndPunctuation(updatedValue[pos]))
relevantIndex++;
pos++;
}
return pos;
}
}
}
function stripSpacesAndPunctuation(str) {
return str.replace(/[.,\\/#!$%^&*;:{}=+\-_`~()\s]/g, "");
}