All files / datepicker/components si-day-selection.component.ts

98.76% Statements 80/81
80.64% Branches 25/31
100% Functions 16/16
98.71% Lines 77/78

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                                                                                                        1x           115x           115x         115x   115x   115x   115x   115x   117x   115x 1242x           115x 209x 209x 209x         209x 209x 209x 209x 209x 209x 209x       8778x 1045x     8778x 8778x 8778x   8778x                     209x     115x   115x 198x           115x 200x 200x 200x           115x 205x 205x 205x     115x     13x 13x   2x 2x   2x 2x   2x 2x   1x 1x   1x 1x   1x 1x   3x 3x   1x 1x                 13x       7x           4x           13x 13x 13x 13x 7x   13x                   6x           6x 6x         4x 4x       34x 34x         13x       10x      
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { DatePipe } from '@angular/common';
import {
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
  input,
  LOCALE_ID,
  model,
  output
} from '@angular/core';
import { isRTL } from '@siemens/element-ng/common';
import { SiTranslatePipe, TranslatableString } from '@siemens/element-translate-ng/translate';
 
import {
  addDaysInRange,
  addMonthsInRange,
  createDate,
  getDayStrings,
  getFirstDateInMonth,
  getLastDateInMonth,
  getWeekEndDate,
  getWeekOfYear,
  getWeekStartDate,
  isAfterMonth,
  isAnotherMonthOrYear,
  isSameDate,
  isSameMonth,
  isSameOrBetween,
  today
} from '../date-time-helper';
import { WeekStart } from '../si-datepicker.model';
import { Cell, SiCalendarBodyComponent } from './si-calendar-body.component';
import { SiCalendarDirectionButtonComponent } from './si-calendar-direction-button.component';
import { DayCompareAdapter } from './si-compare-adapter';
import { SiInitialFocusComponent } from './si-initial-focus.component';
 
/**
 * Show dates of a single month as table and handles the keyboard interactions.
 * The focusedDate is handled according the keyboard interactions.
 */
@Component({
  selector: 'si-day-selection',
  imports: [DatePipe, SiCalendarBodyComponent, SiCalendarDirectionButtonComponent, SiTranslatePipe],
  templateUrl: './si-day-selection.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class SiDaySelectionComponent extends SiInitialFocusComponent {
  /**
   * Indicate whether the week numbers shall be hidden.
   *
   * @defaultValue false
   */
  readonly hideWeekNumbers = input(false, { transform: booleanAttribute });
  /**
   * Defines the starting day of the week. Default is `monday`.
   *
   * @defaultValue 'monday'
   */
  readonly weekStartDay = input<WeekStart>('monday');
  /**
   * The active date, the cell which will receive the focus.
   * @defaultValue calendarUtils.today()
   */
  readonly focusedDate = model.required<Date>();
  /** Today button text */
  readonly todayLabel = input<TranslatableString>();
  /** Aria label for calendar week column */
  readonly calendarWeekLabel = input<TranslatableString>();
  /** Emits when the active focused date changed to another month / year, typically during keyboard navigation */
  readonly activeMonthChange = output<Date>();
  /** Emits when the user requests a different to show a different view */
  readonly viewChange = output<'year' | 'month'>();
  /** The translated list of week days. */
  protected readonly days = computed(() => getDayStrings(this.locale, this.weekStartDay()));
  /** The week numbers which are shown as row label */
  protected readonly weekNumbers = computed(() =>
    this.weeks().map(w => getWeekOfYear(w[0].valueRaw, this.weekStartDay()).toString())
  );
  /**
   * The current visible list of calendar days.
   * Every time the focusedDate changes to either another month or year the list will be rebuild.
   */
  protected readonly weeks = computed(() => {
    const focusedDate = this.focusedDate();
    const monthStart = getFirstDateInMonth(focusedDate);
    const monthEnd = getLastDateInMonth(focusedDate);
    /**
     * We start the month with the first day in the week which has the effect that dates are
     * visible which aren't in the active month.
     */
    const startDate = getWeekStartDate(monthStart, this.weekStartDay());
    const minDate = this.minDate();
    const maxDate = this.maxDate();
    const weeks: Cell[][] = [[], [], [], [], [], []];
    let weekIndex = 0;
    for (
      let i = 0, date = new Date(startDate);
      weeks[weeks.length - 1].length < 7;
      i++, date.setDate(date.getDate() + 1)
    ) {
      if (i > 0 && i % 7 === 0) {
        weekIndex++;
      }
 
      const activeMonth = isSameOrBetween(date, monthStart, monthEnd);
      const isToday = isSameDate(date, today());
      const outOfRange = !isSameOrBetween(date, minDate, maxDate);
 
      weeks.at(weekIndex)?.push({
        value: date.getDate(),
        disabled: outOfRange,
        ariaLabel: date.toDateString(),
        displayValue: date.getDate().toString(),
        isPreview: !activeMonth,
        isToday,
        valueRaw: createDate(date),
        cssClasses: ['day', activeMonth ? 'si-h4' : 'si-body-lg']
      });
    }
    return weeks;
  });
  /** Compare date based on the current view */
  protected compareAdapter = new DayCompareAdapter();
  /** Disable today button if it is the same month */
  protected readonly isTodayButtonDisabled = computed(() =>
    isSameMonth(today(), this.focusedDate())
  );
  /**
   * Indicate the previous button shall be disabled.
   * This happens when the focusedDate is equal or before the minDate.
   */
  protected readonly isPreviousButtonDisabled = computed(() => {
    const minDate = this.minDate();
    const focusedDate = this.focusedDate();
    return minDate && (isSameMonth(focusedDate, minDate) || isAfterMonth(minDate, focusedDate));
  });
  /**
   * Indicate the next button shall be disabled.
   * This happens when the focusedDate is equal or after the maxDate.
   */
  protected readonly isNextButtonDisabled = computed(() => {
    const maxDate = this.maxDate();
    const focusedDate = this.focusedDate();
    return maxDate && (isSameMonth(focusedDate, maxDate) || isAfterMonth(focusedDate, maxDate));
  });
 
  private readonly locale = inject(LOCALE_ID).toString();
 
  protected calendarBodyKeyDown(event: KeyboardEvent): void {
    const isRtl = isRTL();
    switch (event.key) {
      case 'ArrowLeft':
        this.updateFocusedDateByDay(isRtl ? 1 : -1);
        break;
      case 'ArrowRight':
        this.updateFocusedDateByDay(isRtl ? -1 : 1);
        break;
      case 'ArrowUp':
        this.updateFocusedDateByDay(-7);
        break;
      case 'ArrowDown':
        this.updateFocusedDateByDay(7);
        break;
      case 'Home':
        this.updateFocusedDate(getWeekStartDate(this.focusedDate(), this.weekStartDay()));
        break;
      case 'End':
        this.updateFocusedDate(getWeekEndDate(this.focusedDate(), this.weekStartDay()));
        break;
      case 'PageDown':
        this.updateFocusedDateByMonth(1);
        break;
      case 'PageUp':
        this.updateFocusedDateByMonth(-1);
        break;
      case 'Enter':
      case 'Space':
      default:
        // Don't prevent default or focus active cell on keys that we don't explicitly handle.
        return;
    }
 
    // Prevent unexpected default actions such as form submission.
    event.preventDefault();
  }
 
  protected updateFocusedDateByDay(offset: number): void {
    this.updateFocusedDate(
      addDaysInRange(this.focusedDate(), offset, this.minDate(), this.maxDate())
    );
  }
 
  protected updateFocusedDateByMonth(offset: number): void {
    this.updateFocusedDate(
      addMonthsInRange(this.focusedDate(), offset, this.minDate(), this.maxDate())
    );
  }
 
  protected updateFocusedDate(newDate: Date): void {
    const prevDate = this.focusedDate();
    if (!isSameDate(prevDate, newDate)) {
      this.focusedDate.set(newDate);
      if (isAnotherMonthOrYear(newDate, prevDate)) {
        this.activeMonthChange.emit(newDate);
      }
      this.focusActiveCell();
    }
  }
 
  /**
   * Update month of focusedDate.
   * @param offset -1 or -1.
   */
  protected setMonthOffset(offset: number): void {
    // Only update emit focusedDate since the focus shall stay on the button.
    const actualMonth = addMonthsInRange(
      this.focusedDate(),
      offset,
      this.minDate(),
      this.maxDate()
    );
    this.focusedDate.set(actualMonth);
    this.activeMonthChange.emit(actualMonth);
  }
 
  /** Change the focusedDate to today */
  protected goToToday(): void {
    this.focusedDate.set(today());
    this.focusActiveCell();
  }
 
  protected emitSelectedValue(selected: Date): void {
    if (selected !== this.startDate() || selected !== this.endDate()) {
      this.selectedValueChange.emit(selected);
    }
  }
 
  protected emitActiveDate(active: Date): void {
    this.focusedDate.set(active);
  }
 
  protected emitViewChange(view: 'year' | 'month'): void {
    this.viewChange.emit(view);
  }
}