All files / datepicker si-date-range.component.ts

98.09% Statements 103/105
91.89% Branches 34/37
93.75% Functions 30/32
98% Lines 98/100

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                                                                                                                                                                                    1x     1x 21x 21x 21x 21x             21x     21x                       21x                 21x 21x                   21x 21x                   21x 21x                   21x 21x                   21x 21x             21x   21x         21x               21x             21x           21x                       21x     21x 21x   21x 21x 21x 21x 21x 21x 21x                   25x 24x             24x       25x       19x 20x       19x 19x 9x 1x     8x 8x           24x 24x       38x       38x       19x       39x                 3x 3x 3x     3x 1x             10x   10x 10x       9x     9x                 9x 9x 2x 1x         5x 5x 5x 5x   5x     1x           10x         20x 20x   20x                   21x 20x 20x 20x   20x 8x     12x               40x 8x 8x 4x   8x 8x 8x 2x           8x 8x 2x                     39x 19x   20x        
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { A11yModule } from '@angular/cdk/a11y';
import {
  AfterViewInit,
  booleanAttribute,
  ChangeDetectorRef,
  Component,
  ComponentRef,
  computed,
  ElementRef,
  HostAttributeToken,
  HostListener,
  inject,
  input,
  model,
  OnChanges,
  output,
  signal,
  SimpleChanges,
  viewChild,
  viewChildren
} from '@angular/core';
import {
  AbstractControl,
  ControlValueAccessor,
  FormsModule,
  NG_VALIDATORS,
  NG_VALUE_ACCESSOR,
  NgModel,
  ValidationErrors,
  Validator,
  ValidatorFn,
  Validators
} from '@angular/forms';
import {
  positionBottomCenter,
  positionBottomEnd,
  positionBottomStart,
  positionTopCenter,
  positionTopEnd,
  positionTopStart
} from '@siemens/element-ng/common';
import { SI_FORM_ITEM_CONTROL, SiFormItemControl } from '@siemens/element-ng/form';
import { addIcons, elementCalendar, SiIconComponent } from '@siemens/element-ng/icon';
import { SiTranslatePipe, t, TranslatableString } from '@siemens/element-translate-ng/translate';
 
import { getMaxDate, getMinDate } from './date-time-helper';
import { SiDateInputDirective } from './si-date-input.directive';
import { SiDatepickerOverlayComponent } from './si-datepicker-overlay.component';
import { CloseCause, SiDatepickerOverlayDirective } from './si-datepicker-overlay.directive';
import { DatepickerInputConfig, DateRange } from './si-datepicker.model';
 
@Component({
  selector: 'si-date-range',
  imports: [FormsModule, SiDateInputDirective, SiIconComponent, SiTranslatePipe, A11yModule],
  templateUrl: './si-date-range.component.html',
  styleUrl: './si-date-range.component.scss',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: SiDateRangeComponent,
      multi: true
    },
    {
      provide: NG_VALIDATORS,
      useExisting: SiDateRangeComponent,
      multi: true
    },
    {
      provide: SI_FORM_ITEM_CONTROL,
      useExisting: SiDateRangeComponent
    }
  ],
  host: {
    class: 'form-control d-flex align-items-center pe-2',
    role: 'group',
    '[class.disabled]': 'disabled()',
    '[class.readonly]': 'readonly()',
    '[attr.aria-labelledby]': 'labelledby'
  },
  hostDirectives: [
    {
      directive: SiDatepickerOverlayDirective,
      outputs: ['siDatepickerClose']
    }
  ]
})
export class SiDateRangeComponent
  implements ControlValueAccessor, Validator, AfterViewInit, OnChanges, SiFormItemControl
{
  private static idCounter = 0;
  private readonly inputDirectives = viewChildren(SiDateInputDirective);
  private readonly startInput = viewChild.required<NgModel>('startInput');
  private readonly endInput = viewChild.required<NgModel>('endInput');
  private readonly button = viewChild.required<ElementRef>('button');
  /**
   * @defaultValue
   * ```
   * `__si-date-range-${SiDateRangeComponent.idCounter++}`
   * ```
   */
  readonly id = input(`__si-date-range-${SiDateRangeComponent.idCounter++}`);
 
  readonly labelledby =
    inject(new HostAttributeToken('aria-labelledby'), {
      optional: true
    }) ?? `${this.id()}-label`;
 
  /**
   * Date range component configuration.
   *
   * @defaultValue
   * ```
   * { enableDateRange: true }
   * ```
   */
  readonly siDatepickerConfig = model<DatepickerInputConfig>({ enableDateRange: true });
  /**
   * Placeholder of the start date input.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_DATEPICKER.START_DATE_PLACEHOLDER:Start date`)
   * ```
   */
  readonly startDatePlaceholder = input<TranslatableString>(
    t(() => $localize`:@@SI_DATEPICKER.START_DATE_PLACEHOLDER:Start date`)
  );
  /**
   * Placeholder of the end date input.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_DATEPICKER.END_DATE_PLACEHOLDER:End date`)
   * ```
   */
  readonly endDatePlaceholder = input<TranslatableString>(
    t(() => $localize`:@@SI_DATEPICKER.END_DATE_PLACEHOLDER:End date`)
  );
  /**
   * Aria label of the date-range calendar toggle button.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_DATEPICKER.CALENDAR_TOGGLE_BUTTON:Open calendar`)
   * ```
   */
  readonly ariaLabelCalendarButton = input<TranslatableString>(
    t(() => $localize`:@@SI_DATEPICKER.CALENDAR_TOGGLE_BUTTON:Open calendar`)
  );
  /**
   * Form label of the start timepicker.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_DATEPICKER.START_TIME_LABEL:from`)
   * ```
   */
  readonly startTimeLabel = input<TranslatableString>(
    t(() => $localize`:@@SI_DATEPICKER.START_TIME_LABEL:from`)
  );
  /**
   * Form label of the start timepicker.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_DATEPICKER.END_TIME_LABEL:to`)
   * ```
   */
  readonly endTimeLabel = input<TranslatableString>(
    t(() => $localize`:@@SI_DATEPICKER.END_TIME_LABEL:to`)
  );
  /**
   * Automatically close overlay on date selection.
   *
   * @defaultValue false
   */
  readonly autoClose = input(false, { transform: booleanAttribute });
  /** Emits on the date range value changes. */
  readonly siDatepickerRangeChange = output<DateRange | undefined>();
  /**
   * Emits an event to notify about disabling the time from the range picker.
   * When time is disable, we construct a pure date objects in UTC 00:00:00 time.
   */
  readonly disabledTimeChange = output<boolean>();
 
  /**
   * 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 });
 
  /**
   * Set the date-range object displayed in the control.
   * The input can be used if the control is used outside Angular forms.
   */
  readonly value = model<DateRange>();
 
  /**
   * This ID will be bound to the `aria-describedby` attribute of the date-range.
   * Use this to reference the element containing the error message(s) for the date-range.
   * It will be picked by the {@link SiFormItemComponent} if the date-range is used inside a form item.
   *
   * @defaultValue
   * ```
   * `${this.id()}-errormessage`
   * ```
   */
  readonly errormessageId = input(`${this.id()}-errormessage`);
 
  private validator!: ValidatorFn;
  private onChange = (val: any): void => {};
  private onTouch = (): void => {};
 
  protected readonly icons = addIcons({ elementCalendar });
  protected readonly disabled = computed(() => this.disabledInput() || this.disabledNgControl());
  private readonly disabledNgControl = signal(false);
  private readonly cdRef = inject(ChangeDetectorRef);
  private readonly overlayToggle = inject(SiDatepickerOverlayDirective);
  private readonly elementRef = inject(ElementRef);
  private readonly defaultPlacement = [
    positionBottomCenter,
    positionBottomStart,
    positionBottomEnd,
    positionTopCenter,
    positionTopStart,
    positionTopEnd
  ];
 
  ngOnChanges(changes: SimpleChanges): void {
    if (changes.siDatepickerConfig) {
      this.siDatepickerConfig.set({
        ...changes.siDatepickerConfig.currentValue,
        enableDateRange: true,
        startTimeLabel:
          changes.siDatepickerConfig.currentValue.startTimeLabel ?? this.startTimeLabel(),
        endTimeLabel: changes.siDatepickerConfig.currentValue.endTimeLabel ?? this.endTimeLabel()
      });
      Iif (changes.value) {
        this.updateValue(this.value());
      }
    }
    this.overlayToggle.setInputs({ config: this.siDatepickerConfig(), dateRange: this.value() });
  }
 
  ngAfterViewInit(): void {
    this.validator = Validators.compose([
      () => this.endAfterStartValidator(),
      this.childValidation
    ])!;
 
    this.overlayToggle.placement.set(this.defaultPlacement);
    this.overlayToggle.siDatepickerClose.subscribe(cause => {
      if ([CloseCause.Escape, CloseCause.Select].includes(cause)) {
        this.button().nativeElement.focus();
      } else {
        // Mark component as touch when the focus isn't recovered on input
        this.onTouch();
        this.cdRef.markForCheck();
      }
    });
  }
 
  writeValue(dateRange: DateRange): void {
    this.updateValue(dateRange);
    this.overlayToggle.setInputs({ dateRange });
  }
 
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }
 
  registerOnTouched(fn: () => void): void {
    this.onTouch = fn;
  }
 
  setDisabledState(isDisabled: boolean): void {
    this.disabledNgControl.set(isDisabled);
  }
 
  validate(c: AbstractControl): ValidationErrors | null {
    return this.validator ? this.validator(c) : null;
  }
 
  /**
   * Focus out shall close the datepicker except we are moving the focus to the datepicker or one of the input elements.
   * @param event - focus out event with the related target
   */
  @HostListener('focusout', ['$event'])
  protected onFocusOut(event: FocusEvent): void {
    const target = event.relatedTarget as HTMLInputElement;
    if (!this.overlayToggle.contains(target)) {
      this.overlayToggle.closeOverlay();
 
      // Only mark the component as touched when the focus is not moved to the datepicker or one of the input elements.
      if (!this.elementRef.nativeElement.contains(target)) {
        this.onTouch();
      }
    }
  }
 
  /** Forward date range input changes to datepicker overlay */
  protected onInputChanged(dateRange: DateRange): void {
    this.updateValue(dateRange);
 
    this.onChange(this.value());
    this.siDatepickerRangeChange.emit(this.value());
  }
 
  protected show(): void {
    Iif (this.readonly() || this.disabled()) {
      return;
    }
    this.subscribeRangeChanges(
      this.overlayToggle.showOverlay(true, {
        config: this.siDatepickerConfig(),
        dateRange: this.value()
      })
    );
  }
 
  private subscribeRangeChanges(overlay?: ComponentRef<SiDatepickerOverlayComponent>): void {
    overlay?.instance.dateRange.subscribe(d => this.onRangeChanged(d));
    overlay?.instance.disabledTimeChange.subscribe(disabledTime => {
      this.inputDirectives().forEach(inputDirective => inputDirective.onDisabledTime(disabledTime));
      this.disabledTimeChange.emit(disabledTime);
    });
  }
 
  private onRangeChanged(range?: DateRange): void {
    this.updateValue(range);
    this.onChange(range);
    this.siDatepickerRangeChange.emit(range);
    this.validateChildren();
 
    if (this.autoClose() && this.value()?.start && this.value()?.end) {
      // We have to queue the close in the another cycle since other output event
      // emitters like rangeTypeChange can complete before we destroy the overlay.
      setTimeout(() => this.overlayToggle.closeAfterSelection());
    }
  }
 
  /** Run validators on the start/end inputs. */
  private validateChildren(): void {
    this.inputDirectives().forEach(d => d.validatorOnChange());
  }
 
  /** The form control validator for the end date is greater equal start date. */
  private endAfterStartValidator(): ValidationErrors | null {
    const endDate = this.endInput().value;
    const startDate = this.startInput().value;
 
    return !endDate || !startDate || endDate >= startDate
      ? null
      : {
          endBeforeStart: {
            start: startDate,
            end: endDate
          }
        };
  }
 
  private readonly childValidation: ValidatorFn = () => {
    const errors: Record<string, any> = {};
    this.readErrorsFromInnerControl(this.startInput(), 'Start', errors);
    this.readErrorsFromInnerControl(this.endInput(), 'End', errors);
 
    if (Object.keys(errors).length) {
      return errors;
    }
 
    return null;
  };
 
  private readErrorsFromInnerControl(
    control: NgModel,
    type: 'Start' | 'End',
    errors: Record<string, any>
  ): void {
    if (control.invalid) {
      const formatError = control.getError('dateFormat');
      if (formatError) {
        errors[`invalid${type}DateFormat`] = formatError;
      }
      const minError = control.getError('minDate');
      const siDatepickerConfig = this.siDatepickerConfig();
      if (minError) {
        errors.rangeBeforeMinDate = {
          min: getMinDate(siDatepickerConfig.minDate),
          start: this.startInput().value,
          end: this.endInput().value
        };
      }
      const maxError = control.getError('maxDate');
      if (maxError) {
        errors.rangeAfterMaxDate = {
          max: getMaxDate(siDatepickerConfig.maxDate),
          start: this.startInput().value,
          end: this.endInput().value
        };
      }
    }
  }
 
  private updateValue(value?: DateRange): void {
    // this allows angular's built in required validator to work correctly
    if (!value?.start && !value?.end) {
      this.value.set(undefined);
    } else {
      this.value.set(value);
    }
  }
}