All files / packages/sds-components/src/sds/inputDate inputDate.js

79.52% Statements 101/127
69.23% Branches 36/52
67.5% Functions 27/40
80.15% Lines 101/126

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              16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x                 16x 16x                 22x                         22x                     27x                       50x                         24x     1x                 32x     1x 1x                       1x 1x               1x     1x 1x                 23x                                                             2x                     25x     7x                                     1x                   3x                         14x 14x                   3x 3x                 6x     5x                 6x   6x 1x 1x   5x 5x   6x             16x 16x 16x 16x 16x                                                           19x 19x                                                 5x               6x   6x 5x 5x   5x     5x               5x       5x 5x         5x             1x                                     1x     1x 1x   1x 1x                   4x     4x 4x 4x 4x                         3x 2x     3x   3x 3x         3x   3x 3x     3x       3x                                                     1x     1x   1x 1x 1x                     4x       1x                                            
import { LightningElement, api } from 'lwc';
import { reflectAttribute, normalizeBoolean, DateFormatter, dateRegexIso, hasSlotText } from 'sds/utils';
import 'sds/privateThemeProvider';
 
export default class InputDate extends LightningElement {
  static shadowSupportMode = 'native';
 
  _value = '';
  _name = 'input-date';
  _isoDate = '';
  _locale = 'en-US';
  _day = '';
  _month = '';
  _year = '';
  _dayformat = 'numeric';
  _monthformat = 'short';
  _yearformat = 'numeric';
  _invalid = false;
  _validityMessage;
  _validDate = true;
  _dateObject = {};
  _disabled = false;
  _readonly = false;
  _required = false;
  _helptext;
  _inputElement;
  _helpTextElement;
 
  connectedCallback() {
    this._value = this._todaysDate();
    this._isoDate = this._formatIsoDate(this._day, this._month, this._year);
  }
 
  /**
   * Sets the value of the input
   * @param {string} value
   */
  @api id = 'input-date';
 
  /**
   * Sets the month format of the input
   * @param {enum} monthformat
   * @values short, long, numeric, 2-digit
   * @default numeric
   */
  @api
  get monthformat() {
    return this._monthformat;
  }
  set monthformat(value) {
    this._monthformat = value;
  }
 
  /**
   * Sets the day format of the input
   * @param {enum} dayformat
   * @values numeric, 2-digit
   * @default numeric
   */
  @api
  get dayformat() {
    return this._dayformat;
  }
  set dayformat(value) {
    this._dayformat = value;
  }
 
  /**
   * The current values of the input
   * @param {string} value
   */
  @api
  get value() {
    return this._value;
  }
  set value(value) {
    this._value = value;
  }
 
  /**
   * Sets the locale of the input
   * @param {string} locale
   * @default en-US
   */
  @api
  get locale() {
    return this._locale;
  }
  set locale(value) {
    this._locale = value;
  }
 
  /**
   * Sets the name of the input
   * @param {string} name
   * @default input-date
   * @required
   */
  @api
  get name() {
    return this._name;
  }
  set name(value) {
    this._name = value;
  }
 
  /**
   * Determines if the input is disabled
   * @param {boolean} disabled
   * @default false
   */
  @api
  get disabled() {
    return this._disabled;
  }
  set disabled(value) {
    this._disabled = normalizeBoolean(value);
    reflectAttribute(this, 'disabled', this._disabled);
  }
 
  /**
   * Determines if the input is readonly
   * @param {boolean} readonly
   * @default false
   */
  @api
  get readOnly() {
    return this._readonly;
  }
  set readOnly(value) {
    this._readonly = normalizeBoolean(value);
    reflectAttribute(this, 'readonly', this._readonly);
  }
 
  /**
   * Visually hides the label.
   * @type {boolean}
   */
  @api
  get labelHidden() {
    return this._labelHidden;
  }
  set labelHidden(value) {
    this._labelHidden = normalizeBoolean(value);
    reflectAttribute(this, 'label-hidden', this._labelHidden);
  }
 
  /**
   * Determines if the input is required
   * @param {boolean} required
   * @default false
   */
  @api
  get required() {
    return this._required;
  }
  set required(value) {
    this._required = normalizeBoolean(value);
    reflectAttribute(this, 'required', this._required);
  }
 
  /**
   * Returns the day value of the input
   * @returns {string} day
   * @readonly
   */
  @api
  get day() {
    return this._day;
  }
 
  /**
   * Returns the month value of the input
   * @returns {string} month
   * @readonly
   */
  @api
  get month() {
    return this._month;
  }
 
  /**
   * Returns the year value of the input
   * @returns {string} year
   * @readonly
   */
  @api
  get year() {
    return this._year;
  }
 
  /**
   * Allows customer to set invalid state on input
   * An example would be if the input is required and the value is empty on form submit,
   * since we are not using native form validation, we need to offer the ability set the invalid state on the input
   * @param {boolean} invalid
   * @default false
   */
  @api
  get invalid() {
    return this._invalid;
  }
  set invalid(value) {
    this._invalid = normalizeBoolean(value);
    reflectAttribute(this, 'invalid', this._invalid);
  }
 
  /**
   * Returns the validity object of the input
   * @returns {string} validity message
   * @readonly
   */
  @api
  get validity() {
    return Promise.resolve().then(() => this.input.validity);
  }
 
  /**
   * Returns the validity message of the input
   * @returns {string} validity message
   * @readonly
   */
  @api
  get validityMessage() {
    return this._validityMessage;
  }
 
  /**
   * Gets or sets the ISO date of the input.
   *
   * @return {string} The ISO date.
   * @param {string} value - The new ISO date.
   */
  @api
  get isoDate() {
    return this._isoDate;
  }
 
  set isoDate(value) {
    this._isoDate = value;
  }
 
  /**
   * Returns the date object of the input
   * @returns {object} date object
   * @readonly
   * @private
   */
  get input() {
    this._inputElement = this._inputElement || this.template.querySelector('input');
 
    return this._inputElement;
  }
 
  /**
   * Returns the help text element, if it exists
   * Used to dynamically add/remove the associated ID to the input element if help text is present
   * @returns {object} help text element
   * @private
   */
  get helpText() {
    this._helpTextElement = this._helpTextElement || this.template.querySelector('[part="help-text"]');
 
    return this._helpTextElement;
  }
 
  /**
   * If invalid, sets the aria-invalid attribute on the input element
   * and sets invalid attribute on custom element
   * @private
   */
  isInvalid() {
    if (!this.input.validity.valid) {
      this.invalid = true;
    } else {
      this.invalid = false;
    }
  }
 
  /**
   * Handles validity of the input, returns validity message if invalid
   * @param {string} value - an ISO date string
   */
  _handleValidity(value) {
    this._validateDate(value);
    // _validDate gets set in _validateDate, if not valid set validity object to fail with custom message
    if (!this._validDate) {
      this.input.setCustomValidity('Date is not valid');
      this._validityMessage = 'Date is not valid. Please enter a valid date. Format: YYYY-MM-DD';
    } else {
      this.input.setCustomValidity('');
      this._validityMessage = null;
    }
    this.isInvalid();
  }
 
  /**
   * Creates a date object for todays date
   */
  _todaysDate() {
    const today = new Date();
    this._day = String(today.getDate()).padStart(2, '0');
    this._month = String(today.getMonth() + 1).padStart(2, '0');
    this._year = today.getFullYear();
    return new DateFormatter(this.locale, this._day, this._month, this._year, {
      day: this.dayformat,
      month: this.monthformat,
      year: this._yearformat,
    }).format();
  }
 
  /**
   * Formats the date based on the locale
   * @param {string} day
   * @param {string} month
   * @param {string} year
   * @returns {string} formatted date
   */
  @api
  _formatDate(day, month, year) {
    return new DateFormatter(this.locale, day, month, year, {
      day: this.dayformat,
      month: this.monthformat,
      year: this._yearformat,
    }).format();
  }
 
  /**
   * Formats the date to ISO format
   * @param {string} day
   * @param {string} month
   * @param {string} year
   * @returns {string} ISO date
   */
  _formatIsoDate(day, month, year) {
    const date = new Date(Date.UTC(year, month - 1, day, 0, 0, 0));
    return date.toISOString().split('T')[0];
  }
 
  /**
   * Returns the numeric month value
   * @param {string} month
   * @returns {number} numeric month
   */
  _getNumericMonth(month) {
    const date = new Date(`${month} 1, 2000`);
    if (date.toString() !== 'Invalid Date') {
      return date.getMonth() + 1;
    } else {
      // return -1 if invalid month to prevent error in DateFormatter
      return -1;
    }
  }
 
  /**
   * Returns the number of days in a month
   * @param {string} month
   * @Iparam {string} year
   * @returns {number} number of days in month
   */
  _getDaysInMonth(month, year) {
    return new Date(year, month, 0).getDate();
  }
 
  /**
   * IValidates the date, ensure the ISO format is YYYY-MM-DD
   * @param {string} date
   */
  _validateDate(date) {
    Elet dateRegex = dateRegexIso;
    // check if valid date, e.g. 2020/01/01
    if (dateRegex.test(date)) {
      this._validDate = true;
      this._year = Number(dateRegex.exec(date)[1]);
      this._month = Number(dateRegex.exec(date)[2]);
      this._day = Number(dateRegex.exec(date)[3]);
 
      // check if valid month
      if (this._month < 1 || this._month > 12) {
        this._validDate = false;
      }
      // check if valid day
      if (this._day < 1 || this._day > this._getDaysInMonth(this._month, this._year)) {
        this._validDate = false;
      }
      // check if valid year
      if (this._year < 1900 || this._year > 2100) {
        this._validDate = false;
      }
      // If valid, store the date object
      if (this._validDate) {
        this._dateObject.numeric = new DateFormatter(this.locale, this._day, this._month, this._year, {
          day: 'numeric',
          month: 'numeric',
          year: 'numeric',
        }).format();
        this._dateObject.date = new DateFormatter(this.locale, this._day, this._month, this._year, {
          day: this.dayformat,
          month: this.monthformat,
          year: this._yearformat,
        }).format();
    I  }
    } else {
      this._validDate = false;
    }
  }
 
  /*E*
   * Validates the date and updates the dateObject with the given date.
   *
   * @param {string} date - The date to validate and update the dateObject with.
   * @return {void}
   */
  @api
  validateAndSetDate(date) {
    this._handleValidity(date); // Validate the date and update the dateObject
  }
 
  /*I*
   * On click handler for the input
   * Restores ISO date value when focused
   */
  handleClick() {
    if (this.disabled || this.readonly) {
      return;
    }
    this.input.focus();
    this.setAttribute('focus', '');
    // if valid date, restore ISO date when interacting with input
    if (this._isoDate && !this._invalid) {
      this._value = this._isoDate;
    }
  }
 
  /**
   * On input handler for the input
   * Handles validity and stores the value. Sets active attribute to host element when typing.
   * @param {Event} e
   */
  handleInput(e) {
    if (this.disabled || this.readonly) {
    E  return;
    }
    this._handleValidity(e.target.value);
    this._value = e.target.value;
    this.EsetAttribute('active', '');
    this.dispatchEvent(new CustomEvent('change'));
  }
 
  /**
   * On blur handler for the input
   * Handles validity and stores the value as the formatted date. Removes active attribute from host element when blurring.
   * @param {Event} e
   */
  handleBlur(e) {
    if (this.disabled || this.readonly) {
      return;
    }
    // make sure we don't fire off validity check if we are not checking against a valid iso date
    if (e.target.value === this._isoDate) {
      this._handleValidity(this._isoDate);
    }
    // If not invalid, restore formatted date on blur and store new iso date
    if (!this._invalid) {
      // Check if _dateObject.date is defined before assigning it to _value
      if (this._dateObject && this._dateObject.date) {
        this._value = this._dateObject.date;
      } else {
        this._value = e.target.value; // (Prevents "undefined" bug on blur with tab)
      }
      // Store the ISO date in the YYYY-MM-DD format
      this._isoDate = this._formatIsoDate(this._day, this._month, this._year);
    }
    this.removeAttribute('active');
    this.removeAttribute('focus');
 
    // Dispatch an event with both the formatted date and ISO date
    const eventDetail = {
      value: this._value,
      isoDate: this._isoDate,
    };
 
    this.dispatchEvent(
      new CustomEvent('blur', {
        detail: eventDetail,
        bubbles: true,
        composed: true,
      }),
    );
  E}
 
  /**
   * On keydown handler for the input
   * Prevents user from inputting anything other than numbers and hyphens
   * @param {Event} e
   */
  handleKeyPress(e) {
    const keyCode = e.keyCode || e.which;
    const keyValue = String.fromCharCode(keyCode);
    if (!/^[0-9\-]$/.test(keyValue)) {
      e.preventDefault();
    }
  }
 
  /**
   * Slot change event on help text slot
   * Used to dynamically add/remove the associated ID to the input element if help text is present
   * Used to dynamically add "visible" part to the help text element if help text is found in the slot
   * @param {*} e - slot change event
   */
  handleHelpTextSlotChange(e) {
    let childElements = e.target.assignedElements({ flatten: true });
    if (childElements.length > 0) {
      if (this.helpText) {
        this.helpText.id = 'id-help-text';
        this.input.setAttribute('aria-describedby', 'id-help-text');
        this.helpText.setAttribute('part', 'help-text visible');
      }
    }
  }
 
  /**
   * Slot change event on the label slot
   * Used to check if the label has a slotted value, if not, we throw an error that one must be included
   * @param {*} e - slot change event
   */
  handleLabelSlotChange(e) {
    !hasSlotText(e) && console.error('A label value must be included for all form elements.');
  }
}