All files / lib/calendar/calendar-content-days calendar-content-days.component.ts

35.08% Statements 387/1103
100% Branches 0/0
0% Functions 0/48
35.08% Lines 387/1103

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 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 11041x 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 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 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 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     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 1x 1x 1x 1x 1x 1x  
import {
  AfterViewInit,
  Component,
  ElementRef,
  EventEmitter,
  HostBinding,
  Input,
  NgZone,
  OnChanges,
  OnDestroy,
  OnInit,
  Output,
  QueryList,
  SimpleChanges,
  ViewChild,
  ViewChildren,
  inject,
} from '@angular/core';
import { DateTimeFormatOptions } from 'luxon';
 
import { findScrollContainers } from '../../utils/internal-utils';
import { HasSublabel, Item, WidgetKeySet } from '../../utils/util.types';
import { createWidgetKeySet } from '../../utils/utilities';
 
import { DayOfWeek } from '../calendar-appointment/calendar-appointment.component';
import {
  LaneLayout,
  LaneLayoutEntry,
  computeLaneLayout,
} from './layout-algorithm';
 
const DATE_PARSING_ERROR_MESSAGE =
  'Passed date does not exist or could not be parsed: ';
 
export interface DayConfig {
  date: string;
  hasWorkingHours: boolean;
}
 
interface TimeRange {
  start: string;
  end: string;
}
 
export interface Appointment extends Item, Partial<HasSublabel> {
  date: string;
  time: TimeRange;
  isAllDay?: boolean;
}
 
export interface CalendarCell {
  day: DayConfig;
  hour: number;
  slot: 'first' | 'second';
}
 
export interface CalendarAppointmentAction {
  appointment: Appointment;
  event: 'open-details';
}
 
type AppointmentInternal = Appointment & {
  id: string;
};
 
interface CalendarDayLayout {
  date: string;
  laneLayout: LaneLayout<LaneLayoutEntry<AppointmentInternal>>;
}
 
interface FormattedDayDate {
  date: string;
  weekday: string;
  month: string;
  dayOfWeekAbbreviation: DayOfWeek;
}
 
export interface CellOpenEvent {
  date: string;
  time: TimeRange;
}
 
@Component({
  selector: 'gc-calendar-content-days',
  templateUrl: './calendar-content-days.component.html',
  styleUrls: ['./calendar-content-days.component.css'],
})
export class CalendarContentDaysComponent
  implements OnInit, OnChanges, AfterViewInit, OnDestroy
{
  /**
   * Renders each item as a calendar day.
   */
  @Input({ required: true })
  public dayConfigs: readonly DayConfig[] = [];
 
  /**
   * Date string of today.
   */
  @Input({ required: true })
  public today = '';
 
  /**
   * Working hours for all calendar days.
   */
  @Input()
  public workingHours: TimeRange = { start: '08:00', end: '18:00' };
 
  /** Appointments to be rendered in the calendar content. */
  @Input()
  public appointments: readonly Appointment[] = [];
 
  /**
   * Fires upon focusing of a calendar cell.
   */
  @Output()
  public readonly onFocusChange: EventEmitter<CalendarCell> =
    new EventEmitter<CalendarCell>();
 
  /**
   * Fires upon executing the 'open' gesture.
   */
  @Output()
  public readonly onCellOpen: EventEmitter<CellOpenEvent> =
    new EventEmitter<CellOpenEvent>();
 
  /**
   * Fires upon executing appointment actions.
   */
  @Output()
  public readonly onAppointmentAction: EventEmitter<CalendarAppointmentAction> =
    new EventEmitter<CalendarAppointmentAction>();
 
  /** @ignore */
  @HostBinding('style.--gc-column-number')
  protected columnNumber = 1;
 
  /** @ignore */
  @HostBinding('style.--gc-wrapper-height.px')
  protected height?: number;
 
  /** @ignore */
  @ViewChildren('cell ')
  private cells?: QueryList<ElementRef<HTMLElement>>;
 
  /** @ignore */
  @ViewChildren('dayCell')
  private dayCellEl?: QueryList<ElementRef<HTMLElement>>;
 
  /** @ignore */
  @ViewChild('wrapper')
  private wrapperEl!: ElementRef<HTMLElement>;
 
  /** @ignore */
  protected hasHorizontalScroll = false;
 
  /** @ignore */
  protected calendarItems: CalendarDayLayout[] = [];
 
  /** @ignore */
  protected hours = [
    '00:00',
    '01:00',
    '02:00',
    '03:00',
    '04:00',
    '05:00',
    '06:00',
    '07:00',
    '08:00',
    '09:00',
    '10:00',
    '11:00',
    '12:00',
    '13:00',
    '14:00',
    '15:00',
    '16:00',
    '17:00',
    '18:00',
    '19:00',
    '20:00',
    '21:00',
    '22:00',
    '23:00',
  ];
 
  /** @ignore */
  protected daysToRender: DayConfig[] = [];
 
  /** @ignore */
  protected focusedAppointment?: AppointmentInternal;
 
  /** @ignore */
  protected ignoreTab = false;
 
  /** @ignore */
  protected internalAppointments: AppointmentInternal[] = [];
 
  /** @ignore */
  protected weekdayAbbreviated = false;
 
  /** @ignore */
  private focusedCell?: CalendarCell;
 
  /** @ignore */
  private elRef: ElementRef<HTMLElement> = inject<ElementRef<HTMLElement>>(
    ElementRef<HTMLElement>,
  );
 
  /** @ignore */
  private resizeObserver?: ResizeObserver;
 
  /** @ignore */
  private zone = inject(NgZone);
 
  /** @ignore */
  private formattedDayDates: FormattedDayDate[] = [];
 
  /** @ignore */
  private addedHeightToWrapper = 0;
 
  /** @ignore */
  private wrapperElMutationObserver?: MutationObserver;
 
  /** @ignore */
  private componentParentElement!: HTMLElement;
 
  /** @ignore */
  private readonly widgetKeys: WidgetKeySet = createWidgetKeySet(
    'gc-calendar-content-days',
  );
 
  constructor() {
    if (this.elRef.nativeElement.parentElement) {
      this.componentParentElement = this.elRef.nativeElement.parentElement;
    }
  }
 
  /** @ignore */
  ngOnChanges(changes: SimpleChanges): void {
    if ('dayConfigs' in changes) {
      this.onDaysChangeHandler();
      this.calendarItems = this.computeEntryLayout();
    }
  }
 
  /** @ignore */
  ngOnInit(): void {
    this.updateInternalAppointments();
    this.calendarItems = this.computeEntryLayout();

    this.initWrapperMutationObserver();
    this.wrapperElMutationObserver?.observe(this.componentParentElement, {
      childList: true,
    });
  }
 
  /** @ignore */
  ngAfterViewInit(): void {
    const workingHourElement = this.cells?.find(
      e =>
        e.nativeElement.getAttribute('data-hour') === this.workingHours.start,
    );

    setTimeout(() => {
      this.height = Number.parseFloat(
        getComputedStyle(this.componentParentElement).height,
      );
      this.zone.runOutsideAngular(() => {
        setTimeout(() => {
          workingHourElement?.nativeElement.scrollIntoView({ block: 'center' });
        });
      });
    });

    this.resizeObserver = new ResizeObserver(this.updateRendering.bind(this));
    this.resizeObserver.observe(this.elRef.nativeElement);
  }
 
  /** @ignore */
  ngOnDestroy(): void {
    this.resizeObserver?.disconnect();
    this.wrapperElMutationObserver?.disconnect();
  }
 
  /** @ignore */
  protected toDayOfWeekText(date: string): string {
    const weekday = this.formattedDayDates.find(d => d.date === date)?.weekday;

    if (!weekday) {
      throw new Error(DATE_PARSING_ERROR_MESSAGE + date);
    }

    if (this.weekdayAbbreviated) {
      return weekday.slice(0, 2) + '.';
    }

    return weekday;
  }
 
  /** @ignore */
  protected toAbbreviatedDayOfWeek(date: string): DayOfWeek {
    const weekdayAbbreviated = this.formattedDayDates.find(
      d => d.date === date,
    )?.dayOfWeekAbbreviation;

    if (!weekdayAbbreviated) {
      throw new Error(DATE_PARSING_ERROR_MESSAGE + date);
    }

    return weekdayAbbreviated;
  }
 
  /** @ignore */
  protected toMonth(date: string): string {
    const formattedDayDate = this.formattedDayDates.find(d => d.date === date);
    if (!formattedDayDate) {
      throw new Error(DATE_PARSING_ERROR_MESSAGE + date);
    }
    return formattedDayDate.month;
  }
 
  /** @ignore */
  protected createIdForCell(cell: CalendarCell): string {
    return cell.day.date + '-' + cell.hour.toFixed(0) + '-' + cell.slot;
  }
 
  /** @ignore */
  protected toDate(date: string): string {
    return new Date(date).getDate().toString();
  }
 
  /** @ignore */
  protected isWorkingHour(hour: string, day?: DayConfig): boolean {
    if (day) {
      return (
        toTimeFraction(hour) >= toTimeFraction(this.workingHours.start) &&
        toTimeFraction(hour) <= toTimeFraction(this.workingHours.end) &&
        day.hasWorkingHours
      );
    } else {
      return (
        toTimeFraction(hour) >= toTimeFraction(this.workingHours.start) &&
        toTimeFraction(hour) <= toTimeFraction(this.workingHours.end)
      );
    }
  }
 
  /** @ignore */
  protected extractHour(time: string): number {
    const hour = time.split(':')[0];
    return Number.parseInt(hour);
  }
 
  /** @ignore */
  protected extractMinutes(time: string): number {
    const minutes = time.split(':')[1];
    return Number.parseInt(minutes);
  }
 
  /** @ignore */
  protected generateAriaLabelForCell(cell: CalendarCell): string {
    const allDayAppointmentsCount = this.appointments.filter(
      a => a.isAllDay && cell.day.date === a.date,
    ).length;

    const slotStartTime = this.timeToFloat(this.generateHourTextForCell(cell));

    const slotEndTime =
      cell.slot === 'first'
        ? this.timeToFloat(
            this.generateHourTextForCell({ ...cell, slot: 'second' }),
          )
        : this.timeToFloat(
            this.generateHourTextForCell({
              ...cell,
              hour: cell.hour + 1 === 24 ? 0 : cell.hour + 1,
              slot: 'first',
            }),
          );

    const firstSlotTimeRangeText =
      this.generateHourTextForCell(cell) +
      ' Uhr bis ' +
      this.generateHourTextForCell({ ...cell, slot: 'second' });

    const secondSlotTimeRangeText =
      this.generateHourTextForCell(cell) +
      ' Uhr bis ' +
      this.generateHourTextForCell({
        ...cell,
        hour: cell.hour + 1 === 24 ? 0 : cell.hour + 1,
        slot: 'first',
      }) +
      ' Uhr';

    const hourRangeText =
      cell.slot === 'first' ? firstSlotTimeRangeText : secondSlotTimeRangeText;

    const isInSlotRange = (time: string) => {
      const startTimeParsed = this.timeToFloat(time);

      return startTimeParsed >= slotStartTime && startTimeParsed < slotEndTime;
    };

    const appointmentsCount = this.appointments.filter(
      a => isInSlotRange(a.time.start) && cell.day.date === a.date,
    ).length;

    const numberOfAppointmentsText =
      appointmentsCount === 1
        ? 'ein Termin'
        : appointmentsCount.toFixed(0) + ' Termine';

    const numberOfAllDayAppointmentsText =
      allDayAppointmentsCount === 1
        ? 'ein Ganztags Termin'
        : allDayAppointmentsCount.toFixed(0) + ' Ganztagtermine';

    const otherAppointmentsText =
      appointmentsCount === 1
        ? ' ein weiterer Termin'
        : appointmentsCount.toFixed(0) + ' weitere Termine';

    const appointmentsText =
      allDayAppointmentsCount > 0
        ? numberOfAllDayAppointmentsText + ' und ' + otherAppointmentsText
        : numberOfAppointmentsText;

    const todayText = cell.day.date === this.today ? 'Heute, ' : '';

    const isWorkingHourText = !this.isWorkingHour(
      cell.hour.toString(),
      cell.day,
    )
      ? ', außerhalb der Arbeitszeit'
      : '';

    return (
      todayText +
      this.toDayOfWeekText(cell.day.date) +
      ', ' +
      this.toMonth(cell.day.date) +
      ' ' +
      this.toDate(cell.day.date) +
      ' ' +
      new Date(cell.day.date).getFullYear().toString() +
      ', ' +
      hourRangeText +
      ', ' +
      appointmentsText +
      isWorkingHourText
    );
  }
 
  /** @ignore */
  protected onAppointmentFocus(appointment: AppointmentInternal): void {
    this.focusedCell = {
      day: { date: appointment.date, hasWorkingHours: true },
      hour: this.extractHour(appointment.time.start),
      slot:
        this.extractMinutes(appointment.time.start) >= 30 ? 'second' : 'first',
    };
    this.focusedAppointment = appointment;

    if (
      !appointment.isAllDay &&
      !this.isFullVisible(this.findAppointmentElement(appointment))
    ) {
      this.findAppointmentElement(appointment).scrollIntoView({
        block: 'center',
        inline: 'center',
        behavior: 'smooth',
      });
    }

    const lastAppElement = this.findLastAppointment();

    this.ignoreTab = this.focusedAppointment.id === lastAppElement.id;
  }
 
  protected isFullVisible(element: HTMLElement) {
    // TODO Revisit and make it less dependent on magic elements
    const scroll = findScrollContainers(element);
    const viewPortTop = scroll[0].scrollTop;
    const viewPortLeft = scroll[0].scrollLeft;
    const viewPortBottom = scroll[0].clientHeight - 96; // we need to remove the header height who is 96px
    const viewPortRight = scroll[0].clientWidth - 96; // we need to remove the hours column

    const wrapper = element.parentElement?.parentElement;
    const column = wrapper?.parentElement;
    if (!wrapper || !column) {
      return false;
    }

    // To compute the top offset we need to use wrapper
    const top = wrapper.offsetTop - viewPortTop;
    const bottom = top + wrapper.clientHeight;

    // To compute the left offset we need to take the column into account
    const left = column.offsetLeft + wrapper.offsetLeft - viewPortLeft;
    const right = left + wrapper.clientWidth;

    if (top < 0) {
      return false;
    } else if (bottom > viewPortBottom) {
      return false;
    } else if (left < 0) {
      console.log('Left out of view');
      return false;
    } else if (right > viewPortRight) {
      return false;
    }
    return true;
  }
 
  /** @ignore */
  protected onAppointmentKeydown(event: KeyboardEvent): void {
    const key = event.key;
    switch (key) {
      case 'ArrowDown':
        this.handleArrowDown();
        break;
      case 'ArrowUp':
        this.handleArrowUp();
        break;
      case 'ArrowLeft':
        this.handleArrowLeft();
        break;
      case 'ArrowRight':
        this.handleArrowRight();
        break;
      case 'Tab':
        this.handleAppointmentTab(event);
        break;
    }
  }
 
  /** @ignore */
  protected onCellKeydown(event: KeyboardEvent, cell: CalendarCell): void {
    const key = event.key;

    switch (key) {
      case 'ArrowDown':
        this.handleArrowDown();
        break;
      case 'ArrowUp':
        this.handleArrowUp();
        break;
      case 'ArrowLeft':
        this.handleArrowLeft();
        break;
      case 'ArrowRight':
        this.handleArrowRight();
        break;
      case 'Enter':
        this.handleEnterPress(event, cell);
        break;
      case 'Tab':
        event.preventDefault();
        this.handleTab(cell, event.shiftKey);
        break;
    }
  }
 
  /** @ignore */
  protected onCellFocusHandler(cell: CalendarCell): void {
    this.focusedCell = cell;
    this.onFocusChange.emit(cell);
  }
 
  /** @ignore */
  protected convertHourToTimeRange(
    hour: number,
    slot: 'first' | 'second',
  ): TimeRange {
    if (slot === 'first') {
      return { start: hour.toFixed(0) + ':00', end: hour.toFixed(0) + ':30' };
    } else {
      return {
        start: hour.toFixed(0) + ':30',
        end: (hour + 1).toFixed(0) + ':00',
      };
    }
  }
 
  /** @ignore */
  protected createIdForAppointment(appointment: Appointment): string {
    return `${this.widgetKeys.baseKey}_entry_${appointment.key}`;
  }
 
  /** @ignore */
  protected determineMaxAppointmentsInLaneForDay(day: DayConfig): number {
    return (
      this.calendarItems
        .find(ci => ci.date === day.date)
        ?.laneLayout.entries.map(e => e.lane.maxLane)
        .sort((a, b) => b - a)[0] ?? 0
    );
  }
 
  /** @ignore */
  protected onAppointmentActionHandler(
    appointment: Appointment,
    event: 'open-details' | 'open-infobox',
  ): void {
    if (event == 'open-details') {
      this.onAppointmentAction.emit({ appointment, event });
    } else {
      console.warn('TODO: implement infobox handling'); // design spec under clarification, see https://gitlab.bestsolution.at/gefa/gefa-web-controls/-/issues/2095#note_225965
    }
  }
 
  /** @ignore */
  protected createIdForContainer(date: string): string {
    return date + '-calendar-appointment-container';
  }
 
  /** @ignore */
  protected createIdForHeaderCell(date: string): string {
    return date + '-calendar-header-cell';
  }
 
  /** @ignore */
  protected focusFirstAppointment(focusEvent: FocusEvent): void {
    // skip manual focus if focus event isn't caused by tabbing into the .gc-wrapper (i.e. it is caused by an inside click)
    if (focusEvent.relatedTarget) {
      return;
    }

    const firstDayWithAppointment = this.dayConfigs.find(day =>
      this.internalAppointments.find(a => a.date === day.date),
    );

    const firstAllDayAppointmentInFirstDay = this.internalAppointments.find(
      a => a.isAllDay,
    );
    const firstAppointmentInFirstDay = this.internalAppointments.find(
      a => a.date === firstDayWithAppointment?.date,
    );

    const appointmentToFocus =
      firstAllDayAppointmentInFirstDay ?? firstAppointmentInFirstDay;

    if (appointmentToFocus) {
      this.findAppointmentElement(appointmentToFocus).focus();
    }
  }
 
  /** @ignore */
  private handleAppointmentTab(event: KeyboardEvent): void {
    const appointmentsInSameDay = this.internalAppointments.filter(
      a => this.focusedAppointment?.date === a.date,
    );
    const tabIndexSelector = '[tabindex]';

    const isLastInDay =
      appointmentsInSameDay.findIndex(
        a => this.focusedAppointment && a.id === this.focusedAppointment.id,
      ) ===
      appointmentsInSameDay.length - 1;

    const indexOfDay = this.dayConfigs.findIndex(
      d => d.date === this.focusedAppointment?.date,
    );

    const nextDayDate = this.dayConfigs[indexOfDay + 1]?.date;
    const prevDayDate = this.dayConfigs[indexOfDay - 1]?.date;

    if (isLastInDay && nextDayDate && !event.shiftKey) {
      const nextAppElementToFocus = document
        .getElementById(this.createIdForHeaderCell(nextDayDate))
        ?.querySelector<HTMLElement>(tabIndexSelector);

      if (nextAppElementToFocus) {
        event.preventDefault();
        nextAppElementToFocus.focus();
      }
    }

    if (event.shiftKey && prevDayDate && this.focusedAppointment?.isAllDay) {
      const previousAppElements =
        document
          .getElementById(this.createIdForContainer(prevDayDate))
          ?.querySelectorAll<HTMLElement>(tabIndexSelector) ??
        document
          .getElementById(this.createIdForHeaderCell(prevDayDate))
          ?.querySelectorAll<HTMLElement>(tabIndexSelector);

      const prevAppElementToFocus = previousAppElements?.item(
        previousAppElements.length - 1,
      );

      if (prevAppElementToFocus) {
        event.preventDefault();
        prevAppElementToFocus.focus();
      }
    }
  }
 
  /** @ignore */
  private initWrapperMutationObserver() {
    this.zone.runOutsideAngular(() => {
      this.wrapperElMutationObserver = new MutationObserver(() => {
        const addedNodes: HTMLElement[] = [];
        this.componentParentElement.childNodes.forEach(n => {
          if (
            n.nodeName !== 'GC-CALENDAR-CONTENT-DAYS' &&
            n instanceof HTMLElement
          ) {
            addedNodes.push(n);
          }
        });

        if (!this.height) {
          return;
        }

        if (
          addedNodes.length === 0 &&
          this.height !== this.height + this.addedHeightToWrapper
        ) {
          this.zone.run(() => {
            if (!this.height) {
              return;
            }
            this.height = this.height + this.addedHeightToWrapper;
          });
        } else {
          this.addedHeightToWrapper = addedNodes.reduce<number>(
            (prev, curr) => curr.offsetHeight,
            0,
          );
          if (this.height !== this.height - this.addedHeightToWrapper) {
            this.zone.run(() => {
              if (!this.height) {
                return;
              }
              this.height = this.height - this.addedHeightToWrapper;
            });
          }
        }
      });
    });
  }
 
  /** @ignore */
  private findLastAppointment() {
    const internalAppointmentsCopy = [...this.internalAppointments];

    internalAppointmentsCopy.sort(
      (a, b) =>
        this.parseNumberFromDate(b.date, 'day') -
        this.parseNumberFromDate(a.date, 'day'),
    );

    return internalAppointmentsCopy
      .filter(a => a.date === internalAppointmentsCopy[0].date)
      .sort(
        (a, b) => this.timeToFloat(b.time.end) - this.timeToFloat(a.time.start),
      )[0];
  }
 
  /** @ignore */
  private timeToFloat(time: string): number {
    return Number.parseFloat(time.replace(':', '.'));
  }
 
  /** @ignore */
  private parseNumberFromDate(
    date: string,
    option: 'day' | 'month' | 'year',
  ): number {
    const idx = {
      day: 2,
      month: 1,
      year: 0,
    };
    return Number.parseInt(date.split('-')[idx[option]]);
  }
 
  /** @ignore */
  private handleTab(cell: CalendarCell, shiftKey: boolean): void {
    const appointmentsInSameDay = this.internalAppointments.filter(
      a => cell.day.date === a.date && !a.isAllDay,
    );

    const nextAppointment = appointmentsInSameDay.find(a => {
      return (
        this.timeToFloat(a.time.start) >=
        (cell.slot === 'first' ? cell.hour : cell.hour + 0.3)
      );
    });
    const focusNextAppointmentElement = () => {
      if (nextAppointment) {
        this.findAppointmentElement(nextAppointment).focus();
      }
    };

    const prevAppIdx = nextAppointment
      ? appointmentsInSameDay.indexOf(nextAppointment) - 1
      : appointmentsInSameDay.length - 1;
    const previousAppointment = appointmentsInSameDay.at(prevAppIdx);

    if (shiftKey && previousAppointment) {
      this.findAppointmentElement(previousAppointment).focus();
    } else {
      focusNextAppointmentElement();
    }
  }
 
  /** @ignore */
  private handleEnterPress(e: KeyboardEvent, cell: CalendarCell): void {
    if (e.shiftKey) {
      this.onCellOpen.emit({
        date: cell.day.date,
        time: this.convertHourToTimeRange(cell.hour, cell.slot),
      });
    }
  }
 
  /** @ignore */
  private handleArrowDown(): void {
    if (!this.focusedCell) {
      return;
    }
    if (this.focusedCell.slot === 'first') {
      this.getCellElement({ ...this.focusedCell, slot: 'second' })?.focus();
    } else {
      this.getCellElement({
        day: this.focusedCell.day,
        slot: 'first',
        hour: this.focusedCell.hour + 1,
      })?.focus();
    }
  }
 
  /** @ignore */
  private handleArrowUp(): void {
    if (!this.focusedCell) {
      return;
    }
    if (this.focusedCell.slot === 'first') {
      this.getCellElement({
        ...this.focusedCell,
        hour: this.focusedCell.hour - 1,
        slot: 'second',
      })?.focus();
    } else {
      this.getCellElement({
        day: this.focusedCell.day,
        slot: 'first',
        hour: this.focusedCell.hour,
      })?.focus();
    }
  }
 
  /** @ignore */
  private handleArrowLeft(): void {
    if (!this.focusedCell) {
      return;
    }

    const currentCellIndex = this.dayConfigs.findIndex(
      day => day.date === this.focusedCell?.day.date,
    );
    const dayToFocus = this.dayConfigs.at(currentCellIndex - 1);

    if (currentCellIndex - 1 >= 0 && dayToFocus) {
      this.getCellElement({ ...this.focusedCell, day: dayToFocus })?.focus();
    }
  }
 
  /** @ignore */
  private handleArrowRight(): void {
    if (!this.focusedCell) {
      return;
    }

    const currentCellIndex = this.dayConfigs.findIndex(
      day => day.date === this.focusedCell?.day.date,
    );
    const dayToFocus = this.dayConfigs.at(currentCellIndex + 1);

    if (dayToFocus) {
      this.getCellElement({ ...this.focusedCell, day: dayToFocus })?.focus();
    }
  }
 
  /** @ignore */
  private getCellElement(cell: CalendarCell): HTMLElement | null {
    return document.getElementById(this.createIdForCell(cell));
  }
 
  /** @ignore */
  private findAppointmentElement(
    appointment: AppointmentInternal,
  ): HTMLElement {
    const appointmentEl = document.getElementById(appointment.id);
    if (!appointmentEl) {
      throw new Error('Element with id: "' + appointment.id + '" is not found');
    }
    return appointmentEl;
  }
 
  /** @ignore */
  private onDaysChangeHandler(): void {
    this.updateInternalAppointments();
    this.formatDayDates();
    this.zone.runOutsideAngular(() => {
      this.updateRendering();
    });
  }
 
  /** @ignore */
  private updateRendering(): void {
    NgZone.assertNotInAngularZone();
    this.detectDaysToRender();

    if (this.columnNumber !== this.daysToRender.length) {
      this.zone.run(() => {
        this.columnNumber = this.daysToRender.length;
      });
    }

    setTimeout(() => {
      const hasNarrowCell = this.dayCellEl?.some(
        el => el.nativeElement.getBoundingClientRect().width < 160,
      );

      if (
        this.weekdayAbbreviated !== hasNarrowCell &&
        hasNarrowCell !== undefined
      ) {
        this.zone.run(() => {
          this.weekdayAbbreviated = hasNarrowCell;
        });
      }

      if (
        this.hasHorizontalScroll !==
        this.wrapperEl.nativeElement.scrollWidth >
          this.wrapperEl.nativeElement.clientWidth
      ) {
        this.hasHorizontalScroll =
          this.wrapperEl.nativeElement.scrollWidth >
          this.wrapperEl.nativeElement.clientWidth;
      }
    });
  }
 
  /** @ignore */
  private detectDaysToRender(): void {
    if (this.elRef.nativeElement.offsetWidth < 420) {
      this.zone.run(() => {
        this.daysToRender = this.dayConfigs.filter(d => d.date === this.today);
      });
    } else if (this.daysToRender !== this.dayConfigs) {
      this.zone.run(() => {
        this.daysToRender = [...this.dayConfigs];
      });
    }
  }
 
  /** @ignore */
  private updateInternalAppointments(): void {
    this.internalAppointments = this.appointments.map(ac => {
      return {
        ...ac,
        id: this.createIdForAppointment(ac),
      };
    });

    this.sortAppointments(this.internalAppointments);
  }
 
  /** @ignore */
  private sortAppointments(
    appointments: AppointmentInternal[],
  ): AppointmentInternal[] {
    return appointments.sort((a, b) => {
      // Sort by startTime
      if (a.time.start < b.time.start) {
        return -1;
      }
      if (a.time.start > b.time.start) {
        return 1;
      }

      // If start times are equal, sort by primaryInfo
      if (a.label < b.label) {
        return -1;
      }
      if (a.label > b.label) {
        return 1;
      }

      if (a.sublabel && b.sublabel) {
        // If primaryInfo is also equal, sort by secondaryInfo
        if (a.sublabel < b.sublabel) {
          return -1;
        }
        if (a.sublabel > b.sublabel) {
          return 1;
        }
      }

      // If secondaryInfo is also equal, sort by ID
      return a.id.localeCompare(b.id);
    });
  }
 
  /** @ignore */
  private generateHourTextForCell(cell: CalendarCell): string {
    const prefixedHour =
      cell.hour < 10 ? '0' + cell.hour.toFixed(0) : cell.hour.toFixed(0);
    return cell.slot === 'first' ? prefixedHour + ':00' : prefixedHour + ':30';
  }
 
  /** @ignore */
  private computeEntryLayout(): CalendarDayLayout[] {
    return this.dayConfigs.map(day => {
      const layoutEntries = this.internalAppointments
        .filter(a => a.date === day.date && !a.isAllDay)
        .map(a => toLaneLayoutEntry(a));

      const laneLayout = computeLaneLayout(layoutEntries);

      return {
        date: day.date,
        laneLayout,
        items: [],
      };
    });
  }
 
  private formatDayDates(): void {
    const options: DateTimeFormatOptions = {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    };

    const dateTimeFormatDe = new Intl.DateTimeFormat('de-DE', options);

    this.formattedDayDates = this.dayConfigs.map<FormattedDayDate>(d => {
      const days: DayOfWeek[] = [
        'sun',
        'mon',
        'tue',
        'wed',
        'thu',
        'fri',
        'sat',
      ];
      const weekday = dateTimeFormatDe
        .formatToParts(Date.parse(d.date))
        .find(d => d.type === 'weekday');
      const month = dateTimeFormatDe
        .formatToParts(Date.parse(d.date))
        .find(d => d.type === 'month');
      const day = new Date(Date.parse(d.date)).getDay();

      if (!weekday || !month) {
        throw new Error(DATE_PARSING_ERROR_MESSAGE + d.date);
      }

      return {
        date: d.date,
        weekday: weekday.value,
        month: month.value,
        dayOfWeekAbbreviation: days[day],
      } satisfies FormattedDayDate;
    });
  }
}
 
/** @ignore */
function toTimeFraction(time: string) {
  const parts = time.split(':');
  const hours = parseInt(parts[0]);
  const minutes = parseInt(parts[1]);

  const hourFraction = 100 / 24;
  const minuteFraction = hourFraction / 60;
  return hourFraction * hours + minuteFraction * minutes;
}
 
/** @ignore */
function toLaneLayoutEntry(
  appointment: AppointmentInternal,
): LaneLayoutEntry<AppointmentInternal> {
  return {
    data: appointment,
    dimension: {
      min: toTimeFraction(appointment.time.start),
      max: toTimeFraction(appointment.time.end),
    },
    lane: { startLane: 0, endLane: 1, maxLane: 1 },
  };
}