All files / datepicker si-date-input.directive.ts

100% Statements 86/86
97.36% Branches 37/38
91.3% Functions 21/23
100% Lines 85/85

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                                                                                                                                1x     1x               116x                   116x           116x       116x           116x           116x                       116x     116x       116x 242x 242x 242x           116x   116x 116x 116x 116x 116x 116x 116x     144x 1x   144x 81x   144x   138x 138x 138x 138x 138x 12x           242x       105x       105x       105x       113x 113x         231x   231x 231x 9x 9x 9x       231x 188x 188x         188x 188x           200x 200x 107x   200x               37x 37x     37x 37x 20x 20x 20x         2x       298x 148x   298x                 11x   11x                 4x   4x 4x 4x   4x 4x         242x 242x         242x 242x 242x 242x   242x                 242x 242x 242x 242x   242x              
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { formatDate } from '@angular/common';
import {
  booleanAttribute,
  computed,
  Directive,
  HostListener,
  inject,
  input,
  LOCALE_ID,
  model,
  OnChanges,
  output,
  signal,
  SimpleChanges
} from '@angular/core';
import {
  AbstractControl,
  ControlValueAccessor,
  NG_VALIDATORS,
  NG_VALUE_ACCESSOR,
  ValidationErrors,
  Validator,
  Validators
} from '@angular/forms';
import { SI_FORM_ITEM_CONTROL, SiFormItemControl } from '@siemens/element-ng/form';
 
import { compareDate, getMaxDate, getMinDate, isValid, parseDate } from './date-time-helper';
import { DatepickerInputConfig, getDatepickerFormat } from './si-datepicker.model';
 
/**
 * Base directive for date input fields.
 */
@Directive({
  selector: 'input[siDateInput]',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: SiDateInputDirective,
      multi: true
    },
    {
      provide: NG_VALIDATORS,
      useExisting: SiDateInputDirective,
      multi: true
    },
    {
      provide: SI_FORM_ITEM_CONTROL,
      useExisting: SiDateInputDirective
    }
  ],
  host: {
    '[attr.id]': 'id()',
    '[attr.disabled]': 'disabled() || null',
    '[attr.readonly]': 'readonly() || null',
    '[class.readonly]': 'readonly()',
    '[attr.aria-describedby]': 'errormessageId()',
    '[value]': 'dateString()'
  },
  exportAs: 'siDateInput'
})
export class SiDateInputDirective
  implements ControlValueAccessor, OnChanges, Validator, SiFormItemControl
{
  private static idCounter = 0;
 
  /**
   * @defaultValue
   * ```
   * `si-date-input-${SiDateInputDirective.idCounter++}`
   * ```
   */
  readonly id = input(`si-date-input-${SiDateInputDirective.idCounter++}`);
 
  /**
   * Configuration object for the datepicker.
   *
   * @defaultValue
   * ```
   * {}
   * ```
   */
  readonly siDatepickerConfig = model<DatepickerInputConfig | undefined>({});
 
  /**
   * Emits an event to notify about disabling the time from the datepicker.
   * When time is disable, we construct a pure date object in UTC 00:00:00 time.
   */
  readonly siDatepickerDisabledTime = output<boolean>();
  /**
   * Emits an event on state changes e.g. readonly, disable, ... .
   */
  readonly stateChange = output<void>();
  /**
   * Whether the date range input is disabled.
   * @defaultValue false
   */
  // eslint-disable-next-line @angular-eslint/no-input-rename
  readonly disabledInput = input(false, { alias: 'disabled' });
 
  /**
   * Whether the date range input is readonly.
   * @defaultValue false
   */
  readonly readonly = input(false, { transform: booleanAttribute });
 
  /**
   * This ID will be bound to the `aria-describedby` attribute of the date-input.
   * Use this to reference the element containing the error message(s) for the date-input.
   * It will be picked by the {@link SiFormItemComponent} if the date-input is used inside a form item.
   *
   * @defaultValue
   * ```
   * `${this.id()}-errormessage`
   * ```
   */
  readonly errormessageId = input(`${this.id()}-errormessage`);
 
  /** @internal */
  validatorOnChange = (): void => {};
  /**
   * Date form input validator function, validating text format, min and max value.
   */
  protected validator = Validators.compose([
    () => this.formatValidator(),
    () => this.minValidator(),
    () => this.maxValidator()
  ])!;
  protected date?: Date;
  /**
   * Emits a new `date` value on input field value changes.
   */
  protected readonly dateChange = output<Date | undefined>();
  /** @internal */
  public readonly disabled = computed(() => this.disabledInput() || this.disabledNgControl());
  protected onTouched: () => void = () => {};
  protected onModelChange: (value: any) => void = () => {};
  protected readonly dateString = signal('');
  private readonly disabledNgControl = signal(false);
  protected readonly locale = inject(LOCALE_ID).toString();
  private format = '';
 
  ngOnChanges(changes: SimpleChanges): void {
    if (changes.siDatepickerConfig && !changes.siDatepickerConfig.currentValue) {
      this.siDatepickerConfig.set({});
    }
    if (changes.readonly || changes.disabledInput) {
      this.stateChange.emit();
    }
    if (changes.siDatepickerConfig) {
      // reflect possible change is date/time format
      const format = this.format;
      this.format = '';
      this.getFormat();
      const formatChanged = format !== this.format;
      if (this.date && formatChanged) {
        this.updateNativeValue();
      }
    }
  }
 
  validate(c: AbstractControl): ValidationErrors | null {
    return this.validator(c);
  }
 
  registerOnChange(fn: any): void {
    this.onModelChange = fn;
  }
 
  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }
 
  registerOnValidatorChange(fn: () => void): void {
    this.validatorOnChange = fn;
  }
 
  setDisabledState(isDisabled: boolean): void {
    this.disabledNgControl.set(isDisabled);
    this.stateChange.emit();
  }
 
  writeValue(value?: Date | string): void {
    // remove date when user input is empty
    let emptyString = false;
    // Flag to define invalid string
    let invalidDate = false;
    if (typeof value === 'string') {
      emptyString = value.trim().length === 0;
      value = parseDate(value, this.getFormat(), this.locale);
      invalidDate = !value;
    }
 
    // Only emit changes to prevent that a destroyed output emit a value
    if (this.date !== value) {
      this.date = value;
      this.dateChange.emit(this.date);
 
      // We should not change the content of the input field when the user typed
      // a wrong input. Otherwise the typed content changes and the user cannot
      // correct the content.
      if (!invalidDate || emptyString) {
        this.updateNativeValue();
      }
    }
  }
 
  private updateNativeValue(): void {
    let dtStr = '';
    if (isValid(this.date)) {
      dtStr = formatDate(this.date, this.getFormat(), this.locale);
    }
    this.dateString.set(dtStr);
  }
 
  /**
   * Handles `input` events on the input element.
   */
  @HostListener('input', ['$event'])
  protected onInput(event: Event): void {
    const value = (event.target as HTMLInputElement).value;
    const parsedDate = parseDate(value, this.getFormat(), this.locale);
 
    // Is same date
    const hasChanged = !(parsedDate === this.date);
    if (hasChanged) {
      this.date = parsedDate;
      this.onModelChange(this.date);
      this.dateChange.emit(this.date);
    }
  }
 
  @HostListener('blur', ['$event']) protected onBlur(event: FocusEvent): void {
    this.onTouched();
  }
 
  private getFormat(): string {
    if (!this.format) {
      this.format = getDatepickerFormat(this.locale, this.siDatepickerConfig());
    }
    return this.format;
  }
 
  /**
   * Callback when the datepicker changes his value.
   * @param date - updated date
   */
  protected onDateChanged(date?: Date): void {
    // update input element
    this.writeValue(date);
    // update the Forms ngModel
    this.onModelChange(this.date);
  }
 
  /**
   * Datepicker consider time / ignore time changed.
   * @param disabledTime - disable time
   * @internal
   */
  onDisabledTime(disabledTime: boolean): void {
    this.format = '';
    // Temporary reset internal date to force an update with the new date format
    const currentDate = this.date;
    this.date = undefined;
    this.siDatepickerConfig()!.disabledTime = disabledTime;
    // Ensure the time format will be removed
    this.onDateChanged(currentDate);
    this.siDatepickerDisabledTime.emit(disabledTime);
  }
 
  /** The form control validator for date format */
  private formatValidator(): ValidationErrors | null {
    const invalidFormat = this.date && isNaN(this.date.getTime());
    return invalidFormat ? { dateFormat: { format: this.getFormat() } } : null;
  }
 
  /** The form control validator for the min date. */
  private minValidator(): ValidationErrors | null {
    const controlValue = this.date;
    const siDatepickerConfig = this.siDatepickerConfig();
    const min = getMinDate(siDatepickerConfig?.minDate);
    const withTime = siDatepickerConfig?.showTime;
 
    return !min ||
      !isValid(controlValue) ||
      (withTime ? controlValue >= min : compareDate(controlValue, min) >= 0)
      ? null
      : { minDate: { min, actual: controlValue } };
  }
 
  /** The form control validator for the min date. */
  private maxValidator(): ValidationErrors | null {
    const controlValue = this.date;
    const siDatepickerConfig = this.siDatepickerConfig();
    const max = getMaxDate(siDatepickerConfig?.maxDate);
    const withTime = siDatepickerConfig?.showTime;
 
    return !max ||
      !isValid(controlValue) ||
      (withTime ? controlValue <= max : compareDate(controlValue, max) <= 0)
      ? null
      : { maxDate: { max, actual: controlValue } };
  }
}