All files / src/utils mask.ts

100% Statements 82/82
100% Branches 44/44
100% Functions 23/23
100% Lines 70/70

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256                                                                    23x                         23x       23x                 3x 3x 12x   3x 2x 6x             23x         23x   34x     12x 12x     9x 9x     5x     6x 6x     6x 6x                       12x               308x                 92x 91x                 4x 4x   4x 3x 2x   2x 2x   2x 8x 8x   8x 6x   2x     8x     2x                   99x 97x 96x                           29x 29x   29x 29x 26x   26x 26x 26x   26x 101x     101x       101x 1x 1x   100x 7x   93x 86x 86x   7x     94x     19x               2x                 10x   10x               2x   3x      
/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2016-2019 John Jeremy Leider
 *
 * 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.
 *
 * Originally copied from Vuetify package
 * (https://github.com/vuetifyjs/vuetify/blob/v1.5.16/packages/vuetify/src/util/mask.ts)
 */
 
export interface MaskItem {
	test: (char: string) => boolean;
	convert?: (char: string) => string;
}
 
export type MaskType = '#' | 'A' | 'a' | 'C' | 'N' | 'n' | 'X';
 
const patterns: any = {
	'#': /\d/,
	A: /[A-Z]/,
	a: /[a-z]/,
	C: /[A-Za-z]/,
	N: /[0-9A-Z]/,
	n: /[0-9a-z]/,
	X: /[-!$%^&*()_+|~=`{}[:";'<>?,.\]\\ /]/,
};
 
/**
 * Base class control mask on text
 */
export class Mask {
	/**
	 * Mask patterns
	 */
	public static patterns = patterns;
 
	/**
	 * Add a new mask pattern
	 * @param pattern pattern character
	 * @param testExp regular expression
	 * @param forceCase force upper case or lower case
	 */
	public static addPattern(pattern: string, testExp: any, forceCase?: 'uppercase' | 'lowercase') {
		patterns[pattern] = testExp;
		Mask.allowedMasks[pattern] = {
			test: (char: string) => new RegExp(testExp, forceCase ? 'i' : '').test(char),
		};
		if (forceCase) {
			const functionName = forceCase === 'uppercase' ? 'toUpperCase' : 'toLowerCase';
			Mask.allowedMasks[pattern].convert = (char: string) => char[functionName]();
		}
	}
 
	/**
	 * Mask delimiters
	 */
	private static defaultDelimiters: RegExp = patterns.X;
 
	/**
	 * Allowed mask patterns
	 */
	public static allowedMasks: { [key: string]: MaskItem } = {
		'#': {
			test: (char: string) => patterns['#'].test(char),
		},
		A: {
			test: (char: string) => new RegExp(patterns.A, 'i').test(char),
			convert: (char: string) => char.toUpperCase(),
		},
		a: {
			test: (char: string) => new RegExp(patterns.a, 'i').test(char),
			convert: (char: string) => char.toLowerCase(),
		},
		C: {
			test: (char: string) => patterns.C.test(char),
		},
		N: {
			test: (char: string) => new RegExp(patterns.N, 'i').test(char),
			convert: (char: string) => char.toUpperCase(),
		},
		n: {
			test: (char: string) => new RegExp(patterns.n, 'i').test(char),
			convert: (char: string) => char.toLowerCase(),
		},
		X: {
			test: Mask.isMaskDelimiter,
		},
	};
 
	/**
	 * Checks is a mask delimiter
	 * @param char Mask character
	 */
	public static isMaskDelimiter(char: string): boolean {
		return char ? new RegExp(Mask.defaultDelimiters).test(char) : false;
	}
 
	/**
	 * Checks is a valid mask character
	 * @param char Mask character
	 */
	private static isMask(char: any): boolean {
		return char instanceof RegExp || Object.prototype.hasOwnProperty.call(Mask.allowedMasks, char);
	}
 
	/**
	 * Applies mask rules on char value
	 * @param mask Mask character
	 * @param char Text character
	 */
	private static convert(mask: any, char: string): string {
		if (mask instanceof RegExp) return char;
		return Mask.allowedMasks[mask].convert ? Mask.allowedMasks[mask].convert!(char) : char;
	}
 
	/**
	 * Applies mask rules to value
	 * @param mask Mask
	 * @param text Text value
	 */
	public static convertAll(mask: string | any[], text: string | null): string {
		let maskCollection = mask;
		const value = text;
 
		if (value === null) return '';
		if (!mask.length || !value.length) return value;
		if (!Array.isArray(mask)) maskCollection = mask.split('');
 
		let maskIndex = 0;
		let newText = '';
 
		while (maskIndex < value.length) {
			const maskChar = maskCollection[maskIndex];
			const char = value[maskIndex];
 
			if (Mask.isMask(maskChar) && Mask.maskValidates(maskChar, char)) {
				newText += Mask.convert(maskChar, char);
			} else {
				newText += char;
			}
 
			maskIndex += 1;
		}
 
		return newText;
	}
 
	/**
	 * Checks is a valid char based on mask types
	 * @param mask Mask character
	 * @param char Text character
	 * @returns Is valid
	 */
	private static maskValidates(mask: any, char: string): boolean {
		if (!Mask.isMask(mask)) return false;
		if (mask instanceof RegExp) return mask.test(char);
		return Mask.allowedMasks[mask].test(char);
	}
 
	/**
	 * Retrieves a value with mask
	 * @param text Value to apply mask
	 * @param masked Mask pattern
	 * @param dontFillMaskBlanks Should keep invalid mask on value
	 */
	public static getValueWithMask(
		text: string | null | undefined,
		masked: string | any[],
		dontFillMaskBlanks = false,
	): string {
		let maskCollection = masked;
		let value = text;
 
		if (value == null) value = '';
		if (!masked.length || !value.length) return value;
		if (!Array.isArray(masked)) maskCollection = masked.split('');
 
		let textIndex = 0;
		let maskIndex = 0;
		let newText = '';
 
		while (maskIndex < maskCollection.length) {
			const mask = maskCollection[maskIndex];
 
			// Assign the next character
			const char = value[textIndex] || '';
 
			// Check if mask is delimiter
			// and current char matches
			if (!Mask.isMask(mask) && char === mask) {
				newText += mask;
				textIndex += 1;
				// Check if not mask
			} else if (!Mask.isMask(mask) && !dontFillMaskBlanks) {
				newText += mask;
				// Check if is mask and validates
			} else if (Mask.maskValidates(mask, char)) {
				newText += Mask.convert(mask, char);
				textIndex += 1;
			} else {
				return newText;
			}
 
			maskIndex += 1;
		}
 
		return newText;
	}
 
	/**
	 * Retrieves a value without mask
	 * @param text Value with mask
	 */
	public static getValueWithoutMask(text: string): string {
		return text.replace(new RegExp(Mask.defaultDelimiters, 'g'), '');
	}
 
	/**
	 * Checks if text matches the mask
	 * @param text Text being checked
	 * @param mask Test mask
	 */
	public static checkMask(text: string | null | undefined, mask: string | any[]): boolean {
		const remasked = Mask.getValueWithMask(text, mask);
 
		return text === remasked;
	}
 
	/**
	 * Transforms the mask to an array of regexp
	 * @param mask The mask
	 */
	public static getMaskArray(mask: string | any[]): any[] {
		if (Array.isArray(mask)) return mask;
 
		return mask.split('').map((char) => Mask.patterns[char] || char);
	}
}