vvv-mask
Version:
42 lines (38 loc) • 1.21 kB
JavaScript
import {masker} from './masker';
import tokensDefault from './tokens';
function event (name) {
let evt = document.createEvent('Event');
evt.initEvent(name, true, true);
return evt;
}
export default function (el, binding, tokens = tokensDefault) {
let config = binding.value;
if (Array.isArray(config) || typeof config === 'string') {
config = {
mask: config,
tokens: tokens,
};
}
el = el.getElementsByTagName('input')[0];
el.oninput = function (evt) {
if (!evt.isTrusted) return;
let position = el.selectionEnd;
let digit = el.value[position-1];
el.value = masker(el.value, config.mask, true, config.tokens);
while (position < el.value.length && el.value.charAt(position-1) !== digit) {
position++;
}
if (el === document.activeElement) {
el.setSelectionRange(position, position);
setTimeout(function () {
el.setSelectionRange(position, position);
}, 0);
}
el.dispatchEvent(event('input'));
};
let newValue = masker(el.value, config.mask, true, config.tokens);
if (newValue !== el.value) {
el.value = newValue;
el.dispatchEvent(event('input'));
}
}