All files date-time.ts

100% Statements 174/174
100% Branches 78/78
100% Functions 31/31
100% Lines 168/168

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 4491x     1x 1x     1x       42x         42x                   42x         42x         42x         42x         42x         42x         42x         42x                             42x   42x         42x         42x         42x         42x                             42x   42x   42x   42x   42x                 42x     42x 42x   42x 42x   42x 42x   42x 42x   42x 42x 42x 42x 42x 42x 42x   42x 42x 42x 42x 42x 42x   42x 42x 42x 42x   42x 42x 42x       8x       1x       3x 3x 3x 3x                   51x     357x 51x 183x       4x 2x   2x       6x 4x   2x     27x   29x     6x 6x 6x 5x 5x 5x 2x 2x           42x 33x     42x       42x 37x   5x       42x       42x       11x 11x 11x 11x       6x 6x       15x 15x 2x 2x               6x   5x 5x             11x       6x     5x             9x 9x 9x             9x 3x     6x       29x 29x 16x 16x 16x 16x   13x 4x 4x 4x   13x   29x       80x       11x 11x 11x 11x       9x       56x                 2x 1x             1x               33x 2x     31x   31x 9x     22x 7x 3x     4x 4x 3x     4x 4x 4x     15x     1x             37x 3x   34x 23x   11x 5x 2x 1x     1x     3x   3x 3x   3x   3x 1x       2x   2x 2x 1x     7x    
import {
  Config, dayjs, FormatterParserProvider, I18n, Mask,
} from '@zeedhi/core';
import isUndefined from 'lodash.isundefined';
import { TextInput } from '@zeedhi/common';
import { IDateTime, IDateTimeEvents } from './interfaces';
 
export class DateTime extends TextInput implements IDateTime {
/**
 * Restricts which dates can be selected.
 */
  public allowedDates?: ((date: string) => boolean) | string[] = undefined;
 
  /**
* Events registered to the date.
*/
  public activeTab: string = 'calendarTab';
 
  /**
* Events registered to the date.
*/
  public events!: IDateTimeEvents;
 
  /**
* Format used in time value
*/
  public timeFormat: string = 'HH:mm:ss';
 
  /**
 * Format used in time value
 */
  public dateFormat: string = Config.dateFormat;
 
  /**
   * Sets the locale. Accepts a string with a BCP 47 language tag.
  */
  public locale?: string = I18n.instance.language;
 
  /**
   * Toggles visibility of the week numbers in the body of the calendar.
   */
  public showWeek: boolean = false;
 
  /**
* Defines the dateTime format.
*/
  public dateTimeFormat: string = Config.dateTimeFormat;
 
  /**
* Defines the date format.
*/
  public displayDateFormat?: string = Config.displayFormat;
 
  /**
* Defines the time format.
*/
  public displayTimeFormat: string = Config.displayTimeFormat || 'HH:mm:ss';
 
  /**
   * Defines the Time input format.
 */
  public inputFormat?: string = Config.dateInputFormat;
 
  /**
   * Defines the date input format.
 */
  public dateInputFormat?: string;
 
  /**
   * Defines the time input format.
 */
  public timeInputFormat?: string;
 
  /**
   * Toggles the use of seconds in picker.
 */
  public useSeconds: boolean = false;
 
  public showDateTimePicker: boolean = false;
 
  /**
* Defines the format of a time displayed in picker. Available options are ampm and 24hr.
*/
  public timePickerFormat: string = Config.timeFormat || 'ampm';
 
  /**
* Place AM/PM switch in title, not near the clock.
*/
  public ampmInTitle: boolean = true;
 
  /**
   * Sets the first day of the week, starting with 0 for Sunday.
   */
  public firstDayOfWeek: number | string = 0;
 
  /**
* Maximum allowed time.
*/
  public maxTime: string = '';
 
  /**
   * Define the date value.
  */
  public dateValue?: any;
 
  /**
   * Define the time value.
  */
  public timeValue?: any;
 
  /**
* Minimum allowed time.
*/
  public minTime: string = '';
 
  protected isoFormat: string = 'YYYY-MM-DD HH:mm:ss';
 
  protected dateError: boolean = false;
 
  protected formatterFn = FormatterParserProvider.getFormatter('ZdDateTime');
 
  protected parserFn = FormatterParserProvider.getParser('ZdDateTime');
 
  protected initialMask?: string;
 
  protected isSimpleDisplay!: boolean;
 
  /**
* Format used to display the value
*/
  public displayFormat: string = Config.displayDateTimeFormat;
 
  constructor(props: IDateTime) {
    super(props);
    this.dateValidation = this.dateValidation.bind(this);
 
    this.dateFormat = this.getInitValue('dateFormat', props.dateFormat, this.dateFormat);
    this.timeFormat = this.getInitValue('timeFormat', props.timeFormat, this.timeFormat);
 
    this.dateInputFormat = this.getInitValue('dateInputFormat', props.dateInputFormat, this.dateInputFormat);
    this.timeInputFormat = this.getInitValue('timeInputFormat', props.timeInputFormat, this.timeInputFormat);
 
    this.displayTimeFormat = this.getInitValue('displayTimeFormat', props.displayTimeFormat, this.displayTimeFormat);
    this.displayDateFormat = this.getInitValue('displayDateFormat', props.displayDateFormat, this.displayDateFormat);
 
    this.ampmInTitle = this.getInitValue('ampmInTitle', props.ampmInTitle, this.ampmInTitle);
    this.useSeconds = this.getInitValue('useSeconds', props.useSeconds, this.useSeconds);
    this.locale = this.getInitValue('locale', props.locale, this.locale);
    this.activeTab = this.getInitValue('activeTab', props.activeTab, this.activeTab);
    this.timePickerFormat = this.getInitValue('timePickerFormat', props.timePickerFormat, this.timePickerFormat);
    this.maxTime = this.getInitValue('maxTime', props.maxTime, this.maxTime);
    this.minTime = this.getInitValue('minTime', props.minTime, this.minTime);
 
    this.dateValue = this.getInitValue('dateValue', props.dateValue, this.dateValue);
    this.timeValue = this.getInitValue('timeValue', props.timeValue, this.timeValue);
    this.firstDayOfWeek = this.getInitValue('firstDayOfWeek', props.firstDayOfWeek, this.firstDayOfWeek);
    this.showWeek = this.getInitValue('showWeek', props.showWeek, this.showWeek);
    this.rules.push(this.dateValidation);
    this.showDateTimePicker = this.getInitValue('showDateTimePicker', props.showDateTimePicker, this.showDateTimePicker);
 
    this.displayFormat = this.getInitialDisplayFormat();
    this.inputFormat = this.getInitialInputFormat();
    this.dateTimeFormat = this.getInitialDateTimeFormat();
    this.mask = this.getInitValue('mask', props.mask, undefined);
 
    this.createAccessors();
    this.initialMask = this.getInitialMask();
    this.isSimpleDisplay = this.isSimpleFormat(this.displayFormat);
  }
 
  protected maskFormat(format: string) {
    return format.replace(/[A-Za-z]/gi, '#');
  }
 
  get isoValue() {
    return this.formatISODateValue(this.value);
  }
 
  set isoValue(newValue: string) {
    const lastValue = this.value;
    this.dateError = false;
    this.value = this.parseISODateValue(newValue);
    if (lastValue !== this.value) this.change(this.value);
  }
 
  /**
 * Checks if a date format is simple.
 * Simple date formats are the ones that consists only of 'DD', '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 = ['DD', 'MM', 'YYYY', ' ', 'HH', 'mm', 'ss'];
 
    // 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 formatISODateValue(value: string): string {
    if (value && this.isValidDate(value, this.dateTimeFormat)) {
      return dayjs(value, this.dateTimeFormat).format(this.isoFormat);
    }
    return '';
  }
 
  public parseISODateValue(value: string): any {
    if (value && this.isValidDate(value, this.isoFormat)) {
      return dayjs(value, this.isoFormat).format(this.dateTimeFormat);
    }
    return null;
  }
 
  public formatter(value: string): string { return this.formatterFn(value, this); }
 
  public parser(value: string): any { return this.parserFn(value, this); }
 
  public click(event?: Event, element?: any) {
    const clickEvent = event || new MouseEvent('click');
    super.click(clickEvent, element);
    if (!event?.defaultPrevented) {
      this.activeTab = `calendarTab-${this.name}`;
      this.showDateTimePicker = !this.showDateTimePicker;
      if (this.isValidDate(this.value, this.dateTimeFormat)) {
        this.dateValue = dayjs(this.value, this.dateTimeFormat).format(this.dateFormat);
        this.timeValue = dayjs(this.value, this.dateTimeFormat).format(this.timeFormat);
      }
    }
  }
 
  private getInitialMask() {
    if (isUndefined(this.mask)) {
      this.mask = this.inputFormat && this.maskFormat(this.inputFormat);
    }
 
    return this.mask;
  }
 
  private getInitialInputFormat() {
    if (isUndefined(this.dateInputFormat) || isUndefined(this.timeInputFormat)) {
      return undefined;
    }
    return `${this.dateInputFormat} ${this.timeInputFormat}`;
  }
 
  private getInitialDateTimeFormat() {
    return `${this.dateFormat} ${this.timeFormat}`;
  }
 
  private getInitialDisplayFormat() {
    return `${this.displayDateFormat} ${this.displayTimeFormat}`;
  }
 
  public blur(event: Event, element: any) {
    this.removeDateMask();
    this.setDateValue(this.formatter(this.value));
    super.blur(event, element);
    this.showDateTimePicker = true;
  }
 
  public focus(event: Event, element: any) {
    this.addDateMask();
    super.focus(event, element);
  }
 
  public change(event?: Event, element?: any): void {
    super.change(event, element);
    if (this.value === null) {
      this.dateValue = null;
      this.timeValue = null;
    }
  }
 
  /**
* Add date mask
*/
  protected addDateMask() {
    if (isUndefined(this.initialMask) || !this.value) return;
 
    this.mask = this.initialMask;
    this.internalDisplayValue = dayjs(this.value, this.dateTimeFormat).format(this.inputFormat || this.displayFormat);
  }
 
  /**
* Removes the component mask if value is valid
*/
  protected removeDateMask() {
    if (
      isUndefined(this.initialMask) || !this.value || this.dateError
      || !this.isValidDate(this.value, this.dateTimeFormat)
    ) {
      return;
    }
 
    this.mask = '';
  }
 
  /**
* 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 | undefined {
    if (isUndefined(this.initialMask)) {
      return this.maskFormat(this.displayFormat);
    }
 
    return this.mask;
  }
 
  public setDateValue(displayValue: string) {
    const lastValue = this.displayValue;
    if (this.isValidDate(displayValue, this.displayFormat)) {
      this.internalDisplayValue = displayValue;
      this.internalValue = this.parser(displayValue);
      this.dateError = 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.dateError = !!displayValue;
    }
    this.value = this.internalValue; // forces value accessor to be called if necessary
  }
 
  get displayValue() {
    return this.internalDisplayValue;
  }
 
  set displayValue(newValue: string) {
    this.dateError = false;
    this.internalDisplayValue = newValue;
    this.internalValue = this.parser(newValue);
    this.value = this.internalValue; // forces value accessor to be called if necessary
  }
 
  public dateValidation(): boolean | string {
    return !this.dateError || I18n.translate('VALIDATION_INVALID_DATE');
  }
 
  public isValidDate(value: string, format: string, strict: boolean = true): boolean {
    return dayjs(value, format, strict).isValid();
  }
 
  /**
* Triggered when date is clicked.
* @param event
* @param element
*/
  public selectDate(date: string, event?: Event, element?: any) {
    if (this.events.onSelectDate && typeof this.events.onSelectDate === 'function') {
      this.events.onSelectDate({
        date, event, element, component: this,
      });
    }
  }
}
 
FormatterParserProvider.registerFormatter('ZdDateTime', (value: string, {
  dateTimeFormat = Config.dateTimeFormat,
  displayFormat = Config.displayDateTimeFormat,
  inputFormat = Config.dateInputFormat,
  mask = '',
  initialMask,
  isSimpleDisplay = false,
}: any = {}) => {
  if (!value) {
    return '';
  }
 
  const isDateValid = dayjs(value, dateTimeFormat, true).isValid();
 
  if (!isDateValid) {
    return value;
  }
 
  if (mask && initialMask) {
    if (inputFormat) {
      return dayjs(value, dateTimeFormat).format(inputFormat);
    }
 
    let valueToUnmask = value;
    if (isSimpleDisplay) {
      valueToUnmask = dayjs(value, dateTimeFormat).format(displayFormat);
    }
 
    const unmasked = Mask.getValueWithoutMask(valueToUnmask);
    const masked = Mask.getValueWithMask(unmasked, mask);
    return masked;
  }
 
  return dayjs(value, dateTimeFormat).format(displayFormat);
});
 
FormatterParserProvider.registerParser('ZdDateTime', (value: string, {
  dateTimeFormat = Config.dateTimeFormat,
  displayFormat = Config.displayDateTimeFormat,
  inputFormat = Config.dateInputFormat,
  mask = '',
  initialMask,
}: any = {}) => {
  if (!value) {
    return null;
  }
  if (dayjs(value, displayFormat, true).isValid()) {
    return dayjs(value, displayFormat).format(dateTimeFormat);
  }
  if (mask && Mask.checkMask(value, mask)) {
    if (inputFormat) {
      if (dayjs(value, inputFormat, true).isValid()) {
        return dayjs(value, inputFormat).format(dateTimeFormat);
      }
 
      return value;
    }
 
    const unmasked = Mask.getValueWithoutMask(value);
    let masked;
    if (!initialMask) {
      const displayFmtMask = displayFormat.replace(/[A-Za-z]/gi, '#');
 
      masked = Mask.getValueWithMask(unmasked, displayFmtMask);
 
      if (dayjs(masked, displayFormat, true).format(displayFormat) === masked) {
        return dayjs(masked, displayFormat).format(dateTimeFormat);
      }
    }
 
    const dateFmtMask = dateTimeFormat.replace(/[A-Za-z]/gi, '#');
 
    masked = Mask.getValueWithMask(unmasked, dateFmtMask);
    if (dayjs(masked, dateTimeFormat, true).format(dateTimeFormat) === masked) {
      return masked;
    }
  }
  return value;
});