New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@coders-tm/vue-number-format

Package Overview
Dependencies
Maintainers
1
Versions
115
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@coders-tm/vue-number-format - npm Package Compare versions

Comparing version 1.1.6 to 1.1.7

dist/index.cjs.js.map

404

dist/index.cjs.js
/**
* Vue Currency Input 1.0.0
* Vue Number Format 1.0.0
* (c) 2018-2021 Dipak Sarkar <hello@dipaksarkar.in> (https://dipaksarkar.in/)
* @license MIT
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var vue = require('vue');
var options = {
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var options = {
prefix: '',

@@ -23,20 +17,27 @@ suffix: '',

null_value: ''
};
/**
};/**
* Number format function
* @param {Object} options
*/
function NumberFormat(config = options) {
this.options = Object.assign(options, config);
function NumberFormat(opt) {
var this$1$1 = this;
if ( opt === void 0 ) opt = options;
this.options = Object.assign(options, opt);
this.input = '';
this.number = '';
this.isClean = false;
this.isNull = (input = this.input) => !this.numberOnly(input, new RegExp('[^0-9]+', 'gi'));
this.clean = (clean = false) => {
this.isClean = clean;
return this
this.isNull = function (input) {
if ( input === void 0 ) input = this$1$1.input;
return !this$1$1.numberOnly(input, new RegExp('[^0-9]+', 'gi'));
};
this.sign = () => {
const sign = (this.input.toString().indexOf('-') >= 0 && this.realNumber() > 0) ? '-' : '';
this.clean = function (clean) {
if ( clean === void 0 ) clean = false;
this$1$1.isClean = clean;
return this$1$1
};
this.sign = function () {
var sign = (this$1$1.input.toString().indexOf('-') >= 0 && this$1$1.realNumber() > 0) ? '-' : '';
return sign

@@ -57,28 +58,31 @@ };

}
this.toNumber = (string) => Number(string);
this.numberOnly = (string, regExp) => string.toString().replace(regExp, '');
this.toNumber = function (string) { return Number(string); };
this.numberOnly = function (string, regExp) { return string.toString().replace(regExp, ''); };
this.isNegative = this.sign() === '-';
this.numbers = () => {
if (this.options.reverseFill) {
this.number = toFixed(this.numberOnly(this.input, /\D+/g), this.options.precision).replace('.', this.options.decimal);
} else if (typeof this.input === 'number') {
this.number = this.toNumber(this.input.toFixed(this.options.precision)).toString().replace('-', '').replace('.', this.options.decimal);
this.numbers = function () {
if (this$1$1.options.reverseFill) {
this$1$1.number = toFixed(this$1$1.numberOnly(this$1$1.input, /\D+/g), this$1$1.options.precision).replace('.', this$1$1.options.decimal);
} else if (typeof this$1$1.input === 'number') {
this$1$1.number = this$1$1.toNumber(this$1$1.input.toFixed(this$1$1.options.precision)).toString().replace('-', '').replace('.', this$1$1.options.decimal);
// eslint-disable-next-line no-restricted-globals
} else if (!isNaN(this.toNumber(this.input))) {
this.number = this.input.replace('-', '').replace('.', this.options.decimal);
} else if (!isNaN(this$1$1.toNumber(this$1$1.input))) {
this$1$1.number = this$1$1.input.replace('-', '').replace('.', this$1$1.options.decimal);
} else {
this.number = this.numberOnly(this.input, new RegExp(`[^0-9\\${this.options.decimal}]+`, 'gi'));
this.number = this.parts(this.number).join(this.options.decimal);
this$1$1.number = this$1$1.numberOnly(this$1$1.input, new RegExp(("[^0-9\\" + (this$1$1.options.decimal) + "]+"), 'gi'));
this$1$1.number = this$1$1.parts(this$1$1.number).join(this$1$1.options.decimal);
}
return this.number
return this$1$1.number
};
this.realNumber = () => this.toNumber(this.numbers().toString().replace(this.options.decimal, '.'));
this.parts = (number = '', decimal = this.options.decimal) => {
this.realNumber = function () { return this$1$1.toNumber(this$1$1.numbers().toString().replace(this$1$1.options.decimal, '.')); };
this.parts = function (number, decimal) {
if ( number === void 0 ) number = '';
if ( decimal === void 0 ) decimal = this$1$1.options.decimal;
var parts = number.toString().split(decimal);
parts[0] = this.toNumber(parts[0]) || 0;
parts[0] = this$1$1.toNumber(parts[0]) || 0;
if (parts.length > 1) {
parts[1] = parts.slice(1, parts.length).join('');
parts = parts.slice(0, 2);
if (parts[1].length > this.options.precision) {
parts[1] = this.toNumber(`.${parts[1]}`).toFixed(this.options.precision).toString().replace('0.', '');
if (parts[1].length > this$1$1.options.precision) {
parts[1] = this$1$1.toNumber(("." + (parts[1]))).toFixed(this$1$1.options.precision).toString().replace('0.', '');
}

@@ -88,10 +92,10 @@ }

};
this.addSeparator = () => {
var parts = this.numbers().split(this.options.decimal);
parts[0] = parts[0].toString().replace(/(\d)(?=(?:\d{3})+\b)/gm, `$1${this.options.separator}`);
if (this.isClean) {
parts[1] = this.toNumber(`.${parts[1]}`).toString().replace('0.', '');
return parts[1] && parts[1] > 0 ? parts.join(this.options.decimal) : parts[0]
this.addSeparator = function () {
var parts = this$1$1.numbers().split(this$1$1.options.decimal);
parts[0] = parts[0].toString().replace(/(\d)(?=(?:\d{3})+\b)/gm, ("$1" + (this$1$1.options.separator)));
if (this$1$1.isClean) {
parts[1] = this$1$1.toNumber(("." + (parts[1]))).toString().replace('0.', '');
return parts[1] && parts[1] > 0 ? parts.join(this$1$1.options.decimal) : parts[0]
}
return parts.join(this.options.decimal)
return parts.join(this$1$1.options.decimal)
};

@@ -103,7 +107,7 @@ /**

*/
this.format = (input) => {
if (input === '') return this.options.null_value
this.input = input;
if (this.isNull()) return this.options.null_value
return this.sign() + this.options.prefix + this.addSeparator() + this.options.suffix
this.format = function (input) {
if (input === '') { return this$1$1.options.null_value }
this$1$1.input = input;
if (this$1$1.isNull()) { return this$1$1.options.null_value }
return this$1$1.sign() + this$1$1.options.prefix + this$1$1.addSeparator() + this$1$1.options.suffix
};

@@ -115,11 +119,11 @@ /**

*/
this.unformat = (input) => {
if (input === '') return this.options.null_value
this.input = input;
if (this.isNull()) return this.options.null_value
return this.toNumber(this.sign() + this.realNumber())
this.unformat = function (input) {
if (input === '') { return this$1$1.options.null_value }
this$1$1.input = input;
if (this$1$1.isNull()) { return this$1$1.options.null_value }
return this$1$1.toNumber(this$1$1.sign() + this$1$1.realNumber())
};
}
}// import options from './options'
const CONFIG_KEY$1 = '__input-facade__';
var CONFIG_KEY$1 = '__input-facade__';

@@ -137,2 +141,16 @@ /**

}
/**
* Transform an array or string config into an object
*
* @param {object} config The format config object
* @param {object} modifiers An object of modifier flags that can influence the formating process
*/
function normalizeConfig(defaults, extras) {
defaults = defaults || {};
extras = extras || {};
return Object.keys(defaults).concat(Object.keys(extras)).reduce(function (acc, val) {
acc[val] = extras[val] === undefined ? defaults[val] : extras[val];
return acc
}, {})
}

@@ -146,3 +164,3 @@ /**

function getInputElement(el) {
const inputElement = el instanceof HTMLInputElement ? el : el.querySelector('input');
var inputElement = el instanceof HTMLInputElement ? el : el.querySelector('input');

@@ -163,3 +181,3 @@ /* istanbul ignore next */

function updateCursor(el, position) {
const setSelectionRange = () => { el.setSelectionRange(position, position); };
var setSelectionRange = function () { el.setSelectionRange(position, position); };
setSelectionRange();

@@ -178,13 +196,21 @@ // Android Fix

*/
function updateValue(el, vnode, { emit = true, force = false, clean = false } = {}) {
const { config } = el[CONFIG_KEY$1];
let { oldValue } = el[CONFIG_KEY$1];
let currentValue = vnode && vnode.props ? vnode.props.value : el.value;
function updateValue(el, vnode, ref) {
if ( ref === void 0 ) ref = {};
var emit = ref.emit; if ( emit === void 0 ) emit = true;
var force = ref.force; if ( force === void 0 ) force = false;
var clean = ref.clean; if ( clean === void 0 ) clean = false;
var ref$1 = el[CONFIG_KEY$1];
var config = ref$1.config;
var ref$2 = el[CONFIG_KEY$1];
var oldValue = ref$2.oldValue;
var currentValue = vnode && vnode.data.model ? vnode.data.model.value : el.value;
oldValue = oldValue || '';
currentValue = currentValue || '';
const number = new NumberFormat(config).clean(clean);
let masked = number.format(currentValue);
let unmasked = number.unformat(currentValue);
var number = new NumberFormat(config).clean(clean);
var masked = number.format(currentValue);
var unmasked = number.unformat(currentValue);

@@ -222,3 +248,4 @@ // check value with in range max and min value

function inputHandler(event) {
const { target, detail } = event;
var target = event.target;
var detail = event.detail;
// We dont need to run this method on the event we emit (prevent event loop)

@@ -233,4 +260,6 @@ if (detail && detail.facade) {

let positionFromEnd = target.value.length - target.selectionEnd;
const { oldValue, config } = target[CONFIG_KEY$1];
var positionFromEnd = target.value.length - target.selectionEnd;
var ref = target[CONFIG_KEY$1];
var oldValue = ref.oldValue;
var config = ref.config;

@@ -242,6 +271,6 @@ updateValue(target, null, { emit: false });

positionFromEnd = Math.max(positionFromEnd, config.prefix.length + 1);
const decimalPosition = target.value.indexOf(config.decimal);
const diff = positionFromEnd - decimalPosition;
const maxLength = target.value.length - config.suffix.length;
const positionAfterDecimal = positionFromEnd + 1;
var decimalPosition = target.value.indexOf(config.decimal);
var diff = positionFromEnd - decimalPosition;
var maxLength = target.value.length - config.suffix.length;
var positionAfterDecimal = positionFromEnd + 1;
if (decimalPosition > 0 && diff > 0 && positionAfterDecimal <= maxLength) {

@@ -263,3 +292,4 @@ positionFromEnd = positionAfterDecimal;

function blurHandler(event) {
const { target, detail } = event;
var target = event.target;
var detail = event.detail;
// We dont need to run this method on the event we emit (prevent event loop)

@@ -270,3 +300,4 @@ if (detail && detail.facade) {

const { oldValue } = target[CONFIG_KEY$1];
var ref = target[CONFIG_KEY$1];
var oldValue = ref.oldValue;

@@ -278,11 +309,12 @@ updateValue(target, null, { force: true, clean: true });

}
}
}var CONFIG_KEY = CONFIG_KEY$1;
const CONFIG_KEY = CONFIG_KEY$1;
var VNumber = {
bind: function (el, ref, vnode) {
var value = ref.value;
var modifiers = ref.modifiers;
var directive = {
beforeMount: (el, { value, modifiers }, vnode) => {
el = getInputElement(el);
const config = Object.assign({}, options, value, modifiers);
el[CONFIG_KEY] = { config };
var config = normalizeConfig(options, Object.assign(value, modifiers));
el[CONFIG_KEY] = { config: config };
// set initial value

@@ -292,20 +324,20 @@ updateValue(el, vnode, { force: config.prefill });

mounted: (el) => {
inserted: function (el) {
el = getInputElement(el);
const option = el[CONFIG_KEY];
const { config } = option;
var option = el[CONFIG_KEY];
var config = option.config;
// prefer adding event listener to parent element to avoid Firefox bug which does not
// execute `useCapture: true` event handlers before non-capturing event handlers
const handlerOwner = el.parentElement || el;
var handlerOwner = el.parentElement || el;
// use anonymous event handler to avoid inadvertently removing masking for all inputs within a container
const oninput = (e) => inputHandler(e);
var oninput = function (e) { return inputHandler(e); };
handlerOwner.addEventListener('input', oninput, true);
el.onblur = (e) => blurHandler(e);
el.onblur = function (e) { return blurHandler(e); };
// check decimal key and insert to current element
// updated cursor position after format the value
el.onkeydown = (e) => {
el.onkeydown = function (e) {
if ([110, 190].includes(e.keyCode) || e.key === config.decimal) {

@@ -319,10 +351,15 @@ e.preventDefault();

option.cleanup = () => handlerOwner.removeEventListener('input', oninput, true);
option.cleanup = function () { return handlerOwner.removeEventListener('input', oninput, true); };
},
updated: (el, { value, oldValue, modifiers }, vnode) => {
update: function (el, ref, vnode) {
var value = ref.value;
var oldValue = ref.oldValue;
var modifiers = ref.modifiers;
el = getInputElement(el);
if (value !== oldValue) {
const { config } = el[CONFIG_KEY];
el[CONFIG_KEY].config = Object.assign({}, config, value, modifiers);
var ref$1 = el[CONFIG_KEY];
var config = ref$1.config;
el[CONFIG_KEY].config = normalizeConfig(config, Object.assign(value, modifiers));
updateValue(el, vnode, { force: true });

@@ -334,15 +371,16 @@ } else {

unmounted: (el) => {
unbind: function (el) {
getInputElement(el)[CONFIG_KEY].cleanup();
}
};
};//
var script = {
props: {
modelValue: {
required: true
value: {
required: true,
type: [Number, String]
},
null_value: {
type: [Number, String],
default: () => options.null_value
default: function () { return options.null_value; }
},

@@ -359,27 +397,27 @@ masked: {

type: Number,
default: () => options.precision
default: function () { return options.precision; }
},
decimal: {
type: String,
default: () => options.decimal
default: function () { return options.decimal; }
},
separator: {
type: String,
default: () => options.separator
default: function () { return options.separator; }
},
prefix: {
type: String,
default: () => options.prefix
default: function () { return options.prefix; }
},
suffix: {
type: String,
default: () => options.suffix
default: function () { return options.suffix; }
}
},
directives: {
number: directive
number: VNumber
},
data() {
data: function data() {
return {
maskedValue: this.modelValue,
maskedValue: this.value,
unmaskedValue: null

@@ -389,3 +427,3 @@ }

watch: {
masked() {
masked: function masked() {
this.$emit('input', this.emittedValue);

@@ -395,54 +433,134 @@ }

methods: {
input({ target }) {
input: function input(ref) {
var target = ref.target;
this.maskedValue = target.value;
this.unmaskedValue = target.unmaskedValue;
this.$emit('update:modelValue', this.emittedValue);
this.$emit('input', this.emittedValue);
},
change() {
this.$emit('update:modelValue', this.emittedValue);
change: function change() {
this.$emit('change', this.emittedValue);
}
},
computed: {
emittedValue() {
emittedValue: function emittedValue() {
return this.masked ? this.maskedValue : this.unmaskedValue
},
config() {
config: function config() {
return this.$props
}
}
};
};function normalizeComponent(template, style, script, scopeId, isFunctionalTemplate, moduleIdentifier /* server only */, shadowMode, createInjector, createInjectorSSR, createInjectorShadow) {
if (typeof shadowMode !== 'boolean') {
createInjectorSSR = createInjector;
createInjector = shadowMode;
shadowMode = false;
}
// Vue.extend constructor export interop.
var options = typeof script === 'function' ? script.options : script;
// render functions
if (template && template.render) {
options.render = template.render;
options.staticRenderFns = template.staticRenderFns;
options._compiled = true;
// functional template
if (isFunctionalTemplate) {
options.functional = true;
}
}
// scopedId
if (scopeId) {
options._scopeId = scopeId;
}
var hook;
if (moduleIdentifier) {
// server build
hook = function (context) {
// 2.3 injection
context =
context || // cached call
(this.$vnode && this.$vnode.ssrContext) || // stateful
(this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext); // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__;
}
// inject component styles
if (style) {
style.call(this, createInjectorSSR(context));
}
// register component module identifier for async chunk inference
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier);
}
};
// used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook;
}
else if (style) {
hook = shadowMode
? function (context) {
style.call(this, createInjectorShadow(context, this.$root.$options.shadowRoot));
}
: function (context) {
style.call(this, createInjector(context));
};
}
if (hook) {
if (options.functional) {
// register for functional component in vue file
var originalRender = options.render;
options.render = function renderWithStyleInjection(h, context) {
hook.call(context);
return originalRender(h, context);
};
}
else {
// inject component registration as beforeCreate hook
var existing = options.beforeCreate;
options.beforeCreate = existing ? [].concat(existing, hook) : [hook];
}
}
return script;
}/* script */
var __vue_script__ = script;
const _hoisted_1 = ["value"];
/* template */
var __vue_render__ = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('input',{directives:[{name:"number",rawName:"v-number",value:(_vm.config),expression:"config"}],staticClass:"v-number",attrs:{"type":"text","autocomplete":"off"},domProps:{"value":_vm.maskedValue},on:{"change":_vm.change,"input":_vm.input}},[])};
var __vue_staticRenderFns__ = [];
function render(_ctx, _cache, $props, $setup, $data, $options) {
const _directive_number = vue.resolveDirective("number");
/* style */
var __vue_inject_styles__ = undefined;
/* scoped */
var __vue_scope_id__ = undefined;
/* module identifier */
var __vue_module_identifier__ = "data-v-24c3497f";
/* functional template */
var __vue_is_functional_template__ = false;
/* style inject */
/* style inject SSR */
/* style inject shadow dom */
return vue.withDirectives((vue.openBlock(), vue.createElementBlock("input", {
type: "text",
autocomplete: "off",
value: $data.maskedValue,
onChange: _cache[0] || (_cache[0] = (...args) => ($options.change && $options.change(...args))),
onInput: _cache[1] || (_cache[1] = (...args) => ($options.input && $options.input(...args))),
class: "v-number"
}, null, 40 /* PROPS, HYDRATE_EVENTS */, _hoisted_1)), [
[_directive_number, $options.config]
])
}
script.render = render;
script.__file = "src/component.vue";
var index = {
install(app, config) {
if (config) {
Object.assign(options, config);
}
app.directive('number', directive);
app.component('number', script);
var __vue_component__ = /*#__PURE__*/normalizeComponent(
{ render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ },
__vue_inject_styles__,
__vue_script__,
__vue_scope_id__,
__vue_is_functional_template__,
__vue_module_identifier__,
false,
undefined,
undefined,
undefined
);function install(Vue, globalOptions) {
if (globalOptions) {
Object.assign(options, globalOptions);
}
};
exports.component = script;
exports['default'] = index;
exports.directive = directive;
exports.options = options;
Vue.directive('number', VNumber);
Vue.component('number', __vue_component__);
}exports.Number=__vue_component__;exports.VNumber=VNumber;exports['default']=install;exports.options=options;//# sourceMappingURL=index.cjs.js.map
/**
* Vue Currency Input 1.0.0
* Vue Number Format 1.0.0
* (c) 2018-2021 Dipak Sarkar <hello@dipaksarkar.in> (https://dipaksarkar.in/)
* @license MIT
*/
import { resolveDirective, withDirectives, openBlock, createElementBlock } from 'vue';
var options = {
prefix: '',
suffix: '',
separator: ',',
decimal: '.',
precision: 2,
prefill: true,
reverseFill: false,
min: false,
max: false,
null_value: ''
};
/**
* Number format function
* @param {Object} options
*/
function NumberFormat(config = options) {
this.options = Object.assign(options, config);
this.input = '';
this.number = '';
this.isClean = false;
this.isNull = (input = this.input) => !this.numberOnly(input, new RegExp('[^0-9]+', 'gi'));
this.clean = (clean = false) => {
this.isClean = clean;
return this
};
this.sign = () => {
const sign = (this.input.toString().indexOf('-') >= 0 && this.realNumber() > 0) ? '-' : '';
return sign
};
function between(min, n, max) {
return Math.max(min, Math.min(n, max))
}
// Uncaught RangeError: toFixed() digits argument must be between 0 and 20 at Number.toFixed
function fixed(precision) {
return between(0, precision, 20)
}
function toFixed(numbers, precision) {
// eslint-disable-next-line no-restricted-properties
var exp = Math.pow(10, precision);
var float = parseFloat(numbers) / exp;
return float.toFixed(fixed(precision))
}
this.toNumber = (string) => Number(string);
this.numberOnly = (string, regExp) => string.toString().replace(regExp, '');
this.isNegative = this.sign() === '-';
this.numbers = () => {
if (this.options.reverseFill) {
this.number = toFixed(this.numberOnly(this.input, /\D+/g), this.options.precision).replace('.', this.options.decimal);
} else if (typeof this.input === 'number') {
this.number = this.toNumber(this.input.toFixed(this.options.precision)).toString().replace('-', '').replace('.', this.options.decimal);
// eslint-disable-next-line no-restricted-globals
} else if (!isNaN(this.toNumber(this.input))) {
this.number = this.input.replace('-', '').replace('.', this.options.decimal);
} else {
this.number = this.numberOnly(this.input, new RegExp(`[^0-9\\${this.options.decimal}]+`, 'gi'));
this.number = this.parts(this.number).join(this.options.decimal);
}
return this.number
};
this.realNumber = () => this.toNumber(this.numbers().toString().replace(this.options.decimal, '.'));
this.parts = (number = '', decimal = this.options.decimal) => {
var parts = number.toString().split(decimal);
parts[0] = this.toNumber(parts[0]) || 0;
if (parts.length > 1) {
parts[1] = parts.slice(1, parts.length).join('');
parts = parts.slice(0, 2);
if (parts[1].length > this.options.precision) {
parts[1] = this.toNumber(`.${parts[1]}`).toFixed(this.options.precision).toString().replace('0.', '');
}
}
return parts.slice(0, 2)
};
this.addSeparator = () => {
var parts = this.numbers().split(this.options.decimal);
parts[0] = parts[0].toString().replace(/(\d)(?=(?:\d{3})+\b)/gm, `$1${this.options.separator}`);
if (this.isClean) {
parts[1] = this.toNumber(`.${parts[1]}`).toString().replace('0.', '');
return parts[1] && parts[1] > 0 ? parts.join(this.options.decimal) : parts[0]
}
return parts.join(this.options.decimal)
};
/**
* Format the input with default config if there is no constructor config
* @param {Number, String} input
* @return {String}
*/
this.format = (input) => {
if (input === '') return this.options.null_value
this.input = input;
if (this.isNull()) return this.options.null_value
return this.sign() + this.options.prefix + this.addSeparator() + this.options.suffix
};
/**
* Unformat the input with default config if there is no constructor config
* @param {Number, String} input
* @return {String}
*/
this.unformat = (input) => {
if (input === '') return this.options.null_value
this.input = input;
if (this.isNull()) return this.options.null_value
return this.toNumber(this.sign() + this.realNumber())
};
}
const CONFIG_KEY$1 = '__input-facade__';
/**
* Creates a CustomEvent('input') with detail = { facade: true }
* used as a way to identify our own input event
*/
function FacadeInputEvent() {
return new CustomEvent('input', {
bubbles: true,
cancelable: true,
detail: { facade: true }
})
}
/**
* ensure that the element we're attaching to is an input element
* if not try to find an input element in this elements childrens
*
* @param {HTMLInputElement} el
*/
function getInputElement(el) {
const inputElement = el instanceof HTMLInputElement ? el : el.querySelector('input');
/* istanbul ignore next */
if (!inputElement) {
throw new Error('facade directive requires an input element')
}
return inputElement
}
/**
* Updates the cursor position to the right place after the masking rule was applied
* @param {HTMLElement} el
* @param {Number} position
*/
function updateCursor(el, position) {
const setSelectionRange = () => { el.setSelectionRange(position, position); };
setSelectionRange();
// Android Fix
setTimeout(setSelectionRange(), 0);
}
/**
* Updates the element's value and unmasked value based on the masking config rules
*
* @param {HTMLInputElement} el The input element to update
* @param {object} [options]
* @param {Boolean} options.emit Wether to dispatch a new InputEvent or not
* @param {Boolean} options.force Forces the update even if the old value and the new value are the same
*/
function updateValue(el, vnode, { emit = true, force = false, clean = false } = {}) {
const { config } = el[CONFIG_KEY$1];
let { oldValue } = el[CONFIG_KEY$1];
let currentValue = vnode && vnode.props ? vnode.props.value : el.value;
oldValue = oldValue || '';
currentValue = currentValue || '';
const number = new NumberFormat(config).clean(clean);
let masked = number.format(currentValue);
let unmasked = number.unformat(currentValue);
// check value with in range max and min value
if (clean) {
if (config.max && unmasked > config.max) {
masked = number.format(config.max);
unmasked = number.unformat(config.max);
} else if (config.min && unmasked < config.min) {
masked = number.format(config.min);
unmasked = number.unformat(config.min);
}
}
if (force || oldValue !== currentValue) {
el[CONFIG_KEY$1].oldValue = masked;
el.unmaskedValue = unmasked;
// safari makes the cursor jump to the end if el.value gets assign even if to the same value
if (el.value !== masked) {
el.value = masked;
}
// this part needs to be outside the above IF statement for vuetify in firefox
// drawback is that we endup with two's input events in firefox
return emit && el.dispatchEvent(FacadeInputEvent())
}
}
/**
* Input event handler
*
* @param {Event} event The event object
*/
function inputHandler(event) {
const { target, detail } = event;
// We dont need to run this method on the event we emit (prevent event loop)
if (detail && detail.facade) {
return false
}
// since we will be emitting our own custom input event
// we can stop propagation of this native event
event.stopPropagation();
let positionFromEnd = target.value.length - target.selectionEnd;
const { oldValue, config } = target[CONFIG_KEY$1];
updateValue(target, null, { emit: false });
// updated cursor position
positionFromEnd = Math.max(positionFromEnd, config.suffix.length);
positionFromEnd = target.value.length - positionFromEnd;
positionFromEnd = Math.max(positionFromEnd, config.prefix.length + 1);
const decimalPosition = target.value.indexOf(config.decimal);
const diff = positionFromEnd - decimalPosition;
const maxLength = target.value.length - config.suffix.length;
const positionAfterDecimal = positionFromEnd + 1;
if (decimalPosition > 0 && diff > 0 && positionAfterDecimal <= maxLength) {
positionFromEnd = positionAfterDecimal;
}
updateCursor(target, positionFromEnd);
if (oldValue !== target.value) {
target.dispatchEvent(FacadeInputEvent());
}
}
/**
* Blur event handler
*
* @param {Event} event The event object
*/
function blurHandler(event) {
const { target, detail } = event;
// We dont need to run this method on the event we emit (prevent event loop)
if (detail && detail.facade) {
return false
}
const { oldValue } = target[CONFIG_KEY$1];
updateValue(target, null, { force: true, clean: true });
if (oldValue !== target.value) {
target.dispatchEvent(FacadeInputEvent());
}
}
const CONFIG_KEY = CONFIG_KEY$1;
var directive = {
beforeMount: (el, { value, modifiers }, vnode) => {
el = getInputElement(el);
const config = Object.assign({}, options, value, modifiers);
el[CONFIG_KEY] = { config };
// set initial value
updateValue(el, vnode, { force: config.prefill });
},
mounted: (el) => {
el = getInputElement(el);
const option = el[CONFIG_KEY];
const { config } = option;
// prefer adding event listener to parent element to avoid Firefox bug which does not
// execute `useCapture: true` event handlers before non-capturing event handlers
const handlerOwner = el.parentElement || el;
// use anonymous event handler to avoid inadvertently removing masking for all inputs within a container
const oninput = (e) => inputHandler(e);
handlerOwner.addEventListener('input', oninput, true);
el.onblur = (e) => blurHandler(e);
// check decimal key and insert to current element
// updated cursor position after format the value
el.onkeydown = (e) => {
if ([110, 190].includes(e.keyCode) || e.key === config.decimal) {
e.preventDefault();
el.setRangeText(config.decimal);
el.dispatchEvent(new Event('input'));
updateCursor(el, el.value.indexOf(config.decimal) + 1);
}
};
option.cleanup = () => handlerOwner.removeEventListener('input', oninput, true);
},
updated: (el, { value, oldValue, modifiers }, vnode) => {
el = getInputElement(el);
if (value !== oldValue) {
const { config } = el[CONFIG_KEY];
el[CONFIG_KEY].config = Object.assign({}, config, value, modifiers);
updateValue(el, vnode, { force: true });
} else {
updateValue(el, vnode);
}
},
unmounted: (el) => {
getInputElement(el)[CONFIG_KEY].cleanup();
}
};
var script = {
props: {
modelValue: {
required: true
},
null_value: {
type: [Number, String],
default: () => options.null_value
},
masked: {
type: Boolean,
default: false
},
reverseFill: {
type: Boolean,
default: options.reverseFill
},
precision: {
type: Number,
default: () => options.precision
},
decimal: {
type: String,
default: () => options.decimal
},
separator: {
type: String,
default: () => options.separator
},
prefix: {
type: String,
default: () => options.prefix
},
suffix: {
type: String,
default: () => options.suffix
}
},
directives: {
number: directive
},
data() {
return {
maskedValue: this.modelValue,
unmaskedValue: null
}
},
watch: {
masked() {
this.$emit('input', this.emittedValue);
}
},
methods: {
input({ target }) {
this.maskedValue = target.value;
this.unmaskedValue = target.unmaskedValue;
this.$emit('update:modelValue', this.emittedValue);
},
change() {
this.$emit('update:modelValue', this.emittedValue);
}
},
computed: {
emittedValue() {
return this.masked ? this.maskedValue : this.unmaskedValue
},
config() {
return this.$props
}
}
};
const _hoisted_1 = ["value"];
function render(_ctx, _cache, $props, $setup, $data, $options) {
const _directive_number = resolveDirective("number");
return withDirectives((openBlock(), createElementBlock("input", {
type: "text",
autocomplete: "off",
value: $data.maskedValue,
onChange: _cache[0] || (_cache[0] = (...args) => ($options.change && $options.change(...args))),
onInput: _cache[1] || (_cache[1] = (...args) => ($options.input && $options.input(...args))),
class: "v-number"
}, null, 40 /* PROPS, HYDRATE_EVENTS */, _hoisted_1)), [
[_directive_number, $options.config]
])
}
script.render = render;
script.__file = "src/component.vue";
var index = {
install(app, config) {
if (config) {
Object.assign(options, config);
}
app.directive('number', directive);
app.component('number', script);
}
};
export { script as component, index as default, directive, options };
var e={prefix:"",suffix:"",separator:",",decimal:".",precision:2,prefill:!0,reverseFill:!1,min:!1,max:!1,null_value:""};function n(n){var t=this;function i(e){return n=0,t=e,i=20,Math.max(n,Math.min(t,i));var n,t,i}void 0===n&&(n=e),this.options=Object.assign(e,n),this.input="",this.number="",this.isClean=!1,this.isNull=function(e){return void 0===e&&(e=t.input),!t.numberOnly(e,new RegExp("[^0-9]+","gi"))},this.clean=function(e){return void 0===e&&(e=!1),t.isClean=e,t},this.sign=function(){return t.input.toString().indexOf("-")>=0&&t.realNumber()>0?"-":""},this.toNumber=function(e){return Number(e)},this.numberOnly=function(e,n){return e.toString().replace(n,"")},this.isNegative="-"===this.sign(),this.numbers=function(){var e,n,r;return t.options.reverseFill?t.number=(e=t.numberOnly(t.input,/\D+/g),n=t.options.precision,r=Math.pow(10,n),(parseFloat(e)/r).toFixed(i(n))).replace(".",t.options.decimal):"number"==typeof t.input?t.number=t.toNumber(t.input.toFixed(t.options.precision)).toString().replace("-","").replace(".",t.options.decimal):isNaN(t.toNumber(t.input))?(t.number=t.numberOnly(t.input,new RegExp("[^0-9\\"+t.options.decimal+"]+","gi")),t.number=t.parts(t.number).join(t.options.decimal)):t.number=t.input.replace("-","").replace(".",t.options.decimal),t.number},this.realNumber=function(){return t.toNumber(t.numbers().toString().replace(t.options.decimal,"."))},this.parts=function(e,n){void 0===e&&(e=""),void 0===n&&(n=t.options.decimal);var i=e.toString().split(n);return i[0]=t.toNumber(i[0])||0,i.length>1&&(i[1]=i.slice(1,i.length).join(""),(i=i.slice(0,2))[1].length>t.options.precision&&(i[1]=t.toNumber("."+i[1]).toFixed(t.options.precision).toString().replace("0.",""))),i.slice(0,2)},this.addSeparator=function(){var e=t.numbers().split(t.options.decimal);return e[0]=e[0].toString().replace(/(\d)(?=(?:\d{3})+\b)/gm,"$1"+t.options.separator),t.isClean?(e[1]=t.toNumber("."+e[1]).toString().replace("0.",""),e[1]&&e[1]>0?e.join(t.options.decimal):e[0]):e.join(t.options.decimal)},this.format=function(e){return""===e?t.options.null_value:(t.input=e,t.isNull()?t.options.null_value:t.sign()+t.options.prefix+t.addSeparator()+t.options.suffix)},this.unformat=function(e){return""===e?t.options.null_value:(t.input=e,t.isNull()?t.options.null_value:t.toNumber(t.sign()+t.realNumber()))}}var t="__input-facade__";function i(){return new CustomEvent("input",{bubbles:!0,cancelable:!0,detail:{facade:!0}})}function r(e,n){return e=e||{},n=n||{},Object.keys(e).concat(Object.keys(n)).reduce((function(t,i){return t[i]=void 0===n[i]?e[i]:n[i],t}),{})}function a(e){var n=e instanceof HTMLInputElement?e:e.querySelector("input");if(!n)throw new Error("facade directive requires an input element");return n}function o(e,n){var t=function(){e.setSelectionRange(n,n)};t(),setTimeout(t(),0)}function u(e,r,a){void 0===a&&(a={});var o=a.emit;void 0===o&&(o=!0);var u=a.force;void 0===u&&(u=!1);var s=a.clean;void 0===s&&(s=!1);var l=e[t].config,c=e[t].oldValue,d=r&&r.data.model?r.data.model.value:e.value;c=c||"",d=d||"";var f=new n(l).clean(s),p=f.format(d),m=f.unformat(d);if(s&&(l.max&&m>l.max?(p=f.format(l.max),m=f.unformat(l.max)):l.min&&m<l.min&&(p=f.format(l.min),m=f.unformat(l.min))),u||c!==d)return e[t].oldValue=p,e.unmaskedValue=m,e.value!==p&&(e.value=p),o&&e.dispatchEvent(i())}var s=t,l={bind:function(n,t,i){var o=t.value,l=t.modifiers;n=a(n);var c=r(e,Object.assign(o,l));n[s]={config:c},u(n,i,{force:c.prefill})},inserted:function(e){var n=(e=a(e))[s],r=n.config,l=e.parentElement||e,c=function(e){return function(e){var n=e.target,r=e.detail;if(r&&r.facade)return!1;e.stopPropagation();var a=n.value.length-n.selectionEnd,s=n[t],l=s.oldValue,c=s.config;u(n,null,{emit:!1}),a=Math.max(a,c.suffix.length),a=n.value.length-a,a=Math.max(a,c.prefix.length+1);var d=n.value.indexOf(c.decimal),f=a-d,p=n.value.length-c.suffix.length,m=a+1;d>0&&f>0&&m<=p&&(a=m),o(n,a),l!==n.value&&n.dispatchEvent(i())}(e)};l.addEventListener("input",c,!0),e.onblur=function(e){return function(e){var n=e.target,r=e.detail;if(r&&r.facade)return!1;var a=n[t].oldValue;u(n,null,{force:!0,clean:!0}),a!==n.value&&n.dispatchEvent(i())}(e)},e.onkeydown=function(n){([110,190].includes(n.keyCode)||n.key===r.decimal)&&(n.preventDefault(),e.setRangeText(r.decimal),e.dispatchEvent(new Event("input")),o(e,e.value.indexOf(r.decimal)+1))},n.cleanup=function(){return l.removeEventListener("input",c,!0)}},update:function(e,n,t){var i=n.value,o=n.oldValue,l=n.modifiers;if(e=a(e),i!==o){var c=e[s].config;e[s].config=r(c,Object.assign(i,l)),u(e,t,{force:!0})}else u(e,t)},unbind:function(e){a(e)[s].cleanup()}};function c(e,n,t,i,r,a,o,u,s,l){"boolean"!=typeof o&&(s=u,u=o,o=!1);var c,d="function"==typeof t?t.options:t;if(e&&e.render&&(d.render=e.render,d.staticRenderFns=e.staticRenderFns,d._compiled=!0,r&&(d.functional=!0)),i&&(d._scopeId=i),a?(c=function(e){(e=e||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(e=__VUE_SSR_CONTEXT__),n&&n.call(this,s(e)),e&&e._registeredComponents&&e._registeredComponents.add(a)},d._ssrRegister=c):n&&(c=o?function(e){n.call(this,l(e,this.$root.$options.shadowRoot))}:function(e){n.call(this,u(e))}),c)if(d.functional){var f=d.render;d.render=function(e,n){return c.call(n),f(e,n)}}else{var p=d.beforeCreate;d.beforeCreate=p?[].concat(p,c):[c]}return t}var d=c({render:function(){var e=this.$createElement;return(this._self._c||e)("input",{directives:[{name:"number",rawName:"v-number",value:this.config,expression:"config"}],staticClass:"v-number",attrs:{type:"text",autocomplete:"off"},domProps:{value:this.maskedValue},on:{change:this.change,input:this.input}})},staticRenderFns:[]},void 0,{props:{value:{required:!0,type:[Number,String]},null_value:{type:[Number,String],default:function(){return e.null_value}},masked:{type:Boolean,default:!1},reverseFill:{type:Boolean,default:e.reverseFill},precision:{type:Number,default:function(){return e.precision}},decimal:{type:String,default:function(){return e.decimal}},separator:{type:String,default:function(){return e.separator}},prefix:{type:String,default:function(){return e.prefix}},suffix:{type:String,default:function(){return e.suffix}}},directives:{number:l},data:function(){return{maskedValue:this.value,unmaskedValue:null}},watch:{masked:function(){this.$emit("input",this.emittedValue)}},methods:{input:function(e){var n=e.target;this.maskedValue=n.value,this.unmaskedValue=n.unmaskedValue,this.$emit("input",this.emittedValue)},change:function(){this.$emit("change",this.emittedValue)}},computed:{emittedValue:function(){return this.masked?this.maskedValue:this.unmaskedValue},config:function(){return this.$props}}},void 0,!1,void 0,!1,void 0,void 0,void 0);function f(n,t){t&&Object.assign(e,t),n.directive("number",l),n.component("number",d)}export{d as Number,l as VNumber,f as default,e as options};
//# sourceMappingURL=index.esm.js.map
{
"name": "@coders-tm/vue-number-format",
"version": "1.1.6",
"version": "1.1.7",
"private": false,

@@ -18,4 +18,4 @@ "description": "Easy formatted numbers, currency and percentage with input/directive mask for Vue.js",

"build": "rollup --c rollup.config.js",
"docs:build": "vitepress build docs",
"docs:dev": "vitepress dev docs",
"docs:build": "vuepress build docs",
"docs:dev": "vuepress dev docs",
"test": "jest tests/*",

@@ -25,2 +25,41 @@ "lint": "eslint 'src/**/*.{js,vue}'",

},
"devDependencies": {
"@babel/core": "^7.9.0",
"@babel/preset-env": "^7.9.5",
"@vue/cli-plugin-unit-jest": "^4.5.13",
"@vue/cli-service": "^4.5.13",
"@vue/test-utils": "^1.2.2",
"@vuedoc/md": "^1.6.0",
"@vuepress/plugin-back-to-top": "^1.8.2",
"@vuepress/plugin-google-analytics": "^1.8.2",
"@vuepress/plugin-medium-zoom": "^1.8.2",
"@vuepress/plugin-register-components": "^1.4.1",
"babel-core": "^6.26.3",
"babel-jest": "^25.3.0",
"babel-preset-env": "^1.7.0",
"babel-preset-vue": "^2.0.2",
"eslint": "^6.8.0",
"eslint-config-airbnb-base": "^14.1.0",
"eslint-plugin-import": "^2.20.2",
"eslint-plugin-vue": "^6.2.2",
"jest": "^25.3.0",
"node-fetch": "^2.6.0",
"npm-run-all": "^4.1.5",
"postcss": "6.0",
"quasar": "^1.11.3",
"rollup": "^2.6.1",
"rollup-plugin-buble": "^0.19.8",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-css-only": "^2.0.0",
"rollup-plugin-filesize": "^9.1.1",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-replace": "^2.2.0",
"rollup-plugin-terser": "^5.3.0",
"rollup-plugin-vue": "^5.1.6",
"vue": "^2.6.11",
"vue-jest": "^3.0.5",
"vue-template-compiler": "^2.6.11",
"vuepress": "^1.8.2",
"vuepress-plugin-demo-code": "^0.5.0"
},
"bugs": {

@@ -49,24 +88,3 @@ "url": "https://github.com/coders-tm/vue-number-format/issues"

"@coders-tm:registry": "https://npm.pkg.github.com"
},
"devDependencies": {
"@babel/core": "^7.15.5",
"@babel/preset-env": "^7.15.6",
"@vue/cli": "^4.5.13",
"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-eslint": "~4.5.0",
"@vue/cli-service": "^4.5.13",
"@vue/compiler-sfc": "^3.0.0",
"babel-eslint": "^10.1.0",
"babel-jest": "^27.2.0",
"core-js": "^3.6.5",
"eslint": "^7.32.0",
"eslint-plugin-import": "^2.24.2",
"eslint-plugin-vue": "^7.18.0",
"jest": "^27.2.0",
"rollup": "^2.56.3",
"rollup-plugin-filesize": "^9.1.1",
"rollup-plugin-vue": "^6.0.0",
"vitepress": "^0.18.1",
"vue": "^3.0.0"
}
}

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc