UNPKG

ng-spin-box

Version:

<h2>Spinbox Directive for Angular.</h2>

507 lines (478 loc) 23.9 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common')) : typeof define === 'function' && define.amd ? define('ng-spin-box', ['exports', '@angular/core', '@angular/common'], factory) : (global = global || self, factory(global['ng-spin-box'] = {}, global.ng.core, global.ng.common)); }(this, function (exports, core, common) { 'use strict'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]]; return t; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [0, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __exportStar(m, exports) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } function __values(o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result.default = mod; return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } var SpinBoxDirective = /** @class */ (function () { function SpinBoxDirective(el, renderer) { this.el = el; this.renderer = renderer; this._hasFocus = false; this.valueToBeSet = 0; this.changeByMouse = new core.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: core.ElementRef }, { type: core.Renderer2 } ]; }; __decorate([ core.Input('min'), __metadata("design:type", Number) ], SpinBoxDirective.prototype, "min", void 0); __decorate([ core.Input('max'), __metadata("design:type", Number) ], SpinBoxDirective.prototype, "max", void 0); __decorate([ core.Input('step'), __metadata("design:type", Number) ], SpinBoxDirective.prototype, "step", void 0); __decorate([ core.Input('decimal'), __metadata("design:type", Number) ], SpinBoxDirective.prototype, "decimal", void 0); __decorate([ core.Input('snapToStep'), __metadata("design:type", Boolean) ], SpinBoxDirective.prototype, "snapToStep", void 0); __decorate([ core.Input('stepAtCursor'), __metadata("design:type", Boolean) ], SpinBoxDirective.prototype, "stepAtCursor", void 0); __decorate([ core.Input('setLimitOnBlur'), __metadata("design:type", Boolean) ], SpinBoxDirective.prototype, "setLimitOnBlur", void 0); __decorate([ core.Output('changeByMouse'), __metadata("design:type", core.EventEmitter) ], SpinBoxDirective.prototype, "changeByMouse", void 0); __decorate([ core.HostListener('focus'), __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], SpinBoxDirective.prototype, "onFocus", null); __decorate([ core.HostListener('blur'), __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], SpinBoxDirective.prototype, "onBlur", null); __decorate([ core.HostListener('wheel', ['$event']), __metadata("design:type", Function), __metadata("design:paramtypes", [WheelEvent]), __metadata("design:returntype", void 0) ], SpinBoxDirective.prototype, "onMouseWheel", null); __decorate([ core.HostListener('keydown', ['$event']), __metadata("design:type", Function), __metadata("design:paramtypes", [KeyboardEvent]), __metadata("design:returntype", void 0) ], SpinBoxDirective.prototype, "onKeydown", null); SpinBoxDirective = __decorate([ core.Directive({ // tslint:disable-next-line selector: '[ngSpinBox]' }), __metadata("design:paramtypes", [core.ElementRef, core.Renderer2]) ], SpinBoxDirective); return SpinBoxDirective; }()); // this.renderer.setElementProperty(this.el.nativeElement, 'value', validString); var NgSpinBoxModule = /** @class */ (function () { function NgSpinBoxModule() { } NgSpinBoxModule = __decorate([ core.NgModule({ imports: [ common.CommonModule ], declarations: [ SpinBoxDirective ], exports: [ SpinBoxDirective ] }) ], NgSpinBoxModule); return NgSpinBoxModule; }()); exports.NgSpinBoxModule = NgSpinBoxModule; exports.ɵa = SpinBoxDirective; Object.defineProperty(exports, '__esModule', { value: true }); })); //# sourceMappingURL=ng-spin-box.umd.js.map