All files / lib/date-input date-input.component.ts

98.63% Statements 289/293
98.14% Branches 53/54
100% Functions 22/22
98.63% Lines 289/293

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 2941x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 1x 1x 1x 1x 3x 1x 1x 1x 1x 3x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 88x 88x 88x 158x 158x 339x 339x 339x 337x 257x 117x 117x 117x 117x 140x 140x 339x 339x 339x 158x 158x 158x 158x 158x 158x 2918x 2918x 158x 158x 158x 213x 213x 158x 158x 158x 158x 158x 158x 158x 158x 158x 1x 1x 1x 1x 1x 88x 88x 87x 87x 35x 35x 35x 87x 87x 87x 87x 87x 87x 87x 87x 46x 46x 46x 41x 41x 41x 41x 41x 87x 87x 87x 87x 88x 1x 1x 1x 1805x 1805x 1x 1x 1x 3610x 3610x 1x 1x 1x 1805x 1805x 1x 1x 1x 994x         994x 994x 272x 722x 722x 994x 994x 1x 1x 1x 1x 1x 87x 87x 87x 20x 67x 87x 1x 1x 1x 1x 1x 87x 87x 87x 87x 1x 1x 1x 1x 1x 190x 190x 47x 190x 190x 190x 1x 1x 1x 1x 1x 123x 123x 123x 123x 123x 123x 123x 123x 123x 123x 1x  
/*******************************************************************************
 * Copyright bei
 * Entwicklungs- und Pflegeverbund für das gemeinsame Fachverfahren gefa
 *
 *******************************************************************************/
import { Component, ElementRef, Input, ViewChild } from '@angular/core';
import { DateTime } from 'luxon';
 
import { computeErrorTextPrefix } from '../utils/internal-utils';
import {
  InvalidControlValue,
  Nullable,
  WidgetKeySet,
} from '../utils/util.types';
import { createWidgetKeySet, isInvalidControlValue } from '../utils/utilities';
 
import { BaseDateTimeComponent } from '../time-input/base-date-time.component';
 
interface DateFormula {
  getDate: (text: string) => DateTime;
  match: RegExp;
}
 
const ERROR_TEXT_INVALID_FORMAT = 'Falsches Eingabeformat';
const ERROR_TEXT_NONEXISTENT_DATE = 'Datum existiert nicht';
const DATE_FORMAT = 'dd.MM.yyyy';
 
const SUPPORTED_FORMATS = [
  {
    format: 'dd.MM.yyyy',
    regex: /^\d{2}\.\d{2}\.\d{4}$/,
  },
  {
    format: 'ddMM',
    regex: /^\d{4}$/,
  },
  {
    format: 'ddMMyyyy',
    regex: /^\d{8}$/,
  },
  {
    format: 'd.M.',
    regex: /^\d\.\d\.$/,
  },
  {
    format: 'd.MM.',
    regex: /^\d\.\d{2}\.$/,
  },
  {
    format: 'dd.M.',
    regex: /^\d{2}\.\d\.$/,
  },
  {
    format: 'dd.MM.',
    regex: /^\d{2}\.\d{2}\.$/,
  },
  {
    format: 'd.M.yyyy',
    regex: /^\d\.\d\.\d{4}$/,
  },
  {
    format: 'dd.M.yyyy',
    regex: /^\d{2}\.\d\.\d{4}$/,
  },
  {
    format: 'd.MM.yyyy',
    regex: /^\d\.\d{2}\.\d{4}$/,
  },
  {
    format: 'yyyy-MM-dd',
    regex: /^\d{4}-\d{2}-\d{2}$/,
  },
];
 
const SUPPORTED_FORMULAS: DateFormula[] = [
  {
    getDate: (text: string) =>
      DateTime.now().plus({ days: Number(text.slice(0, text.length - 1)) }),
    match: /^(\d+)([tT])$/,
  },
  {
    getDate: (text: string) =>
      DateTime.now().plus({ weeks: Number(text.slice(0, text.length - 1)) }),
    match: /^(\d+)([wW])$/,
  },
  {
    getDate: (text: string) =>
      DateTime.now().plus({ months: Number(text.slice(0, text.length - 1)) }),
    match: /^(\d+)([mM])$/,
  },
  {
    getDate: (text: string) =>
      DateTime.now().plus({ years: Number(text.slice(0, text.length - 1)) }),
    match: /^(\d+)([jJ])$/,
  },
  {
    getDate: () => DateTime.now(),
    match: /^h$/,
  },
  {
    getDate: () => DateTime.now().minus({ days: 1 }),
    match: /^g$/,
  },
  {
    getDate: () => DateTime.now().plus({ days: 1 }),
    match: /^m$/,
  },
];
 
/**
 * A Date input component that allows the user to type in or select a date from the calendar.
 */
@Component({
  selector: 'gc-date-input',
  templateUrl: './date-input.component.html',
  styleUrls: [
    '../base-range-input-field/base-slot-mode.css',
    './date-input.component.css',
  ],
})
export class DateInputComponent extends BaseDateTimeComponent {
  // maximum input length - equals the length of a fully formatted (local) date
  public static readonly _INPUT_MAX_LENGTH = 10;
 
  /**
   * Overrides the default text which is shown when the control is readonly and empty.
   */
  @Input()
  public readonlyEmptyValue = '';
 
  /** @ignore */
  @Input()
  public _sizeHelperValue = '';
 
  /** @ignore */
  @ViewChild('input')
  protected _inputElement!: ElementRef<HTMLInputElement>;
 
  /**
   * Current value of the date input, in ISO 8601 format.
   */
  @Input()
  public override get value(): Nullable<string | InvalidControlValue> {
    return super.value;
  }
 
  public override set value(value: Nullable<string | InvalidControlValue>) {
    super.value = value;
    if (isInvalidControlValue(value)) {
      this.text = value.rawValue;
      this.internalErrorMessage = this.generateErrorMsg(value.rawValue);
    } else if (value !== null) {
      const d = DateTime.fromISO(value);
      this.text = d.toFormat(DATE_FORMAT);
      this.internalErrorMessage = '';
    } else {
      this.text = '';
      this.internalErrorMessage = '';
    }
    this.onInputChange.emit(this.text);
  }
 
  /**
   * @ignore
   * Helper to access static property in an Angular binding.
   */
  public get maxLength() {
    return DateInputComponent._INPUT_MAX_LENGTH;
  }
 
  /** @ignore */
  protected get inputElement(): ElementRef<HTMLInputElement> {
    return this._inputElement;
  }
 
  /** @ignore */
  protected readonly _widgetKeys: WidgetKeySet = createWidgetKeySet('gc-date');
 
  /**
   * displayed on readonly when readonlyEmptyValue is empty
   * @ignore
   */
  protected readonly READONLY_DEFAULT_EMPTY_VALUE = '\u2013';
 
  /**
   * @ignore
   */
  protected updateValue(text: string): void {
    if (text === '') {
      this.value = null;
    } else {
      const computedDateFromText = this.computeTextToDate(text);
 
      const date =
        computedDateFromText ?? DateTime.fromFormat(text, DATE_FORMAT);
      const dateISO = date.toISODate();
      // check whether the date will be represented in expanded ISO format,
      // years which require more than 4 digits would require an additional prefix ('+/-')
      // with an exchangeable interpretation (e.g. Luxon library simply adds the prefix and continues counting)
      // -> as we don't need to support such distant dates large values which would
      // require special handling/interpretation are considered invalid
      // see ISO 8601:2004, 3.5
      const dateISOExpanded = date.year > 9999 || date.year < 0;
 
      if (date.isValid && !dateISOExpanded) {
        this.value = dateISO;
      } else {
        this.value = {
          kind: 'InvalidControlInput',
          rawValue: text,
          errorMessage: this.generateErrorMsg(text),
        };
        // error message updated automatically in 'value' setter
      }
    }
  }
 
  /** @ignore */
  protected getLabelId(): string {
    return this._widgetKeys.labelKey;
  }
 
  /** @ignore */
  protected getInputId(): string {
    return this._widgetKeys.widgetKey;
  }
 
  /** @ignore */
  protected computeAriaDescribedBy(): string | null {
    return this._infoMessageId ?? null;
  }
 
  /** @ignore */
  protected sizeHelperText(): string {
    if (this.readonly && this.text.length === 0) {
      if (this.readonlyEmptyValue === '') {
        return this.READONLY_DEFAULT_EMPTY_VALUE;
      } else {
        return this.readonlyEmptyValue;
      }
    } else if (this._sizeHelperValue) {
      return this._sizeHelperValue;
    } else {
      return this.text;
    }
  }
 
  /**
   * @ignore
   */
  private computeTextToDate(text: string): DateTime | undefined {
    const foundFormula = this.findFormula(text);
 
    return foundFormula
      ? foundFormula.getDate(text)
      : this.computeDateFromTextFormat(text);
  }
 
  /**
   * @ignore
   */
  private findFormula(text: string): DateFormula | undefined {
    return SUPPORTED_FORMULAS.find(
      i => i.match.exec(text.toLowerCase())?.input,
    );
  }
 
  /**
   * @ignore
   */
  private computeDateFromTextFormat(text: string): DateTime | undefined {
    const foundFormat = SUPPORTED_FORMATS.find(
      i => i.regex.exec(text)?.input,
    )?.format;
 
    return foundFormat ? DateTime.fromFormat(text, foundFormat) : undefined;
  }
 
  /**
   * @ignore
   */
  private generateErrorMsg(inputValue: string): string {
    const errorPrefix = computeErrorTextPrefix(
      this.label,
      this._slotElementMode,
      'Datum',
    );
    const errorMessage = this.computeDateFromTextFormat(inputValue)
      ? ERROR_TEXT_NONEXISTENT_DATE
      : ERROR_TEXT_INVALID_FORMAT;
    return errorPrefix + errorMessage;
  }
}