All files / src/components/zd-input input.ts

100% Statements 105/105
100% Branches 17/17
100% Functions 29/29
100% Lines 101/101

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 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 42193x 93x 93x 93x             93x       677x         677x         677x         677x           677x         677x         677x                   677x         677x         677x                   677x         677x         677x         677x         677x         677x         677x         677x         677x         677x         677x                             677x   677x   677x   677x   677x   677x   677x                                                                       117x   117x 3x               23x 4x   19x             4x             1x               2x 1x     1x               677x                 16x 16x 16x 16x               1x 1x 1x             1x 1x 1x             13x 13x 9x 9x                 496x       441x 250x 250x               4x       2x 2x 2x 2x 1x 1x     1x 1x 1x   1x 1x                   25x                 4x               9x 7x 7x       677x               52x   52x 49x 49x       677x   677x   1x                     2x 2x 2x                   2x                 2x   2x 2x         677x 677x 191x   677x       208x 93x  
import { FormatterParserProvider, IDictionary, Mask, Validation } from '@zeedhi/core';
import debounce from 'lodash.debounce';
import { ComponentRender } from '../zd-component/component-render';
import { Form } from '../zd-form/form';
import { IInput, IInputEvents } from './interfaces';
import { IFormGrid } from '../zd-form/interfaces';
 
/**
 * Base class for Input component.
 */
export class Input extends ComponentRender implements IInput {
	/**
	 * Input content alignment.
	 */
	public align = 'left';
 
	/**
	 * Always show error messages even if showHelper is false.
	 */
	public alwaysShowError = false;
 
	/**
	 * Input auto complete.
	 */
	public autofill = true;
 
	/**
	 * Add input clear functionality if the input isn't readonly or disabled.
	 */
	public clearable = true;
 
	/**
	 * Applies specified color to the control.
	 * It can be the name of material or css color in hex.
	 */
	public color = 'primary';
 
	/**
	 * Defines smaller input.
	 */
	public dense = true;
 
	/**
	 * Removes the ability to click or target the input.
	 */
	public disabled = false;
 
	/**
	 * Defines input events.
	 */
	public declare events: IInputEvents;
 
	/**
	 * Hint text.
	 */
	public hint = '';
 
	/**
	 * Defines the input label.
	 */
	public label = '';
 
	/**
	 * Applies a custom character mask to the input.
	 */
	public mask?: any = '';
 
	/**
	 * Input max character length.
	 */
	public maxLength!: number;
 
	/**
	 * Forces hint to always be visible.
	 */
	public persistentHint = false;
 
	/**
	 * Sets the input’s placeholder text.
	 */
	public placeholder = '';
 
	/**
	 * Puts input in readonly state.
	 */
	public readonly = false;
 
	/**
	 * Reverses the input orientation.
	 */
	public reverse = false;
 
	/**
	 * Rules that will validate the input value.
	 */
	public rules: ((value?: any) => boolean | string)[] = [];
 
	/**
	 * Shows input border.
	 */
	public showBorder = true;
 
	/**
	 * Shows input helper.
	 */
	public showHelper = true;
 
	/**
	 * Shows input label.
	 */
	public showLabel = true;
 
	/**
	 * Show rules details in input.
	 */
	public autoHintDetails = false;
 
	/**
	 * Used to watch a value from store.
	 */
	public storePath = '';
 
	/**
	 * Input validations.
	 */
	public validations: IDictionary<IDictionary<string | number>> = {};
 
	/**
	 * Optional validation method assigned by view layer.
	 */
	private viewValidate?: (silent?: boolean) => Promise<string[]>;
 
	/**
	 * Reset validation method assigned by view layer.
	 */
	private viewResetValidation?: () => void;
 
	/**
	 * Parsed field rules.
	 */
	protected parsedValidations: IDictionary<(value?: any) => boolean | string> = {};
 
	protected formatterFn = FormatterParserProvider.getFormatter('ZdInput');
 
	protected parserFn = FormatterParserProvider.getParser('ZdInput');
 
	protected internalDisplayValue = '';
 
	protected internalValue: any = null;
 
	public formParent?: Form = this.getFormParent();
 
	public grid: IFormGrid = {};
 
	/* istanbul ignore next */
	/**
	 * Creates a new Input.
	 * @param props Input properties
	 */
	constructor(props: IInput) {
		super(props);
		this.align = this.getInitValue('align', props.align, this.align);
		this.alwaysShowError = this.getInitValue('alwaysShowError', props.alwaysShowError, this.alwaysShowError);
		this.autofill = this.getInitValue('autofill', props.autofill, this.autofill);
		this.clearable = this.getInitValue('clearable', props.clearable, this.clearable);
		this.color = this.getInitValue('color', props.color, this.color);
		this.dense = this.getInitValue('dense', props.dense, this.dense);
		this.disabled = this.getInitValue('disabled', props.disabled, this.disabled);
		this.hint = this.getInitValue('hint', props.hint, this.hint);
		this.autoHintDetails = this.getInitValue('autoHintDetails', props.autoHintDetails, this.autoHintDetails);
		this.label = this.getInitValue('label', props.label, this.label);
		this.mask = this.getInitValue('mask', props.mask, this.mask);
		this.maxLength = this.getInitValue('maxLength', props.maxLength, this.maxLength);
		this.persistentHint = this.getInitValue('persistentHint', props.persistentHint, this.persistentHint);
		this.placeholder = this.getInitValue('placeholder', props.placeholder, this.placeholder);
		this.readonly = this.getInitValue('readonly', props.readonly, this.readonly);
		this.reverse = this.getInitValue('reverse', props.reverse, this.reverse);
		this.showBorder = this.getInitValue('showBorder', props.showBorder, this.showBorder);
		this.showHelper = this.getInitValue('showHelper', props.showHelper, this.showHelper);
		this.showLabel = this.getInitValue('showLabel', props.showLabel, this.showLabel);
		this.storePath = this.getInitValue('storePath', props.storePath, this.storePath);
		this.value = this.getInitValue('value', props.value, this.value);
		this.validations = this.getInitValue('validations', props.validations, this.validations);
		this.grid = this.getInitValue('grid', props.grid, this.grid);
		this.parseValidations(props.validations || {});
	}
 
	public onCreated(): void {
		super.onCreated();
 
		if (this.formParent) {
			this.formParent.registerInput(this);
		}
	}
 
	/**
	 * Validates input.
	 */
	public validate() {
		if (this.viewValidate) {
			return this.viewValidate();
		}
		return Promise.resolve([]);
	}
 
	/**
	 * Sets view validation method.
	 */
	public setViewValidate(viewValidate: (silent?: boolean) => Promise<string[]>) {
		this.viewValidate = viewValidate;
	}
 
	/**
	 * Sets view reset validation method.
	 */
	public setViewResetValidation(viewResetValidation: () => void) {
		this.viewResetValidation = viewResetValidation;
	}
 
	/**
	 * Reset all form validation errors.
	 * @throws Will throw if viewResetValidation is undefined
	 */
	public resetValidation() {
		if (this.viewResetValidation) {
			return this.viewResetValidation();
		}
 
		throw new Error('viewResetValidation method not assigned');
	}
 
	/**
	 * Adds parsed validations based on field validations.
	 * @param validations Field validations
	 */
	private parseValidations(validations: IDictionary<any>) {
		Object.keys(validations).forEach((name: string) => this.addValidation(name, validations[name]));
	}
 
	/**
	 * Adds input validation.
	 * @param name Validation name
	 * @param config Validation config
	 */
	public addValidation(name: string, config?: IDictionary<any>) {
		const validation = Validation.get(name)(config);
		(this.validations as any)[name] = config;
		this.parsedValidations[name] = validation;
		this.updateRules();
	}
 
	/**
	 * Removes input validation.
	 * @param name Validation name
	 */
	public removeValidation(name: string) {
		delete this.parsedValidations[name];
		delete this.validations[name];
		this.updateRules();
	}
 
	/**
	 * Removes all input validation.
	 */
	public clearValidations() {
		this.parsedValidations = {};
		this.validations = {};
		this.rules = [];
	}
 
	/**
	 * Updates input rules.
	 */
	protected updateRules() {
		this.rules = Object.values(this.parsedValidations).map(
			(validation: (value?: any) => boolean | string) => (value?: any) => {
				const testValue = value !== undefined ? value : this.value;
				return validation(testValue);
			},
		);
	}
 
	/**
	 * Input value.
	 */
	get value(): any {
		return this.internalValue;
	}
 
	set value(value: any) {
		if (this.internalValue !== value) {
			this.internalDisplayValue = this.formatter(value);
			this.internalValue = value;
		}
	}
 
	/**
	 * Input displayed value.
	 */
	get displayValue(): any {
		return this.internalDisplayValue;
	}
 
	set displayValue(value: any) {
		if (this.internalDisplayValue !== value) {
			const parsedValue = this.parser(value);
			this.value = parsedValue;
			if (!this.mask) {
				this.internalDisplayValue = value;
				return;
			}
 
			let { mask } = this;
			if (typeof mask === 'function') {
				mask = mask(parsedValue);
			}
			this.internalDisplayValue = Mask.convertAll(mask, value);
			this.internalValue = this.parser(this.internalDisplayValue);
		}
	}
 
	/**
	 * Retrieves a formatted value.
	 * @param value Any value
	 * @returns A Formatted value
	 */
	public formatter(value: any) {
		return this.formatterFn(value);
	}
 
	/**
	 * Retrieves a parsed value.
	 * @param value Any value
	 * @returns A parsed value
	 */
	public parser(value: any) {
		return this.parserFn(value);
	}
 
	/**
	 * Checks the input value are valid to all applied rules.
	 * @returns Input is valid
	 */
	public isValid(value?: any) {
		return this.rules.every((rule) => {
			const testValue = value !== undefined ? value : this.value;
			return typeof rule(testValue) !== 'string';
		});
	}
 
	private lastChangeValue: any = undefined;
 
	/**
	 * Triggered when the input value changes.
	 * @param event DOM event
	 * @param element Element clicked
	 */
	public change(event?: Event, element?: any) {
		if (this.value === '') this.value = null;
 
		if (this.value !== this.lastChangeValue) {
			this.lastChangeValue = this.value;
			this.callEvent('change', { event, element, component: this });
		}
	}
 
	protected lastInputValue: any = undefined;
 
	protected callInputEvent: ({ event, element, component }: IDictionary) => void = debounce(
		({ event, element, component }: IDictionary) => {
			this.callEvent('input', { event, element, component });
		},
		50,
	);
 
	/**
	 * Triggered when the data is inputted.
	 * @param event DOM event
	 * @param element Element focused
	 */
	public input(event?: Event, element?: any) {
		if (this.value !== this.lastInputValue) {
			this.lastInputValue = this.value;
			this.callInputEvent({ event, element, component: this });
		}
	}
 
	/**
	 * Triggered when a keyboard key is released.
	 * @param event DOM event
	 * @param element Element that lost the focus
	 */
	public keyup(event?: Event, element?: any) {
		this.callEvent('keyup', { event, element, component: this });
	}
 
	/**
	 * Triggered when the user presses a key on the keyboard.
	 * @param event DOM event
	 * @param element Element that lost the focus
	 */
	public keydown(event?: Event, element?: any) {
		this.callEvent('keydown', { event, element, component: this });
 
		if (!event?.defaultPrevented) {
			this.callEvent('afterKeydown', { event, element, component: this });
		}
	}
 
	private getFormParent() {
		let { parent } = this;
		while (parent && !(parent instanceof Form)) {
			parent = parent.parent;
		}
		return parent;
	}
}
 
FormatterParserProvider.registerFormatter('ZdInput', (value: any) => value);
FormatterParserProvider.registerParser('ZdInput', (value: any) => value);