All files / src/components/zd-date-range date-range.ts

100% Statements 246/246
100% Branches 127/127
100% Functions 50/50
100% Lines 220/220

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 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 59493x   93x 93x 93x 93x 93x   93x         86x         86x         86x         86x         86x         86x         86x         86x         86x         86x           117x       86x     86x           86x         86x         86x         86x         86x   86x   86x   86x   86x   86x                                                                                             2x 2x       43x       21x       84x       8x 8x 8x 1x 8x       261x       173x   172x 109x 109x 109x 109x     63x   32x 32x   32x 32x 32x 32x   32x 23x                 23x 23x 23x   9x   9x 43x 43x   9x       29x 29x 29x 11x 11x 11x 11x   18x 5x 5x 5x   18x   29x                   32x 28x       32x 32x   26x 14x 14x 13x   12x       43x 43x 43x   35x 35x 35x   34x 34x 34x   33x 2x     31x       55x       1x       3x 3x 3x 3x           4x 3x   4x 4x 3x 2x     4x       9x 9x 8x 10x 8x       9x       17x 8x         14x       6x 6x 6x 5x         8x 8x 8x 8x   8x 8x         17x 17x               17x       15x 11x 11x   14x 8x 8x     13x   13x 13x 6x 6x   7x 7x             3x                 2x 2x 1x       86x   86x     18x   18x 17x 17x     18x 18x   18x 16x 16x 16x     2x 2x       15x 15x       19x   11x   5x       10x   10x 10x   10x 3x 13x 1x 1x         9x   9x 9x 7x 7x     86x     8x       52x       4x               93x                                   49x 1x     48x 68x   66x   66x 14x     52x   52x 46x     6x     48x       93x                                   29x 1x     28x   28x 15x   13x     28x 28x 43x   42x     41x 3x 3x 2x     1x       38x 38x 4x     34x         93x  
import { Config, DateHelper, FormatterParserProvider, I18n, Mask, Utils, dayjs } from '@zeedhi/core';
import { IDateRange } from './interfaces';
import { isDateAllowed } from '../../utils/date-utils/date-utils';
import { InputFactory } from '../zd-input/input-factory';
import { TextInput } from '../zd-text-input/text-input';
import { getDateRangeMask, getMaskAndUnitMask } from './utils';
import { validateThenFormat } from '../zd-date-input/utils';
 
export class DateRange extends TextInput implements IDateRange {
	public allowedDates?: string[] | ((date: string) => boolean);
	/**
	 * Input auto complete.
	 */
	public autocomplete = false;
 
	/**
	 * Defines the date format.
	 */
	public dateFormat: string = Config.dateFormat;
 
	/**
	 * Defines the date format displayed.
	 */
	public displayFormat: string = Config.displayFormat;
 
	/**
	 * Defines the date input format.
	 */
	public inputFormat?: string = Config.dateInputFormat;
 
	/**
	 * Shows the date picker.
	 */
	public showDatePicker = false;
 
	/**
	 * Sets the first day of the week, starting with 0 for Sunday.
	 */
	public firstDayOfWeek: number | string = 0;
 
	/**
	 * Forces 100% width.
	 */
	public fullWidth = false;
 
	/**
	 * Sets the locale. Accepts a string with a BCP 47 language tag.
	 */
	public locale?: string = I18n.instance.language;
 
	/**
	 * Allows changing displayed month with mouse scroll
	 */
	public scrollable = false;
 
	/**
	 * Toggles visibility of the week numbers in the body of the calendar.
	 */
	public showWeek = false;
 
	/**
	 * Character that will separate the two dates
	 */
	public get splitter(): string {
		return I18n.translate(this.internalSplitter);
	}
 
	public set splitter(splitter: string) {
		this.internalSplitter = splitter;
	}
 
	private internalSplitter = ' ~ ';
 
	/**
	 * Width of the picker.
	 */
 
	public width: number | string = 248;
 
	/**
	 * Helper options.
	 */
	public helperOptions?: string[] = [];
 
	/**
	 * Max value allowed.
	 */
	public max?: string = '';
 
	/**
	 * Min value allowed.
	 */
	public min?: string = '';
 
	/**
	 * Helper value.
	 */
	public helperValue?: string = '';
 
	protected isoFormat = 'YYYY-MM-DD';
 
	protected dateError = false;
 
	protected formatterFn = FormatterParserProvider.getFormatter('ZdDateRange');
 
	protected parserFn = FormatterParserProvider.getParser('ZdDateRange');
 
	public inputMode?: string | undefined = 'none';
 
	/* istanbul ignore next */
	/**
	 * Creates a new Date.
	 * @param props Date properties
	 */
	constructor(props: IDateRange) {
		super(props);
		// Add this logic to resolve template strings
		if (typeof props.appendIcon === 'string' && props.appendIcon.startsWith('{{') && props.appendIcon.endsWith('}}')) {
			const match = props.appendIcon.match(/{{(.*?)}}/);
			if (match) {
				const path = match[1].trim().split('.');
				let value: any = window;
				for (const key of path) {
					value = value?.[key];
				}
				this.appendIcon = value ?? props.appendIcon;
			} else {
				this.appendIcon = props.appendIcon;
			}
		} else {
			this.appendIcon = this.getInitValue('appendIcon', props.appendIcon, 'calendar');
		}
		this.allowedDates = this.getInitValue('allowedDates', props.allowedDates, this.allowedDates);
		this.autocomplete = this.getInitValue('autocomplete', props.autocomplete, this.autocomplete);
		this.dateFormat = this.getInitValue('dateFormat', props.dateFormat, this.dateFormat);
		this.dateValidation = this.dateValidation.bind(this);
		this.displayFormat = this.getInitValue('displayFormat', props.displayFormat, this.displayFormat);
		this.inputFormat = this.getInitValue('inputFormat', props.inputFormat, this.inputFormat);
		this.firstDayOfWeek = this.getInitValue('firstDayOfWeek', props.firstDayOfWeek, this.firstDayOfWeek);
		this.fullWidth = this.getInitValue('fullWidth', props.fullWidth, this.fullWidth);
		this.locale = this.getInitValue('locale', props.locale, this.locale);
		this.scrollable = this.getInitValue('scrollable', props.scrollable, this.scrollable);
		this.showDatePicker = this.getInitValue('showDatePicker', props.showDatePicker, this.showDatePicker);
		this.showWeek = this.getInitValue('showWeek', props.showWeek, this.showWeek);
		this.splitter = this.getInitValue('splitter', props.splitter, this.internalSplitter);
		this.width = this.getInitValue('width', props.width, this.width);
		this.helperOptions = this.getInitValue('helperOptions', props.helperOptions, this.helperOptions);
		this.helperValue = this.getInitValue('helperValue', props.helperValue, this.helperValue);
		this.min = this.getInitValue('min', props.min, this.min);
		this.max = this.getInitValue('max', props.max, this.max);
		this.rules.push(this.dateValidation);
	}
 
	public appendIconClick(event: Event, element: any) {
		this.iconClick(event, element);
		super.appendIconClick(event, element);
	}
 
	public formatter(value: any): string {
		return this.formatterFn(value, this);
	}
 
	public parser(value: string): any {
		return this.parserFn(value, this);
	}
 
	get displayValue() {
		return this.internalDisplayValue;
	}
 
	set displayValue(newValue: string) {
		this.dateError = false;
		this.internalDisplayValue = newValue;
		if (newValue) this.internalValue = this.parser(newValue);
		else this.internalValue = [];
		this.value = this.internalValue; // forces value accessor to be called if necessary
	}
 
	get value(): string[] {
		return this.internalValue;
	}
 
	set value(value: unknown) {
		if (!Array.isArray(value) && value !== null && value !== undefined) return;
 
		if (!value || value.length === 0) {
			this.internalValue = [];
			this.internalDisplayValue = '';
			this.dateObject = [];
			return;
		}
 
		if (this.internalValue === value) return;
 
		this.internalDisplayValue = this.formatter(value);
		this.internalValue = value;
 
		const [startDate, endDate] = value;
		const isStartValid = this.isValidFormatDate(startDate, this.dateFormat);
		const isEndValid = !endDate || this.isValidFormatDate(endDate, this.dateFormat);
		const areDatesValid = isStartValid && isEndValid;
 
		if (areDatesValid) {
			this.dateObject = this.getDatesInRange(startDate, endDate);
		}
	}
 
	/**
	 * Returns all days ranging from start to end as dayjs objects
	 * @returns an array of dayjs objects containing all days between start and end
	 */
	private getDatesInRange(startDateStr: string, endDateStr?: string): dayjs.Dayjs[] {
		const dates: dayjs.Dayjs[] = [];
		let startDate = dayjs(startDateStr, this.dateFormat);
		if (!endDateStr) return [startDate];
 
		const endDate = dayjs(endDateStr, this.dateFormat);
 
		while (startDate.isBefore(endDate) || startDate.isSame(endDate)) {
			dates.push(startDate);
			startDate = startDate.add(1, 'day');
		}
		return dates;
	};
 
	public setDateValue(displayValue: string) {
		const lastValue = this.displayValue;
		const values = this.splitValues(displayValue);
		if (this.isValidDateArray(this.displayFormat, values)) {
			this.internalDisplayValue = displayValue;
			this.internalValue = this.parser(displayValue);
			this.dateError = false;
			if (lastValue !== this.displayValue) this.change();
		} else {
			if (!displayValue) {
				this.internalDisplayValue = displayValue;
				this.internalValue = [];
				if (lastValue !== this.displayValue) this.change();
			}
			this.dateError = !!displayValue;
		}
		this.value = this.internalValue; // forces value accessor to be called if necessary
	}
 
	/**
	 * Faz a validação do array de datas
	 * @param format o formato da data
	 * @param values o array de datas
	 * @returns true se todos os valores forem validados
	 * */
	public isValidDateArray(format: string, values?: string[]) {
		if (!values || values.length < 2) return false;
		return values.every((value) => this.isValidDate(value, format));
	}
 
	private splitValues(value: string) {
		let splitedValue: string[] = [];
		if (!value) return splitedValue;
 
		if (value.indexOf(this.splitter) !== -1) {
			splitedValue = value.split(this.splitter);
			if (splitedValue[1] === '') return [splitedValue[0]];
			return splitedValue;
		}
		return [value];
	}
 
	public isValidDate(value: string, format: string, strict = true): boolean {
		const date = dayjs(value, format, strict);
		const isValidFormat = date.isValid();
		if (!isValidFormat) return false;
 
		const minDate = this.min ? dayjs(this.min, this.dateFormat) : null;
		const isValidMin = !minDate || date.isAfter(minDate) || date.isSame(minDate);
		if (!isValidMin) return false;
 
		const maxDate = this.max ? dayjs(this.max, this.dateFormat) : null;
		const isValidMax = !maxDate || date.isBefore(maxDate) || date.isSame(maxDate);
		if (!isValidMax) return false;
 
		if (!this.getAllowedDates(dayjs(value, format).toDate())) {
			return false;
		}
 
		return true;
	}
 
	public isValidFormatDate(value: string, format: string, strict = true): boolean {
		return dayjs(value, format, strict).isValid();
	}
 
	get isoRangeValue() {
		return this.formatISODateRangeValue(this.value);
	}
 
	set isoRangeValue(newValue: string[]) {
		const lastValue: string[] = this.value;
		this.dateError = false;
		this.value = this.parseISODateRangeValue(newValue);
		if (!Utils.isEqual(lastValue, this.value)) this.change();
	}
 
	public formatISODateRangeValue(dates: string[] | string): string[] {
		let splitedValue: string[];
 
		if (Array.isArray(dates)) splitedValue = dates;
		else splitedValue = this.splitValues(dates);
 
		const formattedValue: string[] = [];
		splitedValue.forEach((value) => {
			if (value && this.isValidFormatDate(value, this.dateFormat)) {
				formattedValue.push(dayjs(value, this.dateFormat, true).format(this.isoFormat));
			}
		});
		return formattedValue;
	}
 
	public parseISODateRangeValue(values: string[]): any {
		const parsedValue: string[] = [];
		if (values.length) {
			values.forEach((value) => {
				if (value && this.isValidFormatDate(value, this.isoFormat)) {
					parsedValue.push(dayjs(value, this.isoFormat, true).format(this.dateFormat));
				}
			});
		}
		return this.sortDates(parsedValue);
	}
 
	private sortDates(parsedValue: string[]): string[] {
		return parsedValue.sort((a: string, b: string) =>
			dayjs(a, this.dateFormat).isAfter(dayjs(b, this.dateFormat)) ? 1 : -1,
		);
	}
 
	public dateValidation(): boolean | string {
		return !this.dateError || I18n.translate('VALIDATION_INVALID_DATE');
	}
 
	public click(event?: Event, element?: any) {
		const clickEvent = event || new MouseEvent('click');
		super.click(clickEvent, element);
		if (!clickEvent.defaultPrevented) {
			this.showDatePicker = !this.showDatePicker;
		}
	}
 
	public blur(event: Event, element: any) {
		super.blur(event, element);
		if (this.value) {
			this.value = this.sortDates(this.value);
			this.setDateValue(this.formatter(this.value));
		}
		if (!Utils.isMobile()) {
			this.showDatePicker = false;
		}
	}
 
	public focus(event: Event, element: any) {
		super.focus(event, element);
		this.updateDisplayValue();
	}
 
	/**
	 * Update the displayValue. When using `inputFormat`, on focus we
	 * must switch to using it as the current format.
	 */
	protected updateDisplayValue() {
		if (!this.inputFormat || !this.value) return;
 
		let firstDate: dayjs.Dayjs | undefined;
		let lastDate: dayjs.Dayjs | undefined;
		if (this.value[0]) {
			firstDate = dayjs(this.value[0], this.dateFormat, true);
			if (!firstDate.isValid()) return;
		}
		if (this.value[1]) {
			lastDate = dayjs(this.value[1], this.dateFormat, true);
			if (!lastDate.isValid()) return;
		}
 
		const format = this.inputFormat;
 
		const firstDateString = firstDate ? firstDate.format(format) : '';
		if (!lastDate) {
			this.internalDisplayValue = firstDateString;
			return;
		}
		const lastDateString = lastDate.format(format);
		this.internalDisplayValue = `${firstDateString}${this.splitter}${lastDateString}`;
	}
 
	/**
	 * Toggle showDatePicker value
	 */
	public togglePicker() {
		this.showDatePicker = !this.showDatePicker;
	}
 
	/**
	 * Triggered when the appended icon is clicked.
	 * @param event DOM event
	 * @param element Text input
	 */
	public iconClick(event: Event, element: any) {
		super.click(event, element);
		if (!event.defaultPrevented) {
			this.togglePicker();
		}
	}
 
	private previousHint = '';
 
	private previousPersistentHint = false;
 
	public updateHelperHint(helperValue: string) {
		const previousHelperHint = this.helperValue ? DateHelper.getLabel(this.helperValue) : '';
 
		if (!this.hint || previousHelperHint !== this.hint) {
			this.previousHint = this.hint;
			this.previousPersistentHint = this.persistentHint;
		}
 
		this.helperValue = helperValue;
		const label = DateHelper.getLabel(helperValue);
 
		if (!helperValue || !label) {
			this.hint = this.previousHint;
			this.persistentHint = this.previousPersistentHint;
			return;
		}
 
		this.hint = label;
		this.persistentHint = true;
	}
 
	public change(event?: Event, element?: any): void {
		super.change(event, element);
		this.updateHelperHint('');
	}
 
	private getExtremities<T>(arr: T[]) {
		if (arr.length === 0) return [];
 
		if (arr.length === 1) return [arr[0]];
 
		return [arr[0], arr[arr.length - 1]];
	}
 
	public setNativeDate(dates: Date[]) {
		this.dateError = false;
 
		const dayjsDates = (dates || []).map((d) => dayjs(d));
		const [start, end] = this.getExtremities(dayjsDates);
 
		if (start && end) {
			for (let d = start; d.isBefore(end) || d.isSame(end); d = d.add(1, 'day')) {
				if (!this.getAllowedDates(d.toDate())) {
					this.dateError = true;
					return;
				}
			}
		}
 
		this.dateObject = (dates || []).map((obj) => dayjs(obj));
 
		const extremityDates = this.getExtremities(this.dateObject);
		this.value = extremityDates
			.filter((obj): obj is dayjs.Dayjs => obj !== null)
			.map((obj) => obj.format(this.dateFormat));
	}
 
	private dateObject: (dayjs.Dayjs | null)[] = [];
 
	public getNativeDate() {
		return this.dateObject.filter((obj): obj is dayjs.Dayjs => obj !== null).map((obj) => obj.toDate());
	}
 
	public getAllowedDates(date: Date) {
		return isDateAllowed(date, this.dateFormat, this.allowedDates);
	}
 
	public getMask() {
		return getDateRangeMask(
			this.inputFormat || this.displayFormat || '',
			this.splitter,
			this.isFocused,
		)
	}
}
 
FormatterParserProvider.registerFormatter(
	'ZdDateRange',
	(
		value: string[],
		{
			dateFormat = Config.dateFormat,
			displayFormat = Config.displayFormat,
			inputFormat = Config.dateInputFormat,
			splitter = ' ~ ',
			isFocused,
		}: {
			dateFormat?: string;
			displayFormat?: string;
			inputFormat?: string;
			splitter?: string;
			isFocused?: boolean;
		} = {},
	) => {
		if (!value || value.length === 0 || (value.length === 1 && !value[0])) {
			return '';
		}
 
		const formattedValues = value
		.filter((date) => !!date)
		.map((date) => {
			const isDateValid = dayjs(date, dateFormat, true).isValid();
 
			if (!isDateValid) {
				return date;
			}
 
			const { mask } = getMaskAndUnitMask({ inputFormat, displayFormat, splitter, isFocused });
 
			if (!mask || !inputFormat || !isFocused) {
				return dayjs(date, dateFormat).format(displayFormat);
			}
 
			return dayjs(date, dateFormat).format(inputFormat);
		});
 
		return formattedValues.join(splitter);
	},
);
 
FormatterParserProvider.registerParser(
	'ZdDateRange',
	(
		value: string,
		{
			dateFormat = Config.dateFormat,
			displayFormat = Config.displayFormat,
			inputFormat = Config.dateInputFormat,
			splitter = ' ~ ',
			isFocused,
		}: {
			dateFormat?: string;
			displayFormat?: string;
			inputFormat?: string;
			splitter?: string;
			isFocused?: boolean;
		} = {},
	) => {
		if (!value) {
			return [];
		}
 
		let splittedValue: string[] = [];
 
		if (value.indexOf(splitter) !== -1) {
			splittedValue = value.split(splitter);
		} else {
			splittedValue.push(value);
		}
 
		const { unitMask } = getMaskAndUnitMask({ inputFormat, displayFormat, splitter, isFocused });
		return splittedValue
		.filter((date) => !!date)
		.map((date) => {
			if (!Mask.checkMask(date, unitMask)) return date;
 
			// when using inputFormat and focused, should parse according to inputFormat
			if (inputFormat && isFocused) {
				const { valid, newValue } = validateThenFormat(date, inputFormat, dateFormat);
				if (valid) {
					return newValue;
				}
 
				return date;
			}
 
			// should parse according to displayFormat
			const { valid, newValue } = validateThenFormat(date, displayFormat, dateFormat);
			if (!valid) {
				return date;
			}
 
			return newValue;
		});
	},
);
 
InputFactory.register('ZdDateRange', DateRange);