UNPKG

@ngx-mask/core

Version:

[@ngx-mask/core](https://github.com/IKatsuba/ngx-mask#readme)

647 lines (611 loc) 29.2 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common'), require('@angular/forms'), require('@angular/cdk/keycodes'), require('rxjs')) : typeof define === 'function' && define.amd ? define('@ngx-mask/core', ['exports', '@angular/core', '@angular/common', '@angular/forms', '@angular/cdk/keycodes', 'rxjs'], factory) : (global = global || self, factory((global['ngx-mask'] = global['ngx-mask'] || {}, global['ngx-mask'].core = {}), global.ng.core, global.ng.common, global.ng.forms, global.ng.cdk.keycodes, global.rxjs)); }(this, (function (exports, core, common, forms, keycodes, rxjs) { '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 = function(d, b) { 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]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __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; }; return __assign.apply(this, arguments); }; 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 && Object.prototype.propertyIsEnumerable.call(s, p[i])) 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) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 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) : adopt(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 = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, 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 s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } 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 __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; }; 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) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } } 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 }; } function __classPrivateFieldGet(receiver, privateMap) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return privateMap.get(receiver); } function __classPrivateFieldSet(receiver, privateMap, value) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to set private field on non-instance"); } privateMap.set(receiver, value); return value; } (function (MaskPatterns) { MaskPatterns["number"] = "\\d"; })(exports.MaskPatterns || (exports.MaskPatterns = {})); function insertChar(text, char, position) { var t = text.split(''); t.splice(position, 0, char); return t.join(''); } function calcOptionalNumbersToUse(pattern, value, tokens) { var numberToken = Object.keys(tokens).find(function (token) { return tokens[token].pattern === exports.MaskPatterns.number; }); if (!numberToken) { return 0; } var numbersInPattern = pattern.replace(new RegExp("[^" + numberToken + "]", 'g'), '').length; var numbersInValue = value.replace(/[^\d]/g, '').length; return numbersInValue - numbersInPattern; } function concatChar(text, character, options, token) { if (token && typeof token.transform === 'function') { character = token.transform(character); } return text + character; } function hasMoreTokens(pattern, pos, inc, tokens) { var pc = pattern.charAt(pos); var token = tokens[pc]; if (pc === '') { return false; } return token && !token.escape ? true : hasMoreTokens(pattern, pos + inc, inc, tokens); } var Mask = /** @class */ (function () { function Mask(pattern, options) { var _a, _b; this.pattern = pattern; this.options = { useDefaults: (_b = (_a = options) === null || _a === void 0 ? void 0 : _a.useDefaults, (_b !== null && _b !== void 0 ? _b : false)), tokens: options.tokens }; } Mask.process = function (value, pattern, options) { return new Mask(pattern, options).process(value); }; ; Mask.applyMask = function (value, pattern, options) { return new Mask(pattern, options).apply(value); }; ; Mask.validate = function (value, pattern, options) { return new Mask(pattern, options).validate(value); }; ; Mask.prototype.process = function (value) { if (!value) { return { result: '', valid: false }; } var tokens = this.options.tokens; var pattern2 = this.pattern; var valid = true; var formatted = ''; var valuePos = 0; var patternPos = 0; var optionalNumbersToUse = calcOptionalNumbersToUse(pattern2, value, tokens); var escapeNext = false; var steps = { start: 0, end: pattern2.length, inc: 1 }; function continueCondition() { if (hasMoreTokens(pattern2, patternPos, steps.inc, tokens)) { // continue in the normal iteration return true; } return patternPos < pattern2.length && patternPos >= 0; } /** * Iterate over the pattern's chars parsing/matching the input value chars * until the end of the pattern. If the pattern ends with recursive chars * the iteration will continue until the end of the input value. * * Note: The iteration must stop if an invalid char is found. */ for (patternPos = steps.start; continueCondition();) { // Value char var vc = value.charAt(valuePos); // Pattern char to match with the value char var pc = pattern2.charAt(patternPos); var token = tokens[pc]; // 1. Handle escape tokens in pattern // go to next iteration: if the pattern char is a escape char or was escaped if (escapeNext) { // pattern char is escaped, just add it and move on formatted = concatChar(formatted, pc, this.options, token); escapeNext = false; patternPos = patternPos + steps.inc; continue; } else if (token && token.escape) { // mark to escape the next pattern char escapeNext = true; patternPos = patternPos + steps.inc; continue; } // 3. Handle the value // break iterations: if value is invalid for the given pattern if (!token) { // add char of the pattern formatted = concatChar(formatted, pc, this.options, token); if (pc === vc) { valuePos += steps.inc; } } else if (token.optional) { // if token is optional, only add the value char if it matchs the token pattern // if not, move on to the next pattern char if (new RegExp(token.pattern).test(vc) && optionalNumbersToUse) { formatted = concatChar(formatted, vc, this.options, token); valuePos += steps.inc; optionalNumbersToUse--; } } else if (new RegExp(token.pattern).test(vc)) { // if token isn't optional the value char must match the token pattern formatted = concatChar(formatted, vc, this.options, token); valuePos += steps.inc; } else if (!vc && token.default && this.options.useDefaults) { // if the token isn't optional and has a default value, use it if the value is finished formatted = concatChar(formatted, token.default, this.options, token); } else if (vc) { // the string value don't match the given pattern valuePos += steps.inc; continue; } else { // the string value don't match the given pattern valid = false; break; } patternPos = patternPos + steps.inc; } return { result: formatted, valid: valid }; }; Mask.prototype.apply = function (value) { return this.process(value).result; }; Mask.prototype.validate = function (value) { return this.process(value).valid; }; return Mask; }()); var NGX_MASK_OPTIONS = new core.InjectionToken('NGX_MASK_OPTIONS', { providedIn: 'root', factory: function () { return { tokens: { '0': { pattern: exports.MaskPatterns.number, default: '0' }, '9': { pattern: exports.MaskPatterns.number, optional: true }, 'A': { pattern: '[a-zA-Z0-9]' }, 'S': { pattern: '[a-zA-Z]' }, 'U': { pattern: '[a-zA-Z]', transform: function (c) { return c.toLocaleUpperCase(); } }, 'L': { pattern: '[a-zA-Z]', transform: function (c) { return c.toLocaleLowerCase(); } }, '$': { escape: true } } }; } }); var NgxMaskService = /** @class */ (function () { function NgxMaskService(options) { this.options = options; this.validateTokens(options.tokens); } NgxMaskService.prototype.applyMask = function (value, mask, options) { return Mask.applyMask(value, mask, __assign(__assign({}, this.options), options)); }; NgxMaskService.prototype.validateTokens = function (tokens) { var token = Object.keys((tokens !== null && tokens !== void 0 ? tokens : {})).find(function (key) { return key.length !== 1; }); if (token) { throw new Error("Token length must be 1! Actual token '" + token + "'"); } }; NgxMaskService.ctorParameters = function () { return [ { type: undefined, decorators: [{ type: core.Inject, args: [NGX_MASK_OPTIONS,] }] } ]; }; NgxMaskService.ɵprov = core["ɵɵdefineInjectable"]({ factory: function NgxMaskService_Factory() { return new NgxMaskService(core["ɵɵinject"](NGX_MASK_OPTIONS)); }, token: NgxMaskService, providedIn: "root" }); NgxMaskService = __decorate([ core.Injectable({ providedIn: 'root' }), __param(0, core.Inject(NGX_MASK_OPTIONS)), __metadata("design:paramtypes", [Object]) ], NgxMaskService); return NgxMaskService; }()); var NgxMaskPipe = /** @class */ (function () { function NgxMaskPipe(maskService) { this.maskService = maskService; } NgxMaskPipe.prototype.transform = function (value, mask, config) { return this.maskService.applyMask(value, mask, config); }; NgxMaskPipe.ctorParameters = function () { return [ { type: NgxMaskService } ]; }; NgxMaskPipe = __decorate([ core.Pipe({ name: 'ngxMask' }), __metadata("design:paramtypes", [NgxMaskService]) ], NgxMaskPipe); return NgxMaskPipe; }()); var NgxMaskDirective = /** @class */ (function () { function NgxMaskDirective(maskService, elementRef, renderer, ngControl) { this.maskService = maskService; this.elementRef = elementRef; this.renderer = renderer; this.ngControl = ngControl; this.valueChange = new core.EventEmitter(); this._mask = ''; this.onChange = function (_) { }; this.onTouched = function () { }; if (ngControl) { ngControl.valueAccessor = this; } } NgxMaskDirective_1 = NgxMaskDirective; Object.defineProperty(NgxMaskDirective.prototype, "value", { get: function () { return this.elementRef.nativeElement.value; }, set: function (value) { this.nativeValue = value; this._onInput(); }, enumerable: true, configurable: true }); Object.defineProperty(NgxMaskDirective.prototype, "mask", { get: function () { return this._mask; }, set: function (value) { this._mask = value; this._onInput(); }, enumerable: true, configurable: true }); Object.defineProperty(NgxMaskDirective.prototype, "nativeValue", { set: function (value) { this.lastNativeValue = value; this.elementRef.nativeElement.value = value; this.valueChange.emit(value); }, enumerable: true, configurable: true }); Object.defineProperty(NgxMaskDirective.prototype, "input", { get: function () { return this.elementRef.nativeElement; }, enumerable: true, configurable: true }); NgxMaskDirective.indexOfFirstDifferentChar = function (value, diff) { if (diff === void 0) { diff = ''; } var index; for (var i = 0; i < diff.length && i < value.length; i++) { if (value.charAt(i) !== diff.charAt(i)) { index = i; break; } } return (index !== null && index !== void 0 ? index : value.length); }; NgxMaskDirective.prototype.registerOnChange = function (fn) { this.onChange = fn; }; NgxMaskDirective.prototype.registerOnTouched = function (fn) { this.onTouched = fn; }; NgxMaskDirective.prototype.setDisabledState = function (isDisabled) { isDisabled ? this.renderer.setAttribute(this.elementRef, 'disabled', 'disabled') : this.renderer.removeAttribute(this.elementRef, 'disabled'); }; NgxMaskDirective.prototype.writeValue = function (obj) { this.value = obj; this._onInput(); }; NgxMaskDirective.prototype.onBlur = function () { this.onTouched(); }; NgxMaskDirective.prototype._onKeydown = function (event) { var _a = this.input, selectionStart = _a.selectionStart, selectionEnd = _a.selectionEnd; this.isBackspaceChange = event.keyCode === keycodes.BACKSPACE && selectionEnd === selectionStart; }; NgxMaskDirective.prototype._onInput = function (_a) { var _b = (_a === void 0 ? {} : _a).emitChange, emitChange = _b === void 0 ? true : _b; var _c = this.input, value = _c.value, selectionStart = _c.selectionStart; var maskedValue = this.maskService.applyMask(value, this.mask); var indexOfFirstDifferentChar = this.lastNativeValue ? NgxMaskDirective_1.indexOfFirstDifferentChar(maskedValue, this.lastNativeValue) : maskedValue.length; this.nativeValue = maskedValue; this.input.selectionStart = this.input.selectionEnd = this.isBackspaceChange ? selectionStart : indexOfFirstDifferentChar + 1; this.isBackspaceChange = false; if (emitChange) { this.onChange(this.value); } }; NgxMaskDirective.prototype.ngAfterViewInit = function () { var _this = this; if (this.ngControl && this.ngControl.value !== this.value) { rxjs.timer(0).subscribe(function () { return _this.onChange(_this.value); }); } }; var NgxMaskDirective_1; NgxMaskDirective.ctorParameters = function () { return [ { type: NgxMaskService }, { type: core.ElementRef }, { type: core.Renderer2 }, { type: forms.NgControl, decorators: [{ type: core.Optional }] } ]; }; __decorate([ core.Output(), __metadata("design:type", Object) ], NgxMaskDirective.prototype, "valueChange", void 0); __decorate([ core.Input(), __metadata("design:type", String), __metadata("design:paramtypes", [String]) ], NgxMaskDirective.prototype, "value", null); __decorate([ core.Input('ngxMask'), __metadata("design:type", String), __metadata("design:paramtypes", [String]) ], NgxMaskDirective.prototype, "mask", null); __decorate([ core.HostListener('blur'), __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], NgxMaskDirective.prototype, "onBlur", null); __decorate([ core.HostListener('keydown', ['$event']), __metadata("design:type", Function), __metadata("design:paramtypes", [KeyboardEvent]), __metadata("design:returntype", void 0) ], NgxMaskDirective.prototype, "_onKeydown", null); __decorate([ core.HostListener('change'), core.HostListener('input'), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", void 0) ], NgxMaskDirective.prototype, "_onInput", null); NgxMaskDirective = NgxMaskDirective_1 = __decorate([ core.Directive({ selector: 'input[ngxMask][type=text]' }), __param(3, core.Optional()), __metadata("design:paramtypes", [NgxMaskService, core.ElementRef, core.Renderer2, forms.NgControl]) ], NgxMaskDirective); return NgxMaskDirective; }()); var NgxMaskCoreModule = /** @class */ (function () { function NgxMaskCoreModule() { } NgxMaskCoreModule_1 = NgxMaskCoreModule; NgxMaskCoreModule.configure = function (options) { return { ngModule: NgxMaskCoreModule_1, providers: [ { provide: NGX_MASK_OPTIONS, useValue: options } ] }; }; var NgxMaskCoreModule_1; NgxMaskCoreModule = NgxMaskCoreModule_1 = __decorate([ core.NgModule({ imports: [common.CommonModule], exports: [ NgxMaskDirective ], declarations: [NgxMaskPipe, NgxMaskDirective] }) ], NgxMaskCoreModule); return NgxMaskCoreModule; }()); exports.Mask = Mask; exports.NGX_MASK_OPTIONS = NGX_MASK_OPTIONS; exports.NgxMaskCoreModule = NgxMaskCoreModule; exports.NgxMaskDirective = NgxMaskDirective; exports.NgxMaskPipe = NgxMaskPipe; exports.NgxMaskService = NgxMaskService; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=ngx-mask-core.umd.js.map