UNPKG

primeng

Version:

PrimeNG is an open source UI library for Angular featuring a rich set of 80+ components, a theme designer, various theme alternatives such as Material, Bootstrap, Tailwind, premium templates and professional support. In addition, it integrates with PrimeB

1,348 lines (1,337 loc) 58.2 kB
export * from 'primeng/types/inputmask'; import * as i2 from '@angular/common'; import { isPlatformBrowser, CommonModule } from '@angular/common'; import * as i0 from '@angular/core'; import { Injectable, InjectionToken, inject, input, booleanAttribute, output, effect, Directive, forwardRef, computed, EventEmitter, ViewChild, ContentChildren, ContentChild, Output, Input, ViewEncapsulation, ChangeDetectionStrategy, Component, NgModule } from '@angular/core'; import { NG_VALUE_ACCESSOR } from '@angular/forms'; import { getUserAgent, isClient } from '@primeuix/utils'; import { SharedModule, PrimeTemplate } from 'primeng/api'; import { AutoFocus } from 'primeng/autofocus'; import { BaseComponent, PARENT_INSTANCE } from 'primeng/basecomponent'; import { BaseInput } from 'primeng/baseinput'; import * as i1 from 'primeng/bind'; import { Bind, BindModule } from 'primeng/bind'; import { TimesIcon } from 'primeng/icons'; import { InputText } from 'primeng/inputtext'; import { BaseStyle } from 'primeng/base'; const style = /*css*/ ` /* For PrimeNG */ p-inputmask { position: relative; } .p-inputmask-clear-icon { position: absolute; top: 50%; margin-top: -0.5rem; cursor: pointer; inset-inline-end: dt('form.field.padding.x'); color: dt('form.field.icon.color'); } p-inputMask:has(.p-inputtext-fluid), p-input-mask:has(.p-inputtext-fluid), p-inputmask:has(.p-inputtext-fluid) { width: 100%; } p-inputMask.ng-invalid.ng-dirty > .p-inputtext, p-input-mask.ng-invalid.ng-dirty > .p-inputtext, p-inputmask.ng-invalid.ng-dirty > .p-inputtext { border-color: dt('inputtext.invalid.border.color'); } p-inputMask.ng-invalid.ng-dirty > .p-inputtext:enabled:focus, p-input-mask.ng-invalid.ng-dirty > .p-inputtext:enabled:focus, p-inputmask.ng-invalid.ng-dirty > .p-inputtext:enabled:focus { border-color: dt('inputtext.focus.border.color'); } p-inputMask.ng-invalid.ng-dirty > .p-inputtext::placeholder, p-input-mask.ng-invalid.ng-dirty > .p-inputtext::placeholder, p-inputmask.ng-invalid.ng-dirty > .p-inputtext::placeholder { color: dt('inputtext.invalid.placeholder.color'); } `; const classes = { root: ({ instance }) => [ 'p-inputmask p-component p-inputwrapper', { 'p-variant-filled': instance.$variant() === 'filled' } ], clearIcon: 'p-inputmask-clear-icon' }; class InputMaskStyle extends BaseStyle { name = 'inputmask'; style = style; classes = classes; static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: InputMaskStyle, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: InputMaskStyle }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: InputMaskStyle, decorators: [{ type: Injectable }] }); /** * * InputMask component is used to enter input in a certain format such as numeric, date, currency, email and phone. * * [Live Demo](https://www.primeng.org/inputmask/) * * @module inputmaskstyle * */ var InputMaskClasses; (function (InputMaskClasses) { /** * Class name of the root element */ InputMaskClasses["root"] = "p-inputmask"; /** * Class name of the clear icon element */ InputMaskClasses["clearIcon"] = "p-inputmask-clear-icon"; })(InputMaskClasses || (InputMaskClasses = {})); /* Port of jQuery MaskedInput by DigitalBush as a Native Angular2 Component in Typescript without jQuery https://github.com/digitalBush/jquery.maskedinput/ Copyright (c) 2007-2014 Josh Bush (digitalbush.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ const INPUTMASK_INSTANCE = new InjectionToken('INPUTMASK_INSTANCE'); const INPUTMASK_DIRECTIVE_INSTANCE = new InjectionToken('INPUTMASK_DIRECTIVE_INSTANCE'); /** * InputMask directive is applied directly to input elements to enable masked input. * @group Components */ class InputMaskDirective extends BaseComponent { $pcInputMaskDirective = inject(INPUTMASK_DIRECTIVE_INSTANCE, { optional: true, skipSelf: true }) ?? undefined; _componentStyle = inject(InputMaskStyle); /** * Used to pass attributes to DOM elements inside the InputMask directive. * @defaultValue undefined * @group Props */ pInputMaskPT = input(...(ngDevMode ? [undefined, { debugName: "pInputMaskPT" }] : /* istanbul ignore next */ [])); /** * Indicates whether the component should be rendered without styles. * @defaultValue undefined * @group Props */ pInputMaskUnstyled = input(...(ngDevMode ? [undefined, { debugName: "pInputMaskUnstyled" }] : /* istanbul ignore next */ [])); /** * Mask pattern. * @group Props */ pInputMask = input(...(ngDevMode ? [undefined, { debugName: "pInputMask" }] : /* istanbul ignore next */ [])); /** * Placeholder character in mask, default is underscore. * @group Props */ slotChar = input('_', ...(ngDevMode ? [{ debugName: "slotChar" }] : /* istanbul ignore next */ [])); /** * Clears the incomplete value on blur. * @group Props */ autoClear = input(true, { ...(ngDevMode ? { debugName: "autoClear" } : /* istanbul ignore next */ {}), transform: booleanAttribute }); /** * Regex pattern for alpha characters. * @group Props */ characterPattern = input('[A-Za-z]', ...(ngDevMode ? [{ debugName: "characterPattern" }] : /* istanbul ignore next */ [])); /** * When present, it specifies that whether to clean buffer value from model. * @group Props */ keepBuffer = input(false, { ...(ngDevMode ? { debugName: "keepBuffer" } : /* istanbul ignore next */ {}), transform: booleanAttribute }); /** * Callback to invoke when the mask is completed. * @group Emits */ onCompleteEvent = output({ alias: 'onComplete' }); /** * Callback to invoke when value changes, emits unmasked value. * @group Emits */ onUnmaskedChange = output(); defs; tests; partialPosition; firstNonMaskPos; lastRequiredNonMaskPos; len; oldVal; buffer; defaultBuffer; focusText; caretTimeoutId; androidChrome = true; focused; _inputElement = null; _listeners = []; isInputVisible(input) { const style = getComputedStyle(input); return style.display !== 'none' && style.visibility !== 'hidden'; } get inputElement() { if (!this._inputElement) { const host = this.el.nativeElement; this._inputElement = host.querySelector('[data-p-maskable]') || Array.from(host.querySelectorAll('input')).find((input) => this.isInputVisible(input)) || host; } return this._inputElement; } constructor() { super(); effect(() => { const pt = this.pInputMaskPT(); pt && this.directivePT.set(pt); }); effect(() => { this.pInputMaskUnstyled() && this.directiveUnstyled.set(this.pInputMaskUnstyled()); }); effect(() => { const maskValue = this.pInputMask(); if (maskValue) { this.initMask(); } }); if (isPlatformBrowser(this.platformId)) { const ua = navigator.userAgent; this.androidChrome = /chrome/i.test(ua) && /android/i.test(ua); } } onAfterViewInit() { if (isPlatformBrowser(this.platformId) && this.inputElement) { const events = [ ['focus', (e) => this.onInputFocus(e)], ['blur', (e) => this.onInputBlur(e)], ['keydown', (e) => this.onInputKeydown(e)], ['keypress', (e) => this.onKeyPress(e)], ['input', (e) => this.onInputChange(e)], ['paste', (e) => this.onPaste(e)] ]; events.forEach(([event, handler]) => { this.inputElement.addEventListener(event, handler); this._listeners.push(() => this.inputElement.removeEventListener(event, handler)); }); } } onDestroy() { this._listeners.forEach((unlisten) => unlisten()); } initMask() { const maskValue = this.pInputMask(); if (!maskValue) { return; } this.tests = []; this.partialPosition = maskValue.length; this.len = maskValue.length; this.firstNonMaskPos = null; this.defs = { '9': '[0-9]', a: this.characterPattern(), '*': `${this.characterPattern()}|[0-9]` }; const maskTokens = maskValue.split(''); for (let i = 0; i < maskTokens.length; i++) { const c = maskTokens[i]; if (c == '?') { this.len--; this.partialPosition = i; } else if (this.defs[c]) { this.tests.push(new RegExp(this.defs[c])); if (this.firstNonMaskPos === null) { this.firstNonMaskPos = this.tests.length - 1; } if (i < this.partialPosition) { this.lastRequiredNonMaskPos = this.tests.length - 1; } } else { this.tests.push(null); } } this.buffer = []; for (let i = 0; i < maskTokens.length; i++) { const c = maskTokens[i]; if (c != '?') { if (this.defs[c]) this.buffer.push(this.getPlaceholder(i)); else this.buffer.push(c); } } this.defaultBuffer = this.buffer.join(''); } onInputFocus(event) { if (this.inputElement.readOnly || !this.pInputMask()) { return; } this.focused = true; this.focusText = this.inputElement.value; clearTimeout(this.caretTimeoutId); const pos = this.checkVal(); this.caretTimeoutId = setTimeout(() => { if (this.inputElement !== this.inputElement.ownerDocument.activeElement) { return; } this.writeBuffer(); if (pos == this.pInputMask()?.replace('?', '').length) { this.caret(0, pos); } else { this.caret(pos); } }, 10); } onInputBlur(e) { if (!this.pInputMask()) { return; } this.focused = false; // Validate/finalize value on blur (clear incomplete if autoClear) if (!this.keepBuffer()) { const valueBefore = this.inputElement.value; this.checkVal(); // If value changed, dispatch input event so ngModel gets updated if (this.inputElement.value !== valueBefore) { this.dispatchInputEvent(); } } } onInputKeydown(e) { if (this.inputElement.readOnly || !this.pInputMask()) { return; } const k = e.which || e.keyCode; let pos; let begin; let end; let iPhone = false; if (isPlatformBrowser(this.platformId)) { iPhone = /iphone/i.test(getUserAgent()); } this.oldVal = this.inputElement.value; // backspace, delete, and escape get special treatment if (k === 8 || k === 46 || (iPhone && k === 127)) { pos = this.caret(); begin = pos.begin; end = pos.end; if (end - begin === 0) { begin = k !== 46 ? this.seekPrev(begin) : (end = this.seekNext(begin - 1)); end = k === 46 ? this.seekNext(end) : end; } this.clearBuffer(begin, end); if (this.keepBuffer()) { this.shiftL(begin, end - 2); } else { this.shiftL(begin, end - 1); } // Dispatch input event to notify parent components (like DatePicker) this.dispatchInputEvent(); e.preventDefault(); } else if (k === 13) { // enter this.onInputBlur(e); } else if (k === 27) { // escape this.inputElement.value = this.focusText; this.caret(0, this.checkVal()); e.preventDefault(); } } onKeyPress(e) { if (this.inputElement.readOnly || !this.pInputMask()) { return; } const k = e.which || e.keyCode; const pos = this.caret(); let p; let c; let next; let completed; if (e.ctrlKey || e.altKey || e.metaKey || k < 32 || (k > 34 && k < 41)) { return; } else if (k && k !== 13) { if (pos.end - pos.begin !== 0) { this.clearBuffer(pos.begin, pos.end); this.shiftL(pos.begin, pos.end - 1); } p = this.seekNext(pos.begin - 1); if (p < this.len) { c = String.fromCharCode(k); if (this.tests[p].test(c)) { this.shiftR(p); this.buffer[p] = c; this.writeBuffer(); // Dispatch input event to notify parent components (like DatePicker) this.dispatchInputEvent(); next = this.seekNext(p); if (isClient() && /android/i.test(getUserAgent())) { const proxy = () => { this.caret(next); }; setTimeout(proxy, 0); } else { this.caret(next); } if (pos.begin <= this.lastRequiredNonMaskPos) { completed = this.isCompleted(); } } } e.preventDefault(); } if (completed) { this.onCompleteEvent.emit(); } } onInputChange(event) { if (!this.pInputMask()) { return; } // Skip synthetic events dispatched by dispatchInputEvent() to avoid re-processing if (!event.isTrusted) { return; } if (this.androidChrome) this.handleAndroidInput(event); else this.handleInputChange(event); } onPaste(event) { if (!this.pInputMask()) { return; } this.handleInputChange(event); } // Helper methods caret(first, last) { let range; let begin; let end; if (!this.inputElement.offsetParent || this.inputElement !== this.inputElement.ownerDocument.activeElement) { return; } if (typeof first == 'number') { begin = first; end = typeof last === 'number' ? last : begin; if (typeof this.inputElement.setSelectionRange === 'function') { this.inputElement.setSelectionRange(begin, end); } else if (this.inputElement['createTextRange']) { range = this.inputElement['createTextRange'](); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', begin); range.select(); } } else { if (typeof this.inputElement.setSelectionRange === 'function') { begin = this.inputElement.selectionStart; end = this.inputElement.selectionEnd; } else if (this.document['selection'] && this.document['selection'].createRange) { range = this.document['selection'].createRange(); begin = 0 - range.duplicate().moveStart('character', -100000); end = begin + range.text.length; } return { begin: begin, end: end }; } } isCompleted() { for (let i = this.firstNonMaskPos; i <= this.lastRequiredNonMaskPos; i++) { if (this.tests[i] && this.buffer[i] === this.getPlaceholder(i)) { return false; } } return true; } getPlaceholder(i) { const slotCharValue = this.slotChar(); if (i < slotCharValue.length) { return slotCharValue.charAt(i); } return slotCharValue.charAt(0); } seekNext(pos) { while (++pos < this.len && !this.tests[pos]) ; return pos; } seekPrev(pos) { while (--pos >= 0 && !this.tests[pos]) ; return pos; } shiftL(begin, end) { let i, j; if (begin < 0) { return; } for (i = begin, j = this.seekNext(end); i < this.len; i++) { if (this.tests[i]) { if (j < this.len && this.tests[i].test(this.buffer[j])) { this.buffer[i] = this.buffer[j]; this.buffer[j] = this.getPlaceholder(j); } else { break; } j = this.seekNext(j); } } this.writeBuffer(); this.caret(Math.max(this.firstNonMaskPos, begin)); } shiftR(pos) { let i, c, j, t; for (i = pos, c = this.getPlaceholder(pos); i < this.len; i++) { if (this.tests[i]) { j = this.seekNext(i); t = this.buffer[i]; this.buffer[i] = c; if (j < this.len && this.tests[j].test(t)) { c = t; } else { break; } } } } handleAndroidInput(e) { const curVal = this.inputElement.value; const pos = this.caret(); if (this.oldVal && this.oldVal.length && this.oldVal.length > curVal.length) { // a deletion or backspace happened this.checkVal(true); while (pos.begin > 0 && !this.tests[pos.begin - 1]) pos.begin--; if (pos.begin === 0) { while (pos.begin < this.firstNonMaskPos && !this.tests[pos.begin]) pos.begin++; } setTimeout(() => { this.caret(pos.begin, pos.begin); this.onUnmaskedChange.emit(this.getUnmaskedValue()); if (this.isCompleted()) { this.onCompleteEvent.emit(); } }, 0); } else { this.checkVal(true); while (pos.begin < this.len && !this.tests[pos.begin]) pos.begin++; setTimeout(() => { this.caret(pos.begin, pos.begin); this.onUnmaskedChange.emit(this.getUnmaskedValue()); if (this.isCompleted()) { this.onCompleteEvent.emit(); } }, 0); } } handleInputChange(event) { if (this.inputElement.readOnly) { return; } setTimeout(() => { const pos = this.checkVal(true); this.caret(pos); this.onUnmaskedChange.emit(this.getUnmaskedValue()); if (this.isCompleted()) { this.onCompleteEvent.emit(); } }, 0); } clearBuffer(start, end) { if (!this.keepBuffer()) { let i; for (i = start; i < end && i < this.len; i++) { if (this.tests[i]) { this.buffer[i] = this.getPlaceholder(i); } } } } writeBuffer() { if (this.buffer && this.inputElement) { this.inputElement.value = this.buffer.join(''); } } /** * Dispatches an input event on the host element. * This is needed to notify parent components of value changes * since programmatic value changes don't trigger native input events. */ dispatchInputEvent() { const event = new Event('input', { bubbles: true, cancelable: true }); this.inputElement.dispatchEvent(event); this.onUnmaskedChange.emit(this.getUnmaskedValue()); } checkVal(allow) { // try to place characters where they belong const test = this.inputElement.value; let lastMatch = -1; let i; let c; let pos; for (i = 0, pos = 0; i < this.len; i++) { if (this.tests[i]) { this.buffer[i] = this.getPlaceholder(i); while (pos++ < test.length) { c = test.charAt(pos - 1); if (this.tests[i].test(c)) { if (!this.keepBuffer()) { this.buffer[i] = c; } lastMatch = i; break; } } if (pos > test.length) { this.clearBuffer(i + 1, this.len); break; } } else { if (this.buffer[i] === test.charAt(pos)) { pos++; } if (i < this.partialPosition) { lastMatch = i; } } } if (allow) { this.writeBuffer(); } else if (lastMatch + 1 < this.partialPosition) { if (this.autoClear() || this.buffer.join('') === this.defaultBuffer) { // Invalid value. Remove it and replace it with the // mask, which is the default behavior. if (this.inputElement.value) this.inputElement.value = ''; this.clearBuffer(0, this.len); } else { // Invalid value, but we opt to show the value to the // user and allow them to correct their mistake. this.writeBuffer(); } } else { this.writeBuffer(); this.inputElement.value = this.inputElement.value.substring(0, lastMatch + 1); } return (this.partialPosition ? i : this.firstNonMaskPos); } getUnmaskedValue() { const unmaskedBuffer = []; for (let i = 0; i < this.buffer.length; i++) { const c = this.buffer[i]; if (this.tests[i] && c != this.getPlaceholder(i)) { unmaskedBuffer.push(c); } } return unmaskedBuffer.join(''); } static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: InputMaskDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive }); static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.8", type: InputMaskDirective, isStandalone: true, selector: "[pInputMask]", inputs: { pInputMaskPT: { classPropertyName: "pInputMaskPT", publicName: "pInputMaskPT", isSignal: true, isRequired: false, transformFunction: null }, pInputMaskUnstyled: { classPropertyName: "pInputMaskUnstyled", publicName: "pInputMaskUnstyled", isSignal: true, isRequired: false, transformFunction: null }, pInputMask: { classPropertyName: "pInputMask", publicName: "pInputMask", isSignal: true, isRequired: false, transformFunction: null }, slotChar: { classPropertyName: "slotChar", publicName: "slotChar", isSignal: true, isRequired: false, transformFunction: null }, autoClear: { classPropertyName: "autoClear", publicName: "autoClear", isSignal: true, isRequired: false, transformFunction: null }, characterPattern: { classPropertyName: "characterPattern", publicName: "characterPattern", isSignal: true, isRequired: false, transformFunction: null }, keepBuffer: { classPropertyName: "keepBuffer", publicName: "keepBuffer", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { onCompleteEvent: "onComplete", onUnmaskedChange: "onUnmaskedChange" }, host: { properties: { "class.p-inputmask": "!$unstyled()" } }, providers: [InputMaskStyle, { provide: INPUTMASK_DIRECTIVE_INSTANCE, useExisting: InputMaskDirective }, { provide: PARENT_INSTANCE, useExisting: InputMaskDirective }], usesInheritance: true, ngImport: i0 }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: InputMaskDirective, decorators: [{ type: Directive, args: [{ selector: '[pInputMask]', standalone: true, providers: [InputMaskStyle, { provide: INPUTMASK_DIRECTIVE_INSTANCE, useExisting: InputMaskDirective }, { provide: PARENT_INSTANCE, useExisting: InputMaskDirective }], host: { '[class.p-inputmask]': '!$unstyled()' } }] }], ctorParameters: () => [], propDecorators: { pInputMaskPT: [{ type: i0.Input, args: [{ isSignal: true, alias: "pInputMaskPT", required: false }] }], pInputMaskUnstyled: [{ type: i0.Input, args: [{ isSignal: true, alias: "pInputMaskUnstyled", required: false }] }], pInputMask: [{ type: i0.Input, args: [{ isSignal: true, alias: "pInputMask", required: false }] }], slotChar: [{ type: i0.Input, args: [{ isSignal: true, alias: "slotChar", required: false }] }], autoClear: [{ type: i0.Input, args: [{ isSignal: true, alias: "autoClear", required: false }] }], characterPattern: [{ type: i0.Input, args: [{ isSignal: true, alias: "characterPattern", required: false }] }], keepBuffer: [{ type: i0.Input, args: [{ isSignal: true, alias: "keepBuffer", required: false }] }], onCompleteEvent: [{ type: i0.Output, args: ["onComplete"] }], onUnmaskedChange: [{ type: i0.Output, args: ["onUnmaskedChange"] }] } }); const INPUTMASK_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => InputMask), multi: true }; /** * InputMask component is used to enter input in a certain format such as numeric, date, currency, email and phone. * @group Components */ class InputMask extends BaseInput { componentName = 'InputMask'; _componentStyle = inject(InputMaskStyle); $pcInputMask = inject(INPUTMASK_INSTANCE, { optional: true, skipSelf: true }) ?? undefined; bindDirectiveInstance = inject(Bind, { self: true }); onAfterViewChecked() { this.bindDirectiveInstance.setAttrs(this.ptms(['root', 'host'])); } ptmParams = computed(() => ({ context: { filled: this.$variant() === 'filled' } }), ...(ngDevMode ? [{ debugName: "ptmParams" }] : /* istanbul ignore next */ [])); /** * HTML5 input type. * @group Props */ type = 'text'; /** * Placeholder character in mask, default is underscore. * @group Props */ slotChar = '_'; /** * Clears the incomplete value on blur. * @group Props */ autoClear = true; /** * When enabled, a clear icon is displayed to clear the value. * @group Props */ showClear = false; /** * Inline style of the input field. * @group Props */ style; /** * Identifier of the focus input to match a label defined for the component. * @group Props */ inputId; /** * Style class of the input field. * @group Props */ styleClass; /** * Advisory information to display on input. * @group Props */ placeholder; /** * Specifies tab order of the element. * @group Props */ tabindex; /** * Title text of the input text. * @group Props */ title; /** * Used to define a string that labels the input element. * @group Props */ ariaLabel; /** * Establishes relationships between the component and label(s) where its value should be one or more element IDs. * @group Props */ ariaLabelledBy; /** * Used to indicate that user input is required on an element before a form can be submitted. * @group Props */ ariaRequired; /** * When present, it specifies that an input field is read-only. * @group Props */ readonly; /** * Defines if ngModel sets the raw unmasked value to bound value or the formatted mask value. * @group Props */ unmask; /** * Regex pattern for alpha characters * @group Props */ characterPattern = '[A-Za-z]'; /** * When present, the input gets a focus automatically on load. * @group Props */ autofocus; /** * Used to define a string that autocomplete attribute the current element. * @group Props */ autocomplete; /** * When present, it specifies that whether to clean buffer value from model. * @group Props */ keepBuffer = false; /** * Mask pattern. * @group Props */ get mask() { return this._mask; } set mask(val) { this._mask = val; this.initMask(); this.writeValue(''); this.onModelChange(this.value); } /** * Callback to invoke when the mask is completed. * @group Emits */ onComplete = new EventEmitter(); /** * Callback to invoke when the component receives focus. * @param {Event} event - Browser event. * @group Emits */ onFocus = new EventEmitter(); /** * Callback to invoke when the component loses focus. * @param {Event} event - Browser event. * @group Emits */ onBlur = new EventEmitter(); /** * Callback to invoke on input. * @param {Event} event - Browser event. * @group Emits */ onInput = new EventEmitter(); /** * Callback to invoke on input key press. * @param {Event} event - Browser event. * @group Emits */ onKeydown = new EventEmitter(); /** * Callback to invoke when input field is cleared. * @group Emits */ onClear = new EventEmitter(); /** * Custom clear icon template. * @group Templates */ clearIconTemplate; templates; inputViewChild; value; _mask; input; defs; tests; partialPosition; firstNonMaskPos; lastRequiredNonMaskPos; len; oldVal; buffer; defaultBuffer; focusText; caretTimeoutId; androidChrome = true; focused; onInit() { if (isPlatformBrowser(this.platformId)) { let ua = navigator.userAgent; this.androidChrome = /chrome/i.test(ua) && /android/i.test(ua); } this.initMask(); } _clearIconTemplate; onAfterContentInit() { this.templates.forEach((item) => { switch (item.getType()) { case 'clearicon': this._clearIconTemplate = item.template; break; } }); } initMask() { if (!this.mask) { return; } this.tests = []; this.partialPosition = this.mask.length; this.len = this.mask.length; this.firstNonMaskPos = null; this.defs = { '9': '[0-9]', a: this.characterPattern, '*': `${this.characterPattern}|[0-9]` }; let maskTokens = this.mask.split(''); for (let i = 0; i < maskTokens.length; i++) { let c = maskTokens[i]; if (c == '?') { this.len--; this.partialPosition = i; } else if (this.defs[c]) { this.tests.push(new RegExp(this.defs[c])); if (this.firstNonMaskPos === null) { this.firstNonMaskPos = this.tests.length - 1; } if (i < this.partialPosition) { this.lastRequiredNonMaskPos = this.tests.length - 1; } } else { this.tests.push(null); } } this.buffer = []; for (let i = 0; i < maskTokens.length; i++) { let c = maskTokens[i]; if (c != '?') { if (this.defs[c]) this.buffer.push(this.getPlaceholder(i)); else this.buffer.push(c); } } this.defaultBuffer = this.buffer.join(''); } caret(first, last) { let range, begin, end; if (!this.inputViewChild?.nativeElement.offsetParent || this.inputViewChild.nativeElement !== this.inputViewChild.nativeElement.ownerDocument.activeElement) { return; } if (typeof first == 'number') { begin = first; end = typeof last === 'number' ? last : begin; if (this.inputViewChild.nativeElement.setSelectionRange) { this.inputViewChild.nativeElement.setSelectionRange(begin, end); } else if (this.inputViewChild.nativeElement['createTextRange']) { range = this.inputViewChild.nativeElement['createTextRange'](); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', begin); range.select(); } } else { if (this.inputViewChild.nativeElement.setSelectionRange) { begin = this.inputViewChild.nativeElement.selectionStart; end = this.inputViewChild.nativeElement.selectionEnd; } else if (this.document && this.document['selection'].createRange) { range = this.document.createRange(); begin = 0 - range.duplicate().moveStart('character', -100000); end = begin + range.text.length; } return { begin: begin, end: end }; } } isCompleted() { let completed; for (let i = this.firstNonMaskPos; i <= this.lastRequiredNonMaskPos; i++) { if (this.tests[i] && this.buffer[i] === this.getPlaceholder(i)) { return false; } } return true; } getPlaceholder(i) { if (i < this.slotChar.length) { return this.slotChar.charAt(i); } return this.slotChar.charAt(0); } seekNext(pos) { while (++pos < this.len && !this.tests[pos]) ; return pos; } seekPrev(pos) { while (--pos >= 0 && !this.tests[pos]) ; return pos; } shiftL(begin, end) { let i, j; if (begin < 0) { return; } for (i = begin, j = this.seekNext(end); i < this.len; i++) { if (this.tests[i]) { if (j < this.len && this.tests[i].test(this.buffer[j])) { this.buffer[i] = this.buffer[j]; this.buffer[j] = this.getPlaceholder(j); } else { break; } j = this.seekNext(j); } } this.writeBuffer(); this.caret(Math.max(this.firstNonMaskPos, begin)); } shiftR(pos) { let i, c, j, t; for (i = pos, c = this.getPlaceholder(pos); i < this.len; i++) { if (this.tests[i]) { j = this.seekNext(i); t = this.buffer[i]; this.buffer[i] = c; if (j < this.len && this.tests[j].test(t)) { c = t; } else { break; } } } } handleAndroidInput(e) { var curVal = this.inputViewChild?.nativeElement.value; var pos = this.caret(); if (this.oldVal && this.oldVal.length && this.oldVal.length > curVal.length) { // a deletion or backspace happened this.checkVal(true); while (pos.begin > 0 && !this.tests[pos.begin - 1]) pos.begin--; if (pos.begin === 0) { while (pos.begin < this.firstNonMaskPos && !this.tests[pos.begin]) pos.begin++; } setTimeout(() => { this.caret(pos.begin, pos.begin); this.updateModel(e); if (this.isCompleted()) { this.onComplete.emit(); } }, 0); } else { this.checkVal(true); while (pos.begin < this.len && !this.tests[pos.begin]) pos.begin++; setTimeout(() => { this.caret(pos.begin, pos.begin); this.updateModel(e); if (this.isCompleted()) { this.onComplete.emit(); } }, 0); } } onInputBlur(e) { this.focused = false; this.onModelTouched(); if (!this.keepBuffer) { this.checkVal(); } this.onBlur.emit(e); if (this.modelValue() != this.focusText || this.modelValue() != this.value) { this.updateModel(e); let event = this.document.createEvent('HTMLEvents'); event.initEvent('change', true, false); this.inputViewChild?.nativeElement.dispatchEvent(event); } } onInputKeydown(e) { if (this.readonly) { return; } let k = e.which || e.keyCode, pos, begin, end; let iPhone; if (isPlatformBrowser(this.platformId)) { iPhone = /iphone/i.test(getUserAgent()); } this.oldVal = this.inputViewChild?.nativeElement.value; this.onKeydown.emit(e); //backspace, delete, and escape get special treatment if (k === 8 || k === 46 || (iPhone && k === 127)) { pos = this.caret(); begin = pos.begin; end = pos.end; if (end - begin === 0) { begin = k !== 46 ? this.seekPrev(begin) : (end = this.seekNext(begin - 1)); end = k === 46 ? this.seekNext(end) : end; } this.clearBuffer(begin, end); if (this.keepBuffer) { this.shiftL(begin, end - 2); } else { this.shiftL(begin, end - 1); } this.updateModel(e); this.onInput.emit(e); e.preventDefault(); } else if (k === 13) { // enter this.onInputBlur(e); this.updateModel(e); } else if (k === 27) { // escape this.inputViewChild.nativeElement.value = this.focusText; this.caret(0, this.checkVal()); this.updateModel(e); e.preventDefault(); } } onKeyPress(e) { if (this.readonly) { return; } var k = e.which || e.keyCode, pos = this.caret(), p, c, next, completed; if (e.ctrlKey || e.altKey || e.metaKey || k < 32 || (k > 34 && k < 41)) { //Ignore return; } else if (k && k !== 13) { if (pos.end - pos.begin !== 0) { this.clearBuffer(pos.begin, pos.end); this.shiftL(pos.begin, pos.end - 1); } p = this.seekNext(pos.begin - 1); if (p < this.len) { c = String.fromCharCode(k); if (this.tests[p].test(c)) { this.shiftR(p); this.buffer[p] = c; this.writeBuffer(); next = this.seekNext(p); if (isClient() && /android/i.test(getUserAgent())) { let proxy = () => { this.caret(next); }; setTimeout(proxy, 0); } else { this.caret(next); } if (pos.begin <= this.lastRequiredNonMaskPos) { completed = this.isCompleted(); } this.onInput.emit(e); } } e.preventDefault(); } this.updateModel(e); if (completed) { this.onComplete.emit(); } } clearBuffer(start, end) { if (!this.keepBuffer) { let i; for (i = start; i < end && i < this.len; i++) { if (this.tests[i]) { this.buffer[i] = this.getPlaceholder(i); } } } } writeBuffer() { if (this.buffer && this.inputViewChild?.nativeElement) { this.inputViewChild.nativeElement.value = this.buffer.join(''); } } checkVal(allow) { //try to place characters where they belong let test = this.inputViewChild?.nativeElement.value, lastMatch = -1, i, c, pos; for (i = 0, pos = 0; i < this.len; i++) { if (this.tests[i]) { this.buffer[i] = this.getPlaceholder(i); while (pos++ < test.length) { c = test.charAt(pos - 1); if (this.tests[i].test(c)) { if (!this.keepBuffer) { this.buffer[i] = c; } lastMatch = i; break; } } if (pos > test.length) { this.clearBuffer(i + 1, this.len); break; } } else { if (this.buffer[i] === test.charAt(pos)) { pos++; } if (i < this.partialPosition) { lastMatch = i; } } } if (allow) { this.writeBuffer(); } else if (lastMatch + 1 < this.partialPosition) { if (this.autoClear || this.buffer.join('') === this.defaultBuffer) { // Invalid value. Remove it and replace it with the // mask, which is the default behavior. if (this.inputViewChild?.nativeElement.value) this.inputViewChild.nativeElement.value = ''; this.clearBuffer(0, this.len); } else { // Invalid value, but we opt to show the value to the // user and allow them to correct their mistake. this.writeBuffer(); } } else { this.writeBuffer(); this.inputViewChild.nativeElement.value = this.inputViewChild?.nativeElement.value.substring(0, lastMatch + 1); } return (this.partialPosition ? i : this.firstNonMaskPos); } onInputFocus(event) { if (this.readonly) { return; } this.focused = true; clearTimeout(this.caretTimeoutId); let pos; this.focusText = this.inputViewChild?.nativeElement.value; pos = this.keepBuffer ? this.inputViewChild?.nativeElement.value.length : this.checkVal(); this.caretTimeoutId = setTimeout(() => { if (this.inputViewChild?.nativeElement !== this.inputViewChild?.nativeElement.ownerDocument.activeElement) { return; } this.writeBuffer(); if (pos == this.mask?.replace('?', '').length) { this.caret(0, pos); } else { this.caret(pos); } }, 10); this.onFocus.emit(event); } onInputChange(event) { if (this.androidChrome) this.handleAndroidInput(event); else this.handleInputChange(event); this.onInput.emit(event); } handleInputChange(event) { if (this.readonly) { return; } setTimeout(() => { var pos = this.checkVal(true); this.caret(pos); this.updateModel(event); if (this.isCompleted()) { this.onComplete.emit(); } }, 0); } getUnmaskedValue() { let unmaskedBuffer = []; for (let i = 0; i < this.buffer.length; i++) { let c = this.buffer[i]; if (this.tests[i] && c != this.getPlaceholder(i)) { unmaskedBuffer.push(c); } } return unmaskedBuffer.join(''); } updateModel(e) { const target = e.target; if (!target) { return; } const updatedValue = this.unmask ? this.getUnmaskedValue() : target.value; if (updatedValue !== null && updatedValue !== undefined) { this.value = updatedValue; this.writeModelValue(this.value); this.onModelChange(this.value); } } focus() { this.inputViewChild?.nativeElement.focus(); } clear() { this.inputViewChild.nativeElement.value = ''; this.value = null; this.onModelChange(this.value); this.onClear.emit(); } /** * @override * * @see {@link BaseEditableHolder.writeControlValue} * Writes the value to the control. */ writeControlValue(value, setModelValue) { this.value = value; setModelValue(this.value); if (this.inputViewChild && this.inputViewChild.nativeElement) { if (this.value == undefined || this.value == null) this.inputViewChild.nativeElement.value = ''; else this.inputViewChild.nativeElement.value = this.value; this.checkVal(); this.focusText = this.inputViewChild.nativeElement.value; } this.cd.markForCheck(); } static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: InputMask, deps: null, target: i0.ɵɵFactoryTarget.Component }); static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "16.1.0", version: "21.2.8", type: InputMask, isStandalone: true, selector: "p-inputmask, p-inputMask, p-input-mask", inputs: { type: "type", slotChar: "slotChar", autoClear: ["autoClear", "autoClear", booleanAttribute], showClear: ["showClear", "showClear", booleanAttribute], style: "style", inputId: "inputId", styleClass: "styleClass", placeholder: "placeholder", tabindex: "tabindex", title: "title", ariaLabel: "ariaLabel", ariaLabelledBy: "ariaLabelledBy", ariaRequired: ["ariaRequired", "ariaRequired", booleanAttribute], readonly: ["readonly", "readonly", booleanAttribute], unmask: ["unmask", "unmask", booleanAttribute], characterPattern: "characterPattern", autofocus: ["autofocus", "autofocus", booleanAttribute], autocomplete: "autocomplete", keepBuffer: ["keepBuffer", "keepBuffer", booleanAttribute], mask: "mask" }, outputs: { onComplete: "onComplete", onFocus: "onFocus", onBlur: "onBlur", onInput: "onInput", onKeydown: "onKeydown", onClear: "onClear" }, host: { properties: { "class": "cx('root')" } }, providers: [INPUTMASK_VALUE_ACCESSOR, InputMaskStyle, { provide: INPUTMASK_INSTANCE, useExisting: InputMask }, { provide: PARENT_INSTANCE, useExisting: InputMask }], queries: [{ propertyName: "clearIconTemplate", first: true, predicate: ["clearicon"] }, { propertyName: "templates", predicate: PrimeTemplate }], viewQueries: [{ propertyName: "inputViewChild", first: true, predicate: ["input"], descendants: true, static: true }], usesInheritance: true, hostDirectives: [{ directive: i1.Bind }], ngImport: i0, template: ` <input #input pInputText [pt]="ptm('pcInputText', ptmParams())" [unstyled]="unstyled()" [attr.id]="inputId" [attr.type]="type" [attr.name]="name()" [invalid]="invalid()" [class]="styleClass" [ngStyle]="style" [attr.placeholder]="placeholder" [attr.title]="title" [pSize]="size()" [attr.size]="inputSize()" [attr.autocomplete]="autocomplete" [attr.maxlength]="maxlength()" [attr.minlength]="minlength()" [attr.tabindex]="tabindex" [attr.aria-label]="ariaLabel" [attr.aria-labelledBy]="ariaLabelledBy" [attr.aria-required]="ariaRequired" [attr.required]="required() ? '' : undefined" [attr.readonly]="readonly ? '' : undefined" [attr.disabled]="$disabled() ? '' : undefined" (focus)="onInputFocus($event)" (