UNPKG

@ngx-mask/core

Version:

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

402 lines (393 loc) 14 kB
import { __decorate, __param, __metadata } from 'tslib'; import { InjectionToken, Inject, ɵɵdefineInjectable, ɵɵinject, Injectable, Pipe, EventEmitter, ElementRef, Renderer2, Optional, Output, Input, HostListener, Directive, NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { NgControl } from '@angular/forms'; import { BACKSPACE } from '@angular/cdk/keycodes'; import { timer } from 'rxjs'; var MaskPatterns; (function (MaskPatterns) { MaskPatterns["number"] = "\\d"; })(MaskPatterns || (MaskPatterns = {})); function insertChar(text, char, position) { const t = text.split(''); t.splice(position, 0, char); return t.join(''); } function calcOptionalNumbersToUse(pattern, value, tokens) { const numberToken = Object.keys(tokens).find(token => tokens[token].pattern === MaskPatterns.number); if (!numberToken) { return 0; } const numbersInPattern = pattern.replace(new RegExp(`[^${numberToken}]`, 'g'), '').length; const 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) { const pc = pattern.charAt(pos); const token = tokens[pc]; if (pc === '') { return false; } return token && !token.escape ? true : hasMoreTokens(pattern, pos + inc, inc, tokens); } class Mask { constructor(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 }; } static process(value, pattern, options) { return new Mask(pattern, options).process(value); } ; static applyMask(value, pattern, options) { return new Mask(pattern, options).apply(value); } ; static validate(value, pattern, options) { return new Mask(pattern, options).validate(value); } ; process(value) { if (!value) { return { result: '', valid: false }; } const { tokens } = this.options; const pattern2 = this.pattern; let valid = true; let formatted = ''; let valuePos = 0; let patternPos = 0; let optionalNumbersToUse = calcOptionalNumbersToUse(pattern2, value, tokens); let escapeNext = false; const 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 const vc = value.charAt(valuePos); // Pattern char to match with the value char const pc = pattern2.charAt(patternPos); const 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 }; } apply(value) { return this.process(value).result; } validate(value) { return this.process(value).valid; } } const NGX_MASK_OPTIONS = new InjectionToken('NGX_MASK_OPTIONS', { providedIn: 'root', factory() { return { tokens: { '0': { pattern: MaskPatterns.number, default: '0' }, '9': { pattern: MaskPatterns.number, optional: true }, 'A': { pattern: '[a-zA-Z0-9]' }, 'S': { pattern: '[a-zA-Z]' }, 'U': { pattern: '[a-zA-Z]', transform: (c) => c.toLocaleUpperCase() }, 'L': { pattern: '[a-zA-Z]', transform: (c) => c.toLocaleLowerCase() }, '$': { escape: true } } }; } }); let NgxMaskService = class NgxMaskService { constructor(options) { this.options = options; this.validateTokens(options.tokens); } applyMask(value, mask, options) { return Mask.applyMask(value, mask, Object.assign(Object.assign({}, this.options), options)); } validateTokens(tokens) { const token = Object.keys((tokens !== null && tokens !== void 0 ? tokens : {})).find(key => key.length !== 1); if (token) { throw new Error(`Token length must be 1! Actual token '${token}'`); } } }; NgxMaskService.ctorParameters = () => [ { type: undefined, decorators: [{ type: Inject, args: [NGX_MASK_OPTIONS,] }] } ]; NgxMaskService.ɵprov = ɵɵdefineInjectable({ factory: function NgxMaskService_Factory() { return new NgxMaskService(ɵɵinject(NGX_MASK_OPTIONS)); }, token: NgxMaskService, providedIn: "root" }); NgxMaskService = __decorate([ Injectable({ providedIn: 'root' }), __param(0, Inject(NGX_MASK_OPTIONS)), __metadata("design:paramtypes", [Object]) ], NgxMaskService); let NgxMaskPipe = class NgxMaskPipe { constructor(maskService) { this.maskService = maskService; } transform(value, mask, config) { return this.maskService.applyMask(value, mask, config); } }; NgxMaskPipe.ctorParameters = () => [ { type: NgxMaskService } ]; NgxMaskPipe = __decorate([ Pipe({ name: 'ngxMask' }), __metadata("design:paramtypes", [NgxMaskService]) ], NgxMaskPipe); var NgxMaskDirective_1; let NgxMaskDirective = NgxMaskDirective_1 = class NgxMaskDirective { constructor(maskService, elementRef, renderer, ngControl) { this.maskService = maskService; this.elementRef = elementRef; this.renderer = renderer; this.ngControl = ngControl; this.valueChange = new EventEmitter(); this._mask = ''; this.onChange = (_) => { }; this.onTouched = () => { }; if (ngControl) { ngControl.valueAccessor = this; } } get value() { return this.elementRef.nativeElement.value; } set value(value) { this.nativeValue = value; this._onInput(); } get mask() { return this._mask; } set mask(value) { this._mask = value; this._onInput(); } set nativeValue(value) { this.lastNativeValue = value; this.elementRef.nativeElement.value = value; this.valueChange.emit(value); } get input() { return this.elementRef.nativeElement; } static indexOfFirstDifferentChar(value, diff = '') { let index; for (let 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); } registerOnChange(fn) { this.onChange = fn; } registerOnTouched(fn) { this.onTouched = fn; } setDisabledState(isDisabled) { isDisabled ? this.renderer.setAttribute(this.elementRef, 'disabled', 'disabled') : this.renderer.removeAttribute(this.elementRef, 'disabled'); } writeValue(obj) { this.value = obj; this._onInput(); } onBlur() { this.onTouched(); } _onKeydown(event) { const { selectionStart, selectionEnd } = this.input; this.isBackspaceChange = event.keyCode === BACKSPACE && selectionEnd === selectionStart; } _onInput({ emitChange = true } = {}) { const { value, selectionStart } = this.input; const maskedValue = this.maskService.applyMask(value, this.mask); const 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); } } ngAfterViewInit() { if (this.ngControl && this.ngControl.value !== this.value) { timer(0).subscribe(() => this.onChange(this.value)); } } }; NgxMaskDirective.ctorParameters = () => [ { type: NgxMaskService }, { type: ElementRef }, { type: Renderer2 }, { type: NgControl, decorators: [{ type: Optional }] } ]; __decorate([ Output(), __metadata("design:type", Object) ], NgxMaskDirective.prototype, "valueChange", void 0); __decorate([ Input(), __metadata("design:type", String), __metadata("design:paramtypes", [String]) ], NgxMaskDirective.prototype, "value", null); __decorate([ Input('ngxMask'), __metadata("design:type", String), __metadata("design:paramtypes", [String]) ], NgxMaskDirective.prototype, "mask", null); __decorate([ HostListener('blur'), __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], NgxMaskDirective.prototype, "onBlur", null); __decorate([ HostListener('keydown', ['$event']), __metadata("design:type", Function), __metadata("design:paramtypes", [KeyboardEvent]), __metadata("design:returntype", void 0) ], NgxMaskDirective.prototype, "_onKeydown", null); __decorate([ HostListener('change'), HostListener('input'), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", void 0) ], NgxMaskDirective.prototype, "_onInput", null); NgxMaskDirective = NgxMaskDirective_1 = __decorate([ Directive({ selector: 'input[ngxMask][type=text]' }), __param(3, Optional()), __metadata("design:paramtypes", [NgxMaskService, ElementRef, Renderer2, NgControl]) ], NgxMaskDirective); var NgxMaskCoreModule_1; let NgxMaskCoreModule = NgxMaskCoreModule_1 = class NgxMaskCoreModule { static configure(options) { return { ngModule: NgxMaskCoreModule_1, providers: [ { provide: NGX_MASK_OPTIONS, useValue: options } ] }; } }; NgxMaskCoreModule = NgxMaskCoreModule_1 = __decorate([ NgModule({ imports: [CommonModule], exports: [ NgxMaskDirective ], declarations: [NgxMaskPipe, NgxMaskDirective] }) ], NgxMaskCoreModule); /** * Generated bundle index. Do not edit. */ export { Mask, MaskPatterns, NGX_MASK_OPTIONS, NgxMaskCoreModule, NgxMaskDirective, NgxMaskPipe, NgxMaskService }; //# sourceMappingURL=ngx-mask-core.js.map