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

100% Statements 200/200
100% Branches 103/103
100% Functions 44/44
100% Lines 189/189

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 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 53593x 93x 93x 93x   93x         93x                                     64x         64x         64x         64x         64x         64x         64x         64x         64x   64x   64x   64x   64x   64x         64x         64x           64x   64x             64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x   64x 64x 64x   64x 64x 64x   64x 64x       312x 312x   312x       186x 186x       69x       126x 126x       65x       7x 7x       64x 55x     64x       33x       24x                 2x 1x                   100x       10x 10x 10x 10x             9x 9x 9x             9x 3x     6x       7x       31x 31x 12x 12x 12x 12x   19x 6x 6x 6x   19x   31x       67x       1x       3x 3x 3x 3x       4x 2x   2x       9x 5x   4x                   73x   584x 73x 133x       12x 11x   1x       3x               6x 6x 6x 5x         11x 11x 11x   11x 11x         6x 6x             6x   5x 5x             11x           3x     8x               2x                 2x                   6x   5x 5x       5x   3x 3x       5x   3x   3x       5x   3x   3x       7x   4x   4x       1x 1x 1x 1x                   5x       6x 4x 3x     3x       93x                             42x 4x   38x 38x 38x   38x 38x 4x     34x 9x 2x     7x 7x 6x     7x 7x 7x     25x       93x                         31x 3x   28x 28x 28x   28x 19x     9x 6x     6x 3x   3x     6x   6x   6x 4x     5x       93x  
import { Config, FormatterParserProvider, I18n, Mask, Utils, dayjs } from '@zeedhi/core';
import isUndefined from 'lodash.isundefined';
import { InputFactory } from '../zd-input/input-factory';
import { TextInput } from '../zd-text-input/text-input';
import { ITime } from './interfaces';
import { TimeFormatSelector } from './time-format-selector';
 
/**
 * Base class for Time Picker component.
 */
export class Time extends TextInput implements ITime {
	/**
	 * Restricts which hours can be selected.
	 */
	public allowedHours?: any[];
 
	/**
	 * Restricts which minutes can be selected.
	 */
	public allowedMinutes?: any[];
 
	/**
	 * Restricts which seconds can be selected.
	 */
	public allowedSeconds?: any[];
 
	/**
	 * Input auto complete.
	 */
	public autofill = false;
 
	/**
	 * Defines the format of a time displayed in picker. Available options are ampm and 24hr.
	 */
	public timeFormat: string = Config.timeFormat || 'ampm'; // change props to pickerFormat
 
	/**
	 * Forces 100% width.
	 */
	public fullWidth = false;
 
	/**
	 * Maximum allowed time.
	 */
	public maxTime = '';
 
	/**
	 * Minimum allowed time.
	 */
	public minTime = '';
 
	/**
	 * Allows changing hour/minute with mouse scroll.
	 */
	public scrollable = false;
 
	/**
	 * Shows the time picker.
	 */
	public showTimePicker = false;
 
	/**
	 * Toggles the use of seconds in picker.
	 */
	public useSeconds = false;
 
	/**
	 * Width of the picker.
	 */
	public width: number | string = 290;
 
	protected formatterFn = FormatterParserProvider.getFormatter('ZdTime');
 
	protected parserFn = FormatterParserProvider.getParser('ZdTime');
 
	private isoFormatValue = 'HH:mm';
 
	private valueFormatInternal: string = Config.valueTimeFormat;
 
	private displayFormatInternal: string = Config.displayTimeFormat;
 
	/**
	 * Defines the time input format.
	 */
	public inputFormat?: string = Config.timeInputFormat;
 
	/**
	 * True when displayValue is valid
	 */
	protected isDisplayValid = true;
 
	protected initialMask?: string;
 
	protected isSimpleDisplay!: boolean;
 
	protected timeError = false;
 
	public inputMode?: string | undefined = 'none';
 
	/**
	 * Create a new Time Picker.
	 * @param props Time properties
	 */
	constructor(props: ITime) {
		super(props);
		this.allowedHours = this.getInitValue('allowedHours', props.allowedHours, this.allowedHours);
		this.allowedMinutes = this.getInitValue('allowedMinutes', props.allowedMinutes, this.allowedMinutes);
		this.allowedSeconds = this.getInitValue('allowedSeconds', props.allowedSeconds, this.allowedSeconds);
		this.timeFormat = this.getInitValue('timeFormat', props.timeFormat, this.timeFormat);
		this.fullWidth = this.getInitValue('fullWidth', props.fullWidth, this.fullWidth);
		this.maxTime = this.getInitValue('maxTime', props.maxTime, this.maxTime);
		this.minTime = this.getInitValue('minTime', props.minTime, this.minTime);
		this.scrollable = this.getInitValue('scrollable', props.scrollable, this.scrollable);
		this.showTimePicker = this.getInitValue('showTimePicker', props.showTimePicker, this.showTimePicker);
		this.useSeconds = this.getInitValue('useSeconds', props.useSeconds, this.useSeconds);
		this.width = this.getInitValue('width', props.width, this.width);
		this.autofill = this.getInitValue('autofill', props.autofill, this.autofill);
		this.timeValidation = this.timeValidation.bind(this);
 
		this.valueFormat = this.getInitValue('valueFormat', props.valueFormat, this.valueFormatInternal);
		this.displayFormat = this.getInitValue('displayFormat', props.displayFormat, this.displayFormatInternal);
		this.inputFormat = this.getInitValue('inputFormat', props.inputFormat, this.inputFormat);
 
		this.timeAllowedValidation = this.timeAllowedValidation.bind(this);
		this.rules.push(this.timeValidation, this.timeAllowedValidation);
		this.mask = this.getInitValue('mask', props.mask, undefined);
 
		this.initialMask = this.getInitialMask();
		this.isSimpleDisplay = this.isSimpleFormat(this.displayFormat);
	}
 
	private getFormat(format: string, timeFormat: string) {
		const timeFormatSelector = new TimeFormatSelector();
		const selectedFormat = timeFormatSelector.getFormat(format, timeFormat, this.useSeconds);
 
		return selectedFormat;
	}
 
	public get displayFormat() {
		this.displayFormatInternal = this.getFormat(this.displayFormatInternal, this.timeFormat);
		return this.displayFormatInternal;
	}
 
	public set displayFormat(value: string) {
		this.displayFormatInternal = value;
	}
 
	public get valueFormat() {
		this.valueFormatInternal = this.getFormat(this.valueFormatInternal, '24hr');
		return this.valueFormatInternal;
	}
 
	public set valueFormat(value: string) {
		this.valueFormatInternal = value;
	}
 
	private get isoFormat() {
		this.isoFormatValue = this.useSeconds ? 'HH:mm:ss' : 'HH:mm';
		return this.isoFormatValue;
	}
 
	private getInitialMask() {
		if (isUndefined(this.mask)) {
			this.mask = this.inputFormat && this.maskFormat(this.inputFormat);
		}
 
		return this.mask;
	}
 
	public formatter(value: string): string {
		return this.formatterFn(value, this);
	}
 
	public parser(value: string): any {
		return this.parserFn(value, this);
	}
 
	/**
	 * Triggered when date is clicked.
	 * @param event
	 * @param element
	 */
	public selectTime(time: string, event?: Event, element?: any) {
		if (this.events.onSelectTime && typeof this.events.onSelectTime === 'function') {
			this.events.onSelectTime({
				time,
				event,
				element,
				component: this,
			});
		}
	}
 
	get displayValue() {
		return this.internalDisplayValue;
	}
 
	set displayValue(newValue: string) {
		this.timeError = false;
		this.internalDisplayValue = newValue;
		this.internalValue = this.parser(newValue);
		this.value = this.internalValue; // forces value accessor to be called if necessary
	}
 
	/**
	 * Assign the updated mask to mask property
	 */
	public updateMask() {
		this.isSimpleDisplay = this.isSimpleFormat(this.displayFormat);
		this.mask = this.getUpdatedMask();
		return this.mask;
	}
 
	/**
	 * Gets the updated masked, based on displayFormat if the initial mask is undefined
	 */
	protected getUpdatedMask(): string {
		if (isUndefined(this.initialMask)) {
			return this.maskFormat(this.displayFormat);
		}
 
		return this.mask;
	}
 
	protected maskFormat(format: string) {
		return format.replace(/[A-Za-z]/gi, '#');
	}
 
	public setTimeValue(displayValue: string) {
		const lastValue = this.displayValue;
		if (this.isValidTime(displayValue, this.displayFormat)) {
			this.internalDisplayValue = displayValue;
			this.internalValue = this.parser(displayValue);
			this.timeError = false;
			if (lastValue !== this.displayValue) this.change(this.value);
		} else {
			if (!displayValue) {
				this.internalDisplayValue = displayValue;
				this.internalValue = null;
				if (lastValue !== this.displayValue) this.change(this.value);
			}
			this.timeError = !!displayValue;
		}
		this.value = this.internalValue; // forces value accessor to be called if necessary
	}
 
	public isValidTime(value: string, format: string | undefined, strict = true): boolean {
		return dayjs(value, format, strict).isValid();
	}
 
	get isoValue() {
		return this.formatISOTimeValue(this.value);
	}
 
	set isoValue(newValue: string) {
		const lastValue = this.value;
		this.timeError = false;
		this.value = this.parseISOTimeValue(newValue);
		if (lastValue !== this.value) this.change(this.value);
	}
 
	public formatISOTimeValue(value: string): string {
		if (value && this.isValidTime(value, this.valueFormat)) {
			return dayjs(value, this.valueFormat).format(this.isoFormat);
		}
		return '';
	}
 
	public parseISOTimeValue(value: string): any {
		if (value && this.isValidTime(value, this.valueFormat)) {
			return dayjs(value, this.isoFormat).format(this.valueFormat);
		}
		return null;
	}
 
	/**
	 * Checks if a time format is simple.
	 * Simple time formats are the ones that consists only of 'HH', 'mm', 'mm' or 'YYYY', and mask delimiters
	 * @param format The format to be checked
	 * @returns true if it is simple, false otherwise
	 */
	protected isSimpleFormat(format: string): boolean {
		const simpleTokens = ['HH', 'mm', 'ss', 'hh', 'A', 'a', 'p', 'P'];
		// remove the simple tokens from the string
		const replaced = simpleTokens.reduce((result, token) => result.replace(token, ''), format);
		const chars = replaced.split('');
		return chars.length ? chars.every((char) => Mask.isMaskDelimiter(char)) : true;
	}
 
	public timeValidation(): boolean | string {
		if (this.isValidTime(this.displayValue, this.displayFormat) || !this.displayValue) {
			return true;
		}
		return I18n.translate('VALIDATION_INVALID_TIME');
	}
 
	public timeAllowedValidation(): boolean | string {
		return (
			!this.displayValue ||
			(this.isValidTime(this.displayValue, this.displayFormat) && this.isTimeAllowed()) ||
			I18n.translate('VALIDATION_TIME_NOT_ALLOWED')
		);
	}
 
	public click(event?: Event, element?: any) {
		const clickEvent = event || new MouseEvent('click');
		super.click(clickEvent, element);
		if (!clickEvent.defaultPrevented) {
			this.showTimePicker = !this.showTimePicker;
		}
	}
 
	public blur(event: Event, element: any) {
		this.removeTimeMask();
		this.setTimeValue(this.formatter(this.value));
		super.blur(event, element);
 
		if (!Utils.isMobile()) {
			this.showTimePicker = false;
		}
	}
 
	public focus(event: Event, element: any) {
		this.addTimeMask();
		super.focus(event, element);
	}
 
	/**
	 * Add date mask
	 */
	protected addTimeMask() {
		if (!this.value) return;
 
		this.mask = this.initialMask;
		this.internalDisplayValue = dayjs(this.value, this.valueFormat).format(this.inputFormat || this.displayFormat);
	}
 
	/**
	 * Removes the component mask if value is valid
	 */
	protected removeTimeMask() {
		if (
			isUndefined(this.initialMask) ||
			!this.value ||
			this.timeError ||
			!this.isValidTime(this.value, this.valueFormat)
		) {
			return;
		}
 
		this.mask = '';
	}
 
	/**
	 * Checks if value is valid according to valueFormat and if displayValue
	 * is true
	 */
	public isFullyValid(value: string = this.value) {
		return this.isValidTime(value, this.valueFormat, true) && this.isDisplayValid;
	}
 
	/**
	 * Last invalid value passed to formatter
	 */
	// private lastInvalid: string = '';
 
	public isTimeAllowed(value: string = this.value) {
		return (
			this.isSameOrAfterMin(value) &&
			this.isSameOrBeforeMax(value) &&
			this.isHourAllowed(value) &&
			this.isMinuteAllowed(value) &&
			this.isSecondAllowed(value)
		);
	}
 
	public isSameOrAfterMin(value: string) {
		if (!this.minTime) return true;
 
		const min = dayjs(this.minTime, this.valueFormat);
		return dayjs(value, this.valueFormat).isSame(min) || dayjs(value, this.valueFormat).isAfter(min);
	}
 
	public isSameOrBeforeMax(value: string) {
		if (!this.maxTime) return true;
 
		const max = dayjs(this.maxTime, this.valueFormat);
		return dayjs(value, this.valueFormat).isSame(max) || dayjs(value, this.valueFormat).isBefore(max);
	}
 
	public isHourAllowed(value: string) {
		if (!this.allowedHours) return true;
 
		const hour = dayjs(value, this.valueFormat).hour();
 
		return this.allowedHours.includes(hour);
	}
 
	public isMinuteAllowed(value: string) {
		if (!this.allowedMinutes) return true;
 
		const minute = dayjs(value, this.valueFormat).minute();
 
		return this.allowedMinutes.includes(minute);
	}
 
	public isSecondAllowed(value: string) {
		if (!this.allowedSeconds) return true;
 
		const second = dayjs(value, this.valueFormat).second();
 
		return this.allowedSeconds.includes(second);
	}
 
	public clear() {
		this.value = null;
		this.change(this.value);
		if (typeof this.events?.onClear === 'function') {
			this.events.onClear({
				component: this,
				value: this.value,
			});
		}
	}
	/**
	 * Converts a date format to a mask
	 */
	private toMask(format: string) {
		return format.replace(/[A-Za-z]/gi, '#'); // .split('').map((char: string) => (char === '#' ? /\d/ : char));
	}
 
	public getMask() {
		if (this.mask && !this.mask.includes('{{') && !this.mask.includes('}}')) {
			if (this.isFocused) {
				return this.toMask(this.displayFormat || '');
			}
		}
		return '';
	}
}
 
FormatterParserProvider.registerFormatter(
	'ZdTime',
	(
		value: string,
		{
			valueFormat = Config.valueTimeFormat,
			displayFormat = Config.displayTimeFormat,
			inputFormat = Config.timeInputFormat,
			timeFormat = Config.timeFormat || 'ampm',
			useSeconds = false,
			mask = '',
			initialMask,
			isSimpleDisplay = false,
		}: any = {},
	) => {
		if (!value) {
			return '';
		}
		const timeFormatSelector = new TimeFormatSelector();
		const timeDisplayFormat = timeFormatSelector.getFormat(displayFormat, timeFormat, useSeconds);
		const timeValueFormat = timeFormatSelector.getFormat(valueFormat, '24hr', useSeconds);
 
		const isTimeValid = dayjs(value, timeValueFormat, true).isValid();
		if (!isTimeValid) {
			return value;
		}
 
		if (mask && initialMask) {
			if (inputFormat) {
				return dayjs(value, timeValueFormat).format(inputFormat);
			}
 
			let valueToUnmask = value;
			if (isSimpleDisplay) {
				valueToUnmask = dayjs(value, timeValueFormat).format(timeDisplayFormat);
			}
 
			const unmasked = Mask.getValueWithoutMask(valueToUnmask);
			const masked = Mask.getValueWithMask(unmasked, mask);
			return masked;
		}
 
		return dayjs(value, timeValueFormat).format(timeDisplayFormat);
	},
);
 
FormatterParserProvider.registerParser(
	'ZdTime',
	(
		value: string,
		{
			displayFormat = Config.displayTimeFormat,
			valueFormat = Config.valueTimeFormat,
			timeFormat = Config.timeFormat || 'ampm',
			useSeconds = false,
			mask = '',
			initialMask,
		}: any = {},
	) => {
		if (!value) {
			return null;
		}
		const timeFormatSelector = new TimeFormatSelector();
		const timeDisplayFormat = timeFormatSelector.getFormat(displayFormat, timeFormat, useSeconds);
		const timeValueFormat = timeFormatSelector.getFormat(valueFormat, '24hr', useSeconds);
 
		if (dayjs(value, timeDisplayFormat, true).isValid()) {
			return dayjs(value, timeDisplayFormat).format(timeValueFormat);
		}
 
		if (mask && Mask.checkMask(value, mask)) {
			const unmasked = Mask.getValueWithoutMask(value);
			let masked;
 
			if (!initialMask) {
				const displayFmtMask = timeDisplayFormat.replace(/[A-Za-z]/gi, '#');
 
				masked = Mask.getValueWithMask(unmasked, displayFmtMask);
			}
 
			const timeFmtMask = timeValueFormat.replace(/[A-Za-z]/gi, '#');
 
			masked = Mask.getValueWithMask(unmasked, timeFmtMask);
 
			if (dayjs(masked, timeValueFormat, true).format(timeValueFormat) === masked) {
				return masked;
			}
		}
		return value;
	},
);
 
InputFactory.register('ZdTime', Time);