All files / datepicker si-timepicker.component.ts

89.27% Statements 208/233
78.44% Branches 91/116
97.36% Functions 37/38
88.83% Lines 199/224

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 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673                                                                                                                                                                            1x 1x   62x               62x     62x                 62x         62x       62x       62x       62x         62x               62x             62x             62x             62x 62x           62x       62x       62x       62x   62x       62x             62x     62x   62x   62x       62x         62x         62x     62x   62x 62x 62x   62x                       62x   62x 62x     62x 41x 41x   62x 57x   62x 62x 62x 87x                     87x 86x                   87x 20x                   87x 14x                     87x     62x             62x 123x 123x   276x 123x 123x           123x 60x 167x         123x   62x 62x                 62x               77x 53x 24x 19x           279x       38x       38x       36x             24x 24x   6x 6x     18x 6x   12x   18x                     62x 12x     18x 38x 18x 16x 16x         1x 1x               16x           16x                 89x 69x 69x 69x                       69x 1x           1x 1x   68x 68x       68x 68x   51x 51x 51x 51x 7x     68x                   166x 23x     143x 21x     122x 1x     121x       121x 20x   101x       94x 94x 94x 94x 94x   94x 33x     94x           94x 2x   92x         550x   550x 543x     550x 3x   547x       72x 72x   72x         72x 12x 12x 12x 12x 12x       72x 1x 1x 1x 1x 1x     72x 11x 61x 1x   60x       6x 6x 6x   2x 2x 2x 2x 2x   2x       2x 2x     2x 2x 2x     2x 2x 2x                         7x       7x       7x 7x 7x 7x   7x 3x     7x 2x     7x 2x   7x       7x             6x 6x     6x 20x 6x       6x 3x   3x         3x          
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { A11yModule, FocusOrigin } from '@angular/cdk/a11y';
import {
  FormatWidth,
  FormStyle,
  getLocaleDayPeriods,
  getLocaleTimeFormat,
  NgTemplateOutlet,
  TranslationWidth
} from '@angular/common';
import {
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  ElementRef,
  HostAttributeToken,
  inject,
  input,
  LOCALE_ID,
  output,
  signal,
  viewChildren
} from '@angular/core';
import { ControlValueAccessor, FormsModule, NG_VALUE_ACCESSOR } from '@angular/forms';
import { SI_FORM_ITEM_CONTROL, SiFormItemControl } from '@siemens/element-ng/form';
import { SiTranslatePipe, t, TranslatableString } from '@siemens/element-translate-ng/translate';
 
import { createDate } from './date-time-helper';
 
/**
 * @internal
 */
interface TimeComponents {
  hour?: string | number;
  minute?: string | number;
  seconds?: string | number;
  milliseconds?: string | number;
  isPM?: boolean;
}
 
interface Value {
  hours: string;
  minutes: string;
  seconds: string;
  milliseconds: string;
}
 
interface Config {
  ariaLabel: TranslatableString;
  label: TranslatableString;
  maxLength: number;
  max: number;
  name: keyof Value;
  pattern: string;
  placeholder: string;
  separator?: string;
}
 
@Component({
  selector: 'si-timepicker',
  imports: [NgTemplateOutlet, FormsModule, SiTranslatePipe, A11yModule],
  templateUrl: './si-timepicker.component.html',
  styleUrl: './si-timepicker.component.scss',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: SiTimepickerComponent,
      multi: true
    },
    {
      provide: SI_FORM_ITEM_CONTROL,
      useExisting: SiTimepickerComponent
    }
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    role: 'group',
    class: 'form-custom-control',
    '[class.readonly]': 'readonly()',
    '[attr.aria-labelledby]': 'labelledby'
  }
})
export class SiTimepickerComponent implements ControlValueAccessor, SiFormItemControl {
  private static idCounter = 0;
  /** @internal */
  readonly forceInvalid = signal(false);
 
  /**
   * @defaultValue
   * ```
   * `__si-timepicker-${SiTimepickerComponent.idCounter++}`
   * ```
   */
  readonly id = input(`__si-timepicker-${SiTimepickerComponent.idCounter++}`);
 
  readonly labelledby =
    inject(new HostAttributeToken('aria-labelledby'), {
      optional: true
    }) ?? `${this.id()}-label`;
  /**
   * All input fields will be disabled if set to true.
   *
   * @defaultValue false
   */
  // eslint-disable-next-line @angular-eslint/no-input-rename
  readonly disabledInput = input(false, { alias: 'disabled' });
 
  /**
   * @defaultValue 'hh'
   */
  readonly hoursLabel = input<TranslatableString>('hh');
  /**
   * @defaultValue 'mm'
   */
  readonly minutesLabel = input<TranslatableString>('mm');
  /**
   * @defaultValue 'ss'
   */
  readonly secondsLabel = input<TranslatableString>('ss');
  /**
   * @defaultValue 'ms'
   */
  readonly millisecondsLabel = input<TranslatableString>('ms');
  /**
   * Hide the labels of the input fields.
   * @defaultValue false
   */
  readonly hideLabels = input(false, { transform: booleanAttribute });
 
  /**
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_DATEPICKER.HOURS:Hours`)
   * ```
   */
  readonly hoursAriaLabel = input(t(() => $localize`:@@SI_DATEPICKER.HOURS:Hours`));
  /**
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_DATEPICKER.MINUTES:Minutes`)
   * ```
   */
  readonly minutesAriaLabel = input(t(() => $localize`:@@SI_DATEPICKER.MINUTES:Minutes`));
  /**
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_DATEPICKER.SECONDS:Seconds`)
   * ```
   */
  readonly secondsAriaLabel = input(t(() => $localize`:@@SI_DATEPICKER.SECONDS:Seconds`));
  /**
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_DATEPICKER.MILLISECONDS:Milliseconds`)
   * ```
   */
  readonly millisecondsAriaLabel = input(
    t(() => $localize`:@@SI_DATEPICKER.MILLISECONDS:Milliseconds`)
  );
 
  /**
   * @defaultValue 'hh'
   */
  readonly hoursPlaceholder = input('hh');
  /**
   * @defaultValue 'mm'
   */
  readonly minutesPlaceholder = input('mm');
  /**
   * @defaultValue 'ss'
   */
  readonly secondsPlaceholder = input('ss');
  /**
   * @defaultValue 'ms'
   */
  readonly millisecondsPlaceholder = input('ms');
 
  readonly meridians = input<string[]>();
  /**
   * @defaultValue 'am/pm'
   */
  readonly meridiansLabel = input<TranslatableString>('am/pm');
  /**
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_DATEPICKER.PERIOD:Period`)
   * ```
   */
  readonly meridiansAriaLabel = input(t(() => $localize`:@@SI_DATEPICKER.PERIOD:Period`));
 
  /** @defaultValue true */
  readonly showMinutes = input(true, { transform: booleanAttribute });
  /** @defaultValue false */
  readonly showSeconds = input(false, { transform: booleanAttribute });
  /** @defaultValue false */
  readonly showMilliseconds = input(false, { transform: booleanAttribute });
  /**
   * Show time in 12-hour period including the select to toggle between AM/PM.
   */
  readonly showMeridian = input<boolean | undefined>();
 
  /**
   * A minimum time limit. The date part of the date object will be ignored.
   */
  readonly min = input<Date>();
 
  /**
   * A maximum time limit. The date part of the date object will be ignored.
   */
  readonly max = input<Date>();
 
  /** @defaultValue false */
  readonly readonly = input(false, { transform: booleanAttribute });
 
  readonly isValid = output<boolean>();
  readonly meridianChange = output<string>();
  readonly inputCompleted = output<void>();
 
  private readonly inputParts = viewChildren<ElementRef<HTMLElement>>('inputPart');
 
  /**
   * This ID will be bound to the `aria-describedby` attribute of the timepicker.
   * Use this to reference the element containing the error message(s) for the timepicker.
   * It will be picked by the {@link SiFormItemComponent} if the timepicker is used inside a form item.
   *
   * @defaultValue
   * ```
   * `${this.id()}-errormessage`
   * ```
   */
  readonly errormessageId = input(`${this.id()}-errormessage`);
 
  private onChange: (val: any) => void = () => {};
  private onTouched: () => void = () => {};
 
  // The following are the time values for the ui.
  protected readonly periods = computed(() => {
    const meridians = this.meridians();
    return meridians?.length ? meridians : this.periodDefaults;
  });
  protected readonly use12HourClock = computed(
    () => this.showMeridian() ?? getLocaleTimeFormat(this.locale, FormatWidth.Full).includes('a')
  );
  protected readonly disabled = computed(() => this.disabledInput() || this.disabledNgControl());
  protected readonly meridian = signal<'' | 'am' | 'pm'>('');
  protected readonly units = computed<Config[]>(() => {
    const config: Config[] = [
      {
        ariaLabel: this.hoursAriaLabel(),
        label: this.hoursLabel(),
        max: this.isPM() ? 12 : 24,
        maxLength: 2,
        name: 'hours',
        pattern: '2[0-4]|[01]?[0-9]',
        placeholder: this.hoursPlaceholder()
      }
    ];
    if (this.showMinutes()) {
      config.push({
        ariaLabel: this.minutesAriaLabel(),
        label: this.minutesLabel(),
        max: 60,
        maxLength: 2,
        name: 'minutes',
        pattern: '[0-5]?[0-9]',
        placeholder: this.minutesPlaceholder()
      });
    }
    if (this.showSeconds()) {
      config.push({
        ariaLabel: this.secondsAriaLabel(),
        label: this.secondsLabel(),
        max: 60,
        maxLength: 2,
        name: 'seconds',
        pattern: '[0-5]?[0-9]',
        placeholder: this.secondsPlaceholder()
      });
    }
    if (this.showMilliseconds()) {
      config.push({
        ariaLabel: this.millisecondsAriaLabel(),
        label: this.millisecondsLabel(),
        max: 1000,
        maxLength: 3,
        name: 'milliseconds',
        pattern: '[0-9]{1,3}',
        placeholder: this.millisecondsPlaceholder(),
        separator: '.'
      });
    }
    return config;
  });
  /* Input fields state */
  protected readonly unitValues = signal({
    hours: '',
    minutes: '',
    seconds: '',
    milliseconds: ''
  });
  /** Validation state of the input fields */
  protected readonly unitValidation = computed(() => {
    const units = this.units();
    const values = this.unitValues();
    // Only validate if the input fields contain a value.
    const empty = Object.values(values).every(v => v.length === 0);
    const valid = empty || this.isValidLimit(this.max(), this.min());
    const validation = {
      hours: valid,
      minutes: valid,
      seconds: valid,
      milliseconds: valid
    };
    if (!empty && valid) {
      for (const config of units) {
        validation[config.name] =
          values[config.name].length > 0 && !isNaN(this.toNumber(values[config.name], config.max));
      }
    }
 
    return validation;
  });
  private readonly disabledNgControl = signal(false);
  private readonly locale = inject(LOCALE_ID).toString();
 
  /**
   * Holds the time as date object that is presented by this control.
   */
  private time?: Date;
  private periodDefaults: string[];
 
  constructor() {
    this.periodDefaults = getLocaleDayPeriods(
      this.locale,
      FormStyle.Format,
      TranslationWidth.Short
    ).slice();
  }
 
  writeValue(obj?: Date | string): void {
    if (this.isValidDate(obj)) {
      this.setTime(this.parseTime(obj));
    } else if (obj == null) {
      this.setTime();
    }
  }
 
  /** @internal */
  isPM(): boolean {
    return this.use12HourClock() && this.meridian() === 'pm';
  }
 
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }
 
  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }
 
  setDisabledState(isDisabled: boolean): void {
    this.disabledNgControl.set(isDisabled);
  }
 
  /**
   * Handle Enter, Arrow up/down and Space key press events.
   */
  protected handleKeyPressEvent(event: KeyboardEvent): void {
    const target = event.target as HTMLInputElement;
    switch (event.key) {
      case 'Enter':
        this.focusNext(event);
        break;
      case 'ArrowUp':
      case 'ArrowDown':
        if (!this.readonly()) {
          this.changeTimeComponent(target.name, event.key === 'ArrowUp');
        } else {
          event.preventDefault();
        }
        break;
      case ' ':
        Iif (this.readonly()) {
          event.preventDefault();
        }
        break;
      default:
        break;
    }
  }
 
  protected toHtmlInputElement = (target?: EventTarget | null): HTMLInputElement =>
    target as HTMLInputElement;
 
  protected updateField(name: keyof Value, value: string): void {
    const prev = this.unitValues()[name];
    const config = this.units().find(u => u.name === name)!;
    if (prev !== value) {
      this.unitValues.update(v => ({ ...v, [name]: value.padStart(config.maxLength, '0') }));
      this.updateTime();
    }
  }
 
  protected toggleMeridian(): void {
    const time = this.changeTime(this.time, { hour: 12 });
    this.setTime(time);
  }
 
  /**
   * Takes the current UI values and updates the time object value
   * accordingly, if they UI input values are valid.
   */
  private updateTime(): void {
    Iif (!this.unitValidation()) {
      this.isValid.emit(false);
      this.onChange(null);
      return;
    }
 
    this.setTime(this.createDateUpdate(this.time));
  }
 
  /**
   * Sets a new time object as model value, updates the user interface
   * and invokes onChange to let timepicker clients know about the update.
   * @param time - The new time to be set.
   */
  private setTime(time?: Date | undefined): void {
    if (this.time !== time) {
      this.time = time;
      this.updateUI(this.time);
      this.onChange(this.time);
    }
  }
 
  /**
   * Updates the user interface by filling the time components
   * into the time input fields. Sets empty values if the date
   * is undefined or invalid.
   *
   * @param value - The date object or string from with the time components are taken.
   */
  private updateUI(value?: string | Date): void {
    if (!value || !this.isValidDate(value)) {
      this.unitValues.set({
        hours: '',
        minutes: '',
        seconds: '',
        milliseconds: ''
      });
      this.meridian.set('am');
      this.meridianChange.emit(this.meridian());
    } else {
      const time = this.parseTime(value);
      Iif (!time) {
        return;
      }
 
      let hours = time.getHours();
      if (this.use12HourClock()) {
        // 12:00 am is midnight while 12:00 pm is noon when users enter a value greater than 12 we can assume it's pm
        this.meridian.set(hours > 12 ? 'pm' : 'am');
        this.meridianChange.emit(this.meridian());
        hours = hours % 12;
        if (hours === 0) {
          hours = 12;
        }
      }
      this.unitValues.set({
        hours: hours.toString().padStart(2, '0'),
        minutes: time.getMinutes().toString().padStart(2, '0'),
        seconds: time.getUTCSeconds().toString().padStart(2, '0'),
        milliseconds: time.getUTCMilliseconds().toString().padStart(3, '0')
      });
    }
  }
 
  private isValidDate(value?: string | Date): boolean {
    if (!value) {
      return false;
    }
 
    if (typeof value === 'string') {
      return this.isValidDate(new Date(value));
    }
 
    if (value instanceof Date && isNaN(value.getHours())) {
      return false;
    }
 
    return true;
  }
 
  private parseTime(value?: string | Date): Date | undefined {
    if (typeof value === 'string') {
      return new Date(value);
    }
    return value;
  }
 
  private createDateUpdate(date: Date | undefined): Date | undefined {
    const value = this.unitValues();
    let hour = this.toNumber(value.hours, this.isPM() ? 12 : 24);
    const minute = this.toNumber(value.minutes, 60);
    const seconds = this.toNumber(value.seconds, 60) || 0;
    const milliseconds = this.toNumber(value.milliseconds, 1000) || 0;
 
    if (this.isPM() && hour !== 12) {
      hour += 12;
    }
 
    Iif (!date) {
      if (!isNaN(hour) && !isNaN(minute)) {
        return createDate(new Date(), hour, minute, seconds, milliseconds);
      } else {
        return date;
      }
    } else if (isNaN(hour) || isNaN(minute)) {
      return date;
    } else {
      return createDate(date, hour, minute, seconds, milliseconds);
    }
  }
 
  private toNumber(value?: string | number, limit?: number): number {
    Iif (typeof value === 'undefined') {
      return NaN;
    } else if (typeof value === 'string') {
      value = parseInt(value, 10);
    }
 
    if (limit !== undefined && (isNaN(value) || value < 0 || value > limit)) {
      return NaN;
    }
    return value;
  }
 
  private isValidLimit(max?: Date, min?: Date): boolean {
    const refDate = new Date();
    const newDate = this.createDateUpdate(refDate);
 
    Iif (!newDate) {
      return false;
    }
 
    let refMax: Date | undefined;
    if (max) {
      refMax = new Date(refDate);
      refMax.setHours(max.getHours());
      refMax.setMinutes(max.getMinutes());
      refMax.setSeconds(max.getSeconds());
      refMax.setMilliseconds(max.getMilliseconds());
    }
 
    let refMin: Date | undefined;
    if (min) {
      refMin = new Date(refDate);
      refMin.setHours(min.getHours());
      refMin.setMinutes(min.getMinutes());
      refMin.setSeconds(min.getSeconds());
      refMin.setMilliseconds(min.getMilliseconds());
    }
 
    if (refMax && newDate > refMax) {
      return false;
    } else if (refMin && newDate < refMin) {
      return false;
    }
    return true;
  }
 
  private changeTimeComponent(key: string, up: boolean): void {
    const change = up ? 1 : -1;
    const date = this.createDateUpdate(new Date());
    switch (key) {
      case 'hours': {
        const newTime = this.changeTime(date, { hour: change });
        let hour = newTime!.getHours();
        if (this.use12HourClock()) {
          hour = hour % 12;
          Iif (hour === 0 && !this.isPM()) {
            hour = 12;
          } else Iif (hour === 0 && this.isPM()) {
            this.toggleMeridian();
          }
        }
        this.updateField('hours', hour.toString());
        break;
      }
      case 'minutes': {
        const newTime = this.changeTime(date, { minute: change });
        this.updateField('minutes', newTime.getMinutes().toString());
        break;
      }
      case 'seconds': {
        const newTime = this.changeTime(date, { seconds: change });
        this.updateField('seconds', newTime.getSeconds().toString());
        break;
      }
      case 'milliseconds': {
        const newTime = this.changeTime(date, { milliseconds: change });
        this.updateField('milliseconds', newTime.getMilliseconds().toString());
        break;
      }
      default:
        break;
    }
  }
 
  private changeTime(value?: Date, diff?: TimeComponents): Date {
    Iif (!value) {
      return this.changeTime(createDate(new Date(), 0, 0, 0, 0), diff);
    }
 
    Iif (!diff) {
      return value;
    }
 
    let hour = value.getHours();
    let minutes = value.getMinutes();
    let seconds = value.getSeconds();
    let milliseconds = value.getMilliseconds();
 
    if (diff.hour) {
      hour = hour + this.toNumber(diff.hour);
    }
 
    if (diff.minute) {
      minutes = minutes + this.toNumber(diff.minute);
    }
 
    if (diff.seconds) {
      seconds = seconds + this.toNumber(diff.seconds);
    }
    Iif (diff.milliseconds) {
      milliseconds = milliseconds + this.toNumber(diff.milliseconds);
    }
 
    return createDate(value, hour, minutes, seconds, milliseconds);
  }
 
  /**
   * Focuses the next available input/select field or emit inputCompleted event.
   */
  protected focusNext(event: Event): void {
    const target = event.target as HTMLElement;
    Iif (!target) {
      return;
    }
    const targets = this.inputParts();
    const position = targets?.findIndex(ref => ref.nativeElement === target);
    Iif (position === undefined || position === -1) {
      return;
    }
 
    if (position < targets!.length - 1) {
      targets![position + 1].nativeElement.focus();
    } else {
      this.inputCompleted.emit();
    }
  }
 
  protected focusChange(event: FocusOrigin): void {
    Iif (event === null) {
      this.onTouched();
    }
  }
}