ng-spin-box
Version:
<h2>Spinbox Directive for Angular.</h2>
325 lines (320 loc) • 13.3 kB
JavaScript
import { __decorate, __metadata } from 'tslib';
import { EventEmitter, ElementRef, Renderer2, Input, Output, HostListener, Directive, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
var SpinBoxDirective = /** @class */ (function () {
function SpinBoxDirective(el, renderer) {
this.el = el;
this.renderer = renderer;
this._hasFocus = false;
this.valueToBeSet = 0;
this.changeByMouse = new EventEmitter();
this._initView();
}
Object.defineProperty(SpinBoxDirective.prototype, "_isDisabled", {
get: function () {
return this.el.nativeElement.disabled;
},
enumerable: true,
configurable: true
});
SpinBoxDirective.prototype._initView = function () {
var _this = this;
var node = this.el.nativeElement;
var parent = node.parentNode;
// Create Wrapper Element
var wrapper = this.renderer.createElement('div');
this.renderer.addClass(wrapper, 'ng-spin-box-wrapper');
this.renderer.setAttribute(wrapper, 'style', "\n position: relative;\n display: inline-block;\n ");
// Wrap Input in our Custom Wrapper
this.renderer.appendChild(wrapper, node);
this.renderer.appendChild(parent, wrapper);
// Add Up/Down Buttons for UserInteraction
var buttonUp = this.renderer.createElement('button');
this.renderer.appendChild(wrapper, buttonUp);
this.renderer.addClass(buttonUp, 'ng-spin-box-btn-up');
this.renderer.listen(buttonUp, 'click', function (e) { _this._clickSpinBoxButton(e, true); });
this.renderer.setAttribute(buttonUp, 'tabIndex', '-1');
this.renderer.setAttribute(buttonUp, 'style', "\n position: absolute;\n top: 0;\n right: 0;\n height: 50%;\n ");
// Add Up/Down Buttons for UserInteraction
var buttonDown = this.renderer.createElement('button');
this.renderer.appendChild(wrapper, buttonDown);
this.renderer.addClass(buttonDown, 'ng-spin-box-btn-down');
this.renderer.listen(buttonDown, 'click', function (e) { _this._clickSpinBoxButton(e, false); });
this.renderer.setAttribute(buttonDown, 'tabIndex', '-1');
this.renderer.setAttribute(buttonDown, 'style', "\n position: absolute;\n bottom: 0;\n right: 0;\n height: 50%;\n ");
};
SpinBoxDirective.prototype._clickSpinBoxButton = function (event, shouldInrease) {
event.preventDefault();
event.stopPropagation();
if (!this._isDisabled) {
this.el.nativeElement.focus();
this._increaseDecreaseValue(shouldInrease);
}
};
/**
* Increase Decrease Value of SpinBox
* @param shouldInrease If true, increase the Value,
* Else Decrease the Value.
*/
SpinBoxDirective.prototype._increaseDecreaseValue = function (shouldInrease) {
var valueStr = this.el.nativeElement.value;
var value = +(valueStr || 0);
var precision = +(this.decimal || 0);
/**
* Add Decimal logic
*/
var multiplier = Math.pow(10, (precision + 2));
var decimalValue = value * multiplier;
decimalValue = +decimalValue.toFixed(precision + 2);
var step = (+this.step) || 1;
// Get Cursor Position
var cursorPosition = this.el.nativeElement.selectionStart;
var decimalPosition = valueStr.indexOf(this._getDecimalSeparator);
var cursorFactor = (cursorPosition - decimalPosition);
// Convert String type values to boolean, to stop the need of Data Binding
var shouldSnapToStep = typeof this.snapToStep === 'string' ? JSON.parse(this.snapToStep) : this.snapToStep;
if (shouldInrease) {
if (this.stepAtCursor && (cursorPosition <= valueStr.length - 2)) {
var stepMultiplier = Math.pow(10, (precision + 2) - cursorFactor);
decimalValue += (1 * stepMultiplier);
}
else {
if (shouldSnapToStep) {
var decimalVal = Math.round((decimalValue) / (step * multiplier)) * (step * multiplier);
if (decimalVal > (decimalValue)) {
decimalVal -= (step * multiplier);
}
decimalValue = (decimalVal) + (step * multiplier);
}
else {
decimalValue += (step * multiplier);
}
}
}
else {
// if (this.stepAtCursor && (cursorPosition > decimalPosition && cursorPosition <= valueStr.length - 2)) {
if (this.stepAtCursor && (cursorPosition <= valueStr.length - 2)) {
var stepMultiplier = Math.pow(10, (precision + 2) - cursorFactor);
decimalValue -= (1 * stepMultiplier);
}
else {
if (shouldSnapToStep) {
var decimalVal = Math.round((decimalValue) / (step * multiplier)) * (step * multiplier);
if (decimalVal < (decimalValue)) {
decimalVal += (step * multiplier);
}
decimalValue = (decimalVal) - (step * multiplier);
}
else {
decimalValue -= (step * multiplier);
}
}
}
var finalValue = (decimalValue / multiplier).toFixed(precision);
// If input value is entered out of bounds, then upon scrolling it, it jumps to a value within bounds.
if ((+finalValue) >= (+this.min || -Infinity) && (+finalValue) <= (+this.max || Infinity)) {
this.valueToBeSet = +finalValue;
}
else if ((+finalValue) < (+this.min || -Infinity)) {
this.valueToBeSet = this.min;
}
else if ((+finalValue) > (+this.max || Infinity)) {
this.valueToBeSet = this.max;
}
if (this.changeByMouse) {
this.changeByMouse.emit(finalValue);
}
// Value to be set needs to be string
var valueToBeSetStr = (+this.valueToBeSet).toFixed(precision);
this.renderer.setProperty(this.el.nativeElement, 'value', valueToBeSetStr);
// Trigger Input Event
var event;
try {
event = new Event('input', { bubbles: true, cancelable: false });
}
catch (e) {
event = document.createEvent('Event');
event.initEvent('input', true, false);
}
// dispatch the event
this.el.nativeElement.dispatchEvent(event);
if (valueStr.indexOf(this._getDecimalSeparator) !== -1) {
this.el.nativeElement.selectionStart = cursorPosition;
this.el.nativeElement.selectionEnd = cursorPosition;
}
};
SpinBoxDirective.prototype.onFocus = function () {
this._hasFocus = true;
};
SpinBoxDirective.prototype.onBlur = function () {
var setLimitOnBlur = typeof this.setLimitOnBlur === 'string' ? JSON.parse(this.setLimitOnBlur) : this.setLimitOnBlur;
if (setLimitOnBlur) {
this._hasFocus = false;
// On blur, if the entered values is out of bounds, it should jump within bounds
var value = +(this.el.nativeElement.value || 0);
var shouldInrease = false;
if (value > this.max) {
this._increaseDecreaseValue(shouldInrease);
}
else if (value < this.min) {
shouldInrease = true;
this._increaseDecreaseValue(shouldInrease);
}
}
};
SpinBoxDirective.prototype.onMouseWheel = function (event) {
event.preventDefault();
if (!this._hasFocus || this._isDisabled) {
return;
}
(event.deltaY > 0) ? this._increaseDecreaseValue(false) : this._increaseDecreaseValue(true);
};
SpinBoxDirective.prototype.onKeydown = function (event) {
var key = event.key;
var cursorPosition = this.el.nativeElement.selectionStart;
// console.log('The Event triggered', key, event);
if (key === 'ArrowUp' || key === 'Up') {
if (event.shiftKey) {
return;
}
else {
this._increaseDecreaseValue(true);
}
}
else if (key === 'ArrowDown' || key === 'Down') {
if (event.shiftKey) {
return;
}
else {
this._increaseDecreaseValue(false);
}
}
// Allow special key presses
if (event.ctrlKey || event.metaKey ||
key === 'ArrowLeft' || key === 'ArrowRight' || key === 'Backspace' ||
key === 'Delete' || key === 'Tab' || key === 'Left' || key === 'Right') {
return;
}
// Allow a minus sign if the value can be negative
if (key === '-' && cursorPosition === 0 && (this.min && this.min < 0)) {
return;
}
// Allow Entry with valid Precision
if (this._checkPrecision(key)) {
return;
}
// Allow digits
// if ((/[0-9]/g).test(key)) {
// return;
// }
// Prevent the default action
event.preventDefault();
};
Object.defineProperty(SpinBoxDirective.prototype, "_getDecimalSeparator", {
get: function () {
var number = 1.1;
return number.toLocaleString().substring(1, 2);
},
enumerable: true,
configurable: true
});
SpinBoxDirective.prototype._checkPrecision = function (key) {
var decimal = (+this.decimal) || 0;
var refElement = this.el.nativeElement;
var value = refElement.value.substr(0, refElement.selectionStart) + key + refElement.value.substr(refElement.selectionEnd);
var regexString = '^\\d+\\' + this._getDecimalSeparator + '?\\d{0,' + decimal + '}$';
return new RegExp(regexString, 'g').test(value);
};
SpinBoxDirective.ctorParameters = function () { return [
{ type: ElementRef },
{ type: Renderer2 }
]; };
__decorate([
Input('min'),
__metadata("design:type", Number)
], SpinBoxDirective.prototype, "min", void 0);
__decorate([
Input('max'),
__metadata("design:type", Number)
], SpinBoxDirective.prototype, "max", void 0);
__decorate([
Input('step'),
__metadata("design:type", Number)
], SpinBoxDirective.prototype, "step", void 0);
__decorate([
Input('decimal'),
__metadata("design:type", Number)
], SpinBoxDirective.prototype, "decimal", void 0);
__decorate([
Input('snapToStep'),
__metadata("design:type", Boolean)
], SpinBoxDirective.prototype, "snapToStep", void 0);
__decorate([
Input('stepAtCursor'),
__metadata("design:type", Boolean)
], SpinBoxDirective.prototype, "stepAtCursor", void 0);
__decorate([
Input('setLimitOnBlur'),
__metadata("design:type", Boolean)
], SpinBoxDirective.prototype, "setLimitOnBlur", void 0);
__decorate([
Output('changeByMouse'),
__metadata("design:type", EventEmitter)
], SpinBoxDirective.prototype, "changeByMouse", void 0);
__decorate([
HostListener('focus'),
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", void 0)
], SpinBoxDirective.prototype, "onFocus", null);
__decorate([
HostListener('blur'),
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", void 0)
], SpinBoxDirective.prototype, "onBlur", null);
__decorate([
HostListener('wheel', ['$event']),
__metadata("design:type", Function),
__metadata("design:paramtypes", [WheelEvent]),
__metadata("design:returntype", void 0)
], SpinBoxDirective.prototype, "onMouseWheel", null);
__decorate([
HostListener('keydown', ['$event']),
__metadata("design:type", Function),
__metadata("design:paramtypes", [KeyboardEvent]),
__metadata("design:returntype", void 0)
], SpinBoxDirective.prototype, "onKeydown", null);
SpinBoxDirective = __decorate([
Directive({
// tslint:disable-next-line
selector: '[ngSpinBox]'
}),
__metadata("design:paramtypes", [ElementRef, Renderer2])
], SpinBoxDirective);
return SpinBoxDirective;
}());
// this.renderer.setElementProperty(this.el.nativeElement, 'value', validString);
var NgSpinBoxModule = /** @class */ (function () {
function NgSpinBoxModule() {
}
NgSpinBoxModule = __decorate([
NgModule({
imports: [
CommonModule
],
declarations: [
SpinBoxDirective
],
exports: [
SpinBoxDirective
]
})
], NgSpinBoxModule);
return NgSpinBoxModule;
}());
/**
* Generated bundle index. Do not edit.
*/
export { NgSpinBoxModule, SpinBoxDirective as ɵa };
//# sourceMappingURL=ng-spin-box.js.map