All files / lib/internal/menu menu.component.ts

97.22% Statements 1087/1118
94.65% Branches 230/243
96.77% Functions 60/62
97.22% Lines 1087/1118

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 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 11191x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1221x 1221x 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1305x 1305x 1305x 1305x 1305x 359x 946x 1305x 1221x 1221x 9504x 9504x 1221x 1221x 1221x 1221x 1221x 80325x 80325x 80325x 1221x 1221x 8208x 8208x 8208x 814x 814x 7394x 7394x 7394x       8208x 8208x 1221x 1221x 1221x 1221x 1221x 6206x 6206x 1221x 1221x 1221x 1221x 1221x 267x 267x 267x 267x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1221x 1x 1x 1221x 1221x 1221x 1221x 1221x 1x 1x 1x 1x 1x 10833x 417x 10833x 10833x 10833x 1305x 10833x 10833x 10833x 10833x 9667x 9667x 1169x 1169x 1169x 10833x 10833x 10833x 10833x 10416x 9528x 1346x 1346x 10833x 10833x 10833x 10833x 147x 10765x 8256x 814x       10833x 10833x 10833x 1x 1x 1x 1x 1x 127x 127x 127x 1x 1x 1x 1x 1x 126x 107x 107x 126x 126x 1x 1x 1x 1x 1x 98x 1x 97x 97x 13x 97x 97x 98x 98x 98x 13x 98x 98x 1x 1x 1x 1x 1x 17x 17x 17x 17x 1x 1x 1x 1x 1x 116x 116x 116x 116x 116x 35x 2x 2x 2x 3x 3x 3x 3x 6x 1x 1x 1x 35x 29x     29x 29x 35x 116x 116x 116x 6x 6x 116x 116x 1x 1x 1x 1x 1x 34256x 34256x 1x 1x 1x 1x 1x 174x 174x 174x 72x 174x 174x 174x 174x 1x 1x 1x 1x 1x 171x 171x 171x 171x 171x 171x 171x 171x 171x 171x 66x 66x 66x 66x 66x 66x 66x 13x 10x 10x 66x 66x 171x 1x 1x 1x 1x 1x 210x 210x 1x 1x 1x 1x 1x 32x 4x 4x 4x 4x 4x 4x 4x 4x 31x 32x 1x 1x 1x 1x 1x 132x 132x 132x 132x 132x 27x 23x 23x 23x 23x 23x 43x 2x 2x 2x 2x 2x 2x 2x 104x 63x 63x 63x 86x 8x 8x 8x 91x 1x 1x 105x 3x 3x 3x 4x 1x 1x 1x 1x 1x 10x 20x 3x 3x 3x 11x 11x 3x 3x 3x 130x 25x 25x 25x 132x 132x 132x 131x 131x 132x 132x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 458x 458x 1x 1x 1x 1x 1x 170281x 170281x 1x 1x 1x 1x 1x 166042x 166042x 1x 1x 1x 1x 1x 77069x 77069x 1x 1x 1x 5952x 5952x 1x 1x 1x 1x 1x 40526x 40526x 40526x 40526x 40526x 1x 1x 1x 1x 1x 23931x 23931x 23931x 23931x 1x 1x 1x 1x 1x 296612x 296612x 296612x 296612x 1x 1x 1x 1x 1x 83021x 83021x 83021x 3500x 83021x 83021x 1x 1x 1x 1x 1x 143x 143x 143x 60x 60x 60x 60x 60x 60x 60x 143x 143x 143x 4x 143x 143x 143x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 67x 67x 67x 67x 61x 61x 3x 3x 3x 64x 64x 64x 64x 64x           64x 64x 64x 67x 67x 1x 1x 181x 181x 181x 181x 181x 181x 181x 181x 124x 124x 181x 181x 10x 66x 66x 181x 181x 1x 1x 1x 1x 1x 13x 13x 13x 13x   13x 13x 13x 3x 3x 3x 3x 10x 10x 10x 10x 10x 13x 13x 13x 13x 13x 13x 13x 1x 1x 1x 1x 1x 124x 107x 10x 97x 94x 3x 3x 107x 107x 124x 124x 124x 124x 124x 124x 1x 1x 124x 124x 124x 124x       107x 107x 107x 107x 107x       124x 124x 1x 1x 1x 1x 1x 106x 8x 8x 8x 98x 98x 98x 98x 106x 106x 106x 1x 1x 1x 1x 1x 53x 53x 53x 47x 47x 6x 6x 6x 6x 6x 6x 6x 1x 5x 5x 6x 6x 6x 53x 53x 1x 1x 1x 1x 1x 192x 192x 192x 192x 192x 192x 192x 192x 1x 1x 1x 1x 1x 1x 1x 252x 252x 252x 252x 252x 252x 252x 252x 25x 227x   252x 252x 1x 1x 1x 1x 1x 97x 97x 97x 97x 97x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 63x 63x 63x   63x 63x 63x 63x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1x 1x 1x 1x 1x 8x 8x 1x 7x 7x 8x 8x 1x 1x 1x 1x 1x 25x 25x 12x 12x 12x 13x 25x 25x 8x 25x 25x 1x 1x 1x 1x 1x 25x 25x 25x 25x 94x 94x 28x 28x 25x 25x 25x 19x 70x 70x 48x 48x 19x 19x 25x 25x 25x 1x 1x 1x 1x 1x 160x 160x 1x 1x 1x 1x 1x 15x 15x 1x 1x 1x 1x 1x 1297x 1010x 1010x 1010x 111x 111x 899x 899x 899x 1010x 1010x 1297x 1x 1x 1x 1x 1x 1030x 1030x 1030x 1030x 156x 874x 874x 1030x 1030x 1030x 1x 1x 1x 1x 1x 1346x 1346x 1346x 267x 267x 59x 208x 208x 267x 267x 267x 267x 1079x 1079x 1346x 1346x 1346x 1x 1x 1473x 103x 103x 103x 103x 1473x 1473x 1x 1x 1x 1x 1x 1305x 1305x 1305x 1030x 1030x 1030x 1030x 940x 940x 940x 940x 940x 940x 940x 940x 940x 940x 940x 90x 90x 90x 90x 90x 90x 90x 90x 90x 19x 19x 19x 19x 17x 17x 19x 19x 90x 90x 90x 90x 90x 90x 15x 15x 15x 90x 90x 90x 1030x 1030x 804x 804x 105x 105x 105x 804x 1030x 1030x 1030x 1030x 1030x 1305x 1x 1x 1x 1x 1x 417x 417x     417x 417x 1x  
/*******************************************************************************
 * Copyright bei
 * Entwicklungs- und Pflegeverbund für das gemeinsame Fachverfahren gefa
 *
 *******************************************************************************/
import {
  Component,
  Directive,
  ElementRef,
  EventEmitter,
  Input,
  OnChanges,
  OnDestroy,
  Output,
  QueryList,
  SimpleChanges,
  TemplateRef,
  ViewChild,
  ViewChildren,
} from '@angular/core';
 
import {
  Maybe,
  isPrintableCharacter,
  subscribe,
  textToLine,
  waitForRender,
} from '../../utils/internal-utils';
import {
  Callback,
  Item,
  ItemGroup,
  Key,
  MenuItemWithChildren,
  hasSublabel,
} from '../../utils/util.types';
import { isItemGroup, itemTrack } from '../../utils/utilities';
 
import {
  Alignment,
  OverlayContainerComponent,
  OverlayLocation,
} from '../overlay-container/overlay-container.component';
 
interface MenuItemsTemplateContext {
  $implicit: Item[];
}
 
@Directive({
  selector: 'ng-template[data-gc-menu-item]',
  standalone: false,
})
export class MenuItemsTemplateDirective {
  constructor(
    public readonly template: TemplateRef<MenuItemsTemplateContext>,
  ) {}
 
  /**
   * @ignore
   */
  static ngTemplateContextGuard(
    _dir: MenuItemsTemplateDirective,
    ctx: unknown,
  ): ctx is MenuItemsTemplateContext {
    return true;
  }
}
 
let UNIQUE_ID = 0;
 
const ARIA_CONTROLS = 'aria-controls';
const ARIA_EXPANDED = 'aria-expanded';
const ARIA_HASPOPUP = 'aria-haspopup';
 
type BaseMenuItem<T> = T | MenuItemWithChildren<BaseMenuItem<T>>;
type MenuItemType<T> = readonly ItemGroup<T>[] | readonly BaseMenuItem<T>[];
 
/**
 * A Menu element that opens a menu with multiple items as options.
 */
@Component({
  selector: 'gc-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.css'],
  standalone: false,
})
export class MenuComponent<T extends Item> implements OnDestroy, OnChanges {
  /**
   * Action that is fired when an menu item is pressed.
   */
  @Output()
  public readonly onAction: EventEmitter<T> = new EventEmitter<T>();
 
  /**
   * A separate element that is as an anchor.
   * Overrides the *menuOwner* as anchor if set.
   */
  @Input()
  public anchor?: ElementRef<HTMLElement>;
 
  /** Internal callback method that fires when menu is closed and overrides the default focus behavior. */
  @Input()
  public _onMenuClosedFocusCallback?: Callback;
 
  /**
   * Fired when popup menu is closed.
   */
  @Output()
  public readonly onClose: EventEmitter<string> = new EventEmitter<string>();
 
  /**
   * All items in the menu that are disabled.
   */
  @Input()
  public disabledItems: ReadonlySet<string> = new Set();
 
  /**
   * Number of pixels that the menu will be offset from the anchor.
   */
  @Input()
  public offset = 0;
 
  /**
   * Decides on which side of the menuOwner element the menu is going to appear.
   */
  @Input()
  public alignment: Alignment = 'end';
 
  /**
   * Decides upon which mouse event the menu will be triggered. In case of contextmenu the anchor element
   * must have a position relative and it must be able to append child nodes
   */
  @Input()
  public mouseEventType: 'click' | 'contextmenu' = 'click';
 
  /** Override the element which is used to label the menu, by default the menu owner is used. */
  @Input()
  public menuLabelledByOverride?: string;
 
  /** Optional icon provider */
  @Input()
  public iconProvider?: TemplateRef<unknown>;
 
  /**
   * Optional stores the identifier of an item to be marked as currently selected
   */
  @Input()
  public selectedItem?: Key;
 
  /**
   * Renders the label and sublabel in the same line with a colon symbol (':') used as separator in-between.
   */
  @Input()
  public singleLineLabels = false;
 
  /** @ignore */
  @Input()
  protected parentReference?: {
    parentMenu: MenuComponent<T>;
    itemOwnerKey: Key;
  };
 
  /** @ignore */
  @ViewChildren('menuitem')
  protected menuItemElements!: QueryList<ElementRef<HTMLElement>>;
 
  /** @ignore */
  @ViewChild('menu')
  protected menuContainer?: ElementRef<HTMLElement>;
 
  /** @ignore */
  @ViewChild('overlaycontainer', { static: true })
  private overlayContainer?: OverlayContainerComponent;
 
  /** @ignore */
  @ViewChildren('submenu')
  private submenuComponents?: QueryList<MenuComponent<T>>;
 
  /**
   * An element that acts as the menu owner and anchor.
   */
  @Input()
  public set menuOwner(
    owner: ElementRef<HTMLElement> | HTMLElement | undefined,
  ) {
    this._menuOwner =
      owner === undefined || 'nativeElement' in owner
        ? owner
        : new ElementRef(owner);
  }
 
  public get menuOwner(): ElementRef<HTMLElement> | undefined {
    return this._menuOwner;
  }
 
  /**
   * All items that will appear in the menu.
   */
  @Input()
  public get menuItems(): MenuItemType<T> {
    return this._menuItems;
  }
 
  public set menuItems(items: MenuItemType<T>) {
    this._menuItems = items;
    if (items.length > 0) {
      if (this._isItemGroup(items)) {
        this._menuItemsHaveSublabels = items.some(
          item => item.items.length > 0 && hasSublabel(item.items[0]),
        );
      } else {
        this._menuItemsHaveSublabels = hasSublabel(items[0]);
      }
    } else {
      this._menuItemsHaveSublabels = false;
    }
  }
 
  /**
   * @ignore
   */
  get menuOpen(): boolean {
    return this._menuOpen;
  }
 
  /**
   * @ignore
   */
  set menuOpen(menuOpen: boolean) {
    this._menuOpen = menuOpen;
 
    this.updateMenuOwnerAriaAttributes();
  }
 
  /**
   * @ignore
   */
  public _overlayLocation: OverlayLocation = 'end-bottom';
 
  /**
   * @ignore
   */
  public readonly _menuId: string;
 
  /**
   * @ignore
   */
  public _menuOwnerId: string;
 
  /**
   * @ignore
   */
  public _menuOpen = false;
 
  /** @ignore */
  public _menuItemsHaveSublabels = false;
 
  /** @ignore */
  public _alignmentInternal: Alignment = 'end';
 
  /**
   * @ignore
   */
  protected _offsetInternal = 0;
 
  /**
   * @ignore
   */
  protected readonly menuComponent!: MenuComponent<T>;
 
  /** @ignore */
  private _menuOwner?: ElementRef<HTMLElement>;
 
  /** @ignore */
  private _currentSelectedItemIndex = -1;
 
  /** @ignore */
  private _menuItems: MenuItemType<T> = [];
 
  /** @ignore */
  private positionOverride = false;
 
  /**
   * @ignore
   */
  private menuHasFocus = false;
 
  /**
   * @ignore
   */
  private postPopupVisibleBlock: Callback | undefined;
 
  /**
   * @ignore
   */
  private menuOwnerCleanupCallbacks: Callback[] = [];
 
  /** @ignore */
  private locationOverrideAnchor?: HTMLSpanElement;
 
  constructor() {
    this.menuComponent = this;
    this._menuId = 'menu-' + UNIQUE_ID.toString();
    this._menuOwnerId = 'menu-owner-' + UNIQUE_ID.toString();
    UNIQUE_ID++;
  }
 
  /**
   * @ignore
   */
  ngOnChanges(changes: SimpleChanges): void {
    if ('mouseEventType' in changes) {
      this.initPositionOverride();
    }
 
    if ('menuOwner' in changes) {
      this.initMenuOwner();
    }
 
    if (
      'alignment' in changes ||
      'mouseEventType' in changes ||
      'offset' in changes
    ) {
      this._alignmentInternal = this.alignment;
      this._offsetInternal = this.offset;
    }
 
    if (
      'mouseEventType' in changes ||
      'menuOwner' in changes ||
      'anchor' in changes
    ) {
      this.determineOverlayContainerAnchor();
    }
 
    if (
      (('selectedItem' in changes &&
        changes.selectedItem.currentValue !== undefined) ||
        'menuItems' in changes) &&
      this._isItemGroup(this.menuItems) &&
      this.selectedItem
    ) {
      console.error(
        'Selected Item is not supported together with grouped items in menu',
      );
    }
  }
 
  /**
   * @ignore
   */
  ngOnDestroy(): void {
    this.cleanupLocationOverrideAnchor();
    this.menuOwnerCleanupCallbacks.forEach(cleanup => cleanup());
  }
 
  /**
   * @ignore
   */
  protected _handlePopupVisible(): void {
    if (this.postPopupVisibleBlock) {
      this.postPopupVisibleBlock();
      this.postPopupVisibleBlock = undefined;
    }
  }
 
  /**
   * @ignore
   */
  protected _handleOwnerAction(event: MouseEvent): void {
    if (this.menuOpen && !this.parentReference) {
      this.closePopupMenu(true);
    } else {
      if (this.mouseEventType === 'contextmenu') {
        this.handleContextMenuEvent(event);
      }
      this.openPopupMenu('first', true);
    }
 
    if (this.mouseEventType === 'contextmenu') {
      event.preventDefault();
    }
  }
 
  /**
   * @ignore
   */
  protected async _handleOwnerHover(): Promise<void> {
    // waits for the overlay container to become stable
    await waitForRender();
    this.openPopupMenu('first', false);
  }
 
  /**
   * @ignore
   */
  protected _handleOwnerKeyDown(event: KeyboardEvent): void {
    const key = event.key;
    let flag = false;
 
    if (this.mouseEventType !== 'contextmenu') {
      switch (key) {
        case 'ArrowDown':
          flag = true;
          this.openPopupMenu('first', true);
          break;
        case 'ArrowUp':
          flag = true;
          this.openPopupMenu('last', true);
          break;
        case 'Escape':
          flag = true;
          this.closePopupMenu(false);
          break;
        default:
          if (this.menuOpen && isPrintableCharacter(key)) {
            this.moveFocusToNextItemStartingWithChar(key);
            flag = true;
          }
          break;
      }
    }
 
    if (flag) {
      event.stopPropagation();
      event.preventDefault();
    }
  }
 
  /**
   * @ignore
   */
  protected _itemTrackBy(_index: number, item: Item): string {
    return itemTrack(item);
  }
 
  /**
   * @ignore
   */
  protected _handleOwnerBlur(): void {
    if (!this.menuHasFocus) {
      setTimeout(() => {
        if (!this.menuHasFocus) {
          this.closePopupMenu(false);
        }
      });
    }
  }
 
  /**
   * @ignore
   */
  protected _handleMenuItemBlur(event: FocusEvent): void {
    const relatedTargetIsMenuItemElement = this.menuItemElements.some(
      el => el.nativeElement === event.relatedTarget,
    );
    this.menuHasFocus = relatedTargetIsMenuItemElement;
    const relatedTargetIsChild = this.isFocusTargetRecursiveChild(
      this,
      event.relatedTarget,
    );
 
    if (!relatedTargetIsChild) {
      const recursiveParentMenu = this.findRecursiveParentMenu(
        this,
        event.relatedTarget,
      );
      if (
        !relatedTargetIsMenuItemElement &&
        this.menuOpen &&
        event.relatedTarget !== recursiveParentMenu.menuOwner?.nativeElement
      ) {
        recursiveParentMenu.closePopupMenu(event.relatedTarget === null);
      }
    }
  }
 
  /**
   * @ignore
   */
  protected _handleMenuItemFocus(): void {
    this.menuHasFocus = true;
  }
 
  /**
   * @ignore
   */
  protected _handleMenuItemClick(itemKey: Key): void {
    if (this._isItemDisabled(itemKey)) {
      this.findItemByKey(itemKey).then(i => {
        const idx = this.menuItems.findIndex(m => m === i);
        if (idx >= 0) {
          this._currentSelectedItemIndex = idx;
        }
      });
      return;
    }
    this.handleMenuItemSelect(itemKey);
  }
 
  /**
   * @ignore
   */
  protected _handleMenuItemKeyDown(event: KeyboardEvent, itemKey: Key): void {
    const key = event.key;
    let flag = false;
 
    switch (key) {
      case 'Enter':
      case ' ':
        if (!this._isItemDisabled(itemKey)) {
          this.handleMenuItemSelect(itemKey);
        }
        flag = true;
        break;
      case 'ArrowRight':
        this.findItemByKey(itemKey).then(item => {
          if (this.isItemHasChildren(item) && !this._isItemDisabled(itemKey)) {
            this.handleMenuItemSelect(itemKey);
            flag = true;
          }
        });
        break;
      case 'ArrowDown':
        flag = true;
        this.moveFocusToNextItem();
        break;
      case 'ArrowUp':
        this.moveFocusToPrevItem();
        flag = true;
        break;
      case 'Tab':
        this.findRecursiveParentMenu(this, null).closePopupMenu(true);
        break;
      case 'Escape':
        this.closePopupMenu(true);
        flag = true;
        break;
      case 'ArrowLeft':
        if (this.parentReference) {
          this.closePopupMenu(true);
          flag = true;
        }
        break;
      case 'Home':
      case 'PageUp':
        this.moveFocusToFirstItem();
        flag = true;
        break;
      case 'End':
      case 'PageDown':
        this.moveFocusToLastItem();
        flag = true;
        break;
      default:
        if (isPrintableCharacter(key)) {
          this.moveFocusToNextItemStartingWithChar(key);
          flag = true;
        }
    }
    if (flag) {
      event.stopPropagation();
      event.preventDefault();
    }
  }
 
  /**
   * @ignore
   */
  protected _handleHide(): void {
    this.closePopupMenu(true);
  }
 
  /**
   * @ignore
   */
  protected _handleLocationChange(location: OverlayLocation): void {
    this._overlayLocation = location;
  }
 
  /**
   * @ignore
   */
  protected _isItemDisabled(itemKey: Key) {
    return this.disabledItems.has(itemKey);
  }
 
  /**
   * @ignore
   */
  protected _isItemSelected(itemKey: Key) {
    return this.selectedItem === itemKey;
  }
 
  /**
   * @ignore
   */
  protected _processItemText(text: string) {
    return textToLine(text, 32, '<br>');
  }
 
  /** @ignore */
  protected _itemSublabelText(item: Item): string | undefined {
    return hasSublabel(item) ? item.sublabel : undefined;
  }
 
  /**
   * @ignore
   */
  protected _isItemGroup(
    items: MenuItemType<T>,
  ): items is readonly ItemGroup<T>[] {
    const item = items[0];
    return isItemGroup(item);
  }
 
  /**
   * @ignore
   */
  protected _hasAnyItemChildren(
    items: MenuItemType<T>,
  ): items is readonly MenuItemWithChildren<T>[] {
    return items.some(mi => this.isItemHasChildren(mi));
  }
 
  /**
   * @ignore
   */
  protected isItemHasChildren(
    item: Item | ItemGroup<T> | MenuItemWithChildren<T>,
  ): item is MenuItemWithChildren<T> {
    return 'children' in item;
  }
 
  /**
   * @ignore
   */
  protected isItemChildMenuOpen(itemKey: Key): boolean {
    return (
      this.submenuComponents?.some(
        menu => menu.parentReference?.itemOwnerKey === itemKey && menu.menuOpen,
      ) ?? false
    );
  }
 
  /**
   * @ignore
   */
  protected closePopupMenu(focusOwner: boolean): void {
    this.menuOpen = false;
    if (focusOwner) {
      if (this._onMenuClosedFocusCallback) {
        this._onMenuClosedFocusCallback();
      } else {
        const el = this.menuOwner?.nativeElement;
        if (el) {
          this.focusElement(el);
        }
      }
    }
    const childSubmenu = this.submenuComponents?.find(el => el.menuOpen);
    if (childSubmenu) {
      childSubmenu.closePopupMenu(false);
    }
    this.onClose.emit(this._menuOwnerId);
  }
 
  /**
   * @ignore
   */
  protected onMenuItemAction(itemKey: T) {
    this.onAction.emit(itemKey);
    this.closePopupMenu(this.parentReference ? false : true);
  }
 
  private findRecursiveParentMenu(
    menu: MenuComponent<T>,
    focusTarget: EventTarget | null,
  ): MenuComponent<T> {
    if (focusTarget !== null) {
      const found = menu.parentReference?.parentMenu.menuItemElements.some(
        el => el.nativeElement === focusTarget,
      );
      if (found) {
        return menu;
      }
    }
    const openedParentMenu =
      menu.parentReference?.parentMenu.submenuComponents?.some(
        el => el.menuOpen,
      );
    if (openedParentMenu && menu.parentReference) {
      return this.findRecursiveParentMenu(
        menu.parentReference.parentMenu,
        focusTarget,
      );
    } else {
      return menu;
    }
  }
 
  private isFocusTargetRecursiveChild(
    menu: MenuComponent<T>,
    focusTarget: EventTarget | null,
  ): boolean {
    const found = menu.menuItemElements.some(
      el => el.nativeElement === focusTarget,
    );
    if (found) {
      return true;
    }
 
    const openedSubmenu = menu.submenuComponents?.find(el => el.menuOpen);
    if (openedSubmenu) {
      return this.isFocusTargetRecursiveChild(openedSubmenu, focusTarget);
    } else {
      return false;
    }
  }
 
  /**
   * @ignore
   */
  private handleContextMenuEvent(event: MouseEvent): void {
    if (this.menuOwner) {
      let menuOverrideAnchorLeft = 0;
      let menuOverrideAnchorTop = 0;
      const menuOwnerBounds = this.anchor
        ? this.anchor.nativeElement.getBoundingClientRect()
        : this.menuOwner.nativeElement.getBoundingClientRect();
      // checks if contextmenu event source is not a right mouse button & alignment === auto
      if (event.button !== 2 && this.alignment === 'auto') {
        this._alignmentInternal = 'middle';
        menuOverrideAnchorLeft = menuOwnerBounds.width / 2;
        menuOverrideAnchorTop = menuOwnerBounds.height / 2;
        this._offsetInternal = this.offset;
      } else {
        this._alignmentInternal = this.alignment;
        menuOverrideAnchorLeft = event.clientX - menuOwnerBounds.left;
        menuOverrideAnchorTop = event.clientY - menuOwnerBounds.top;
        this._offsetInternal = 0;
      }
      if (this.locationOverrideAnchor) {
        this.locationOverrideAnchor.style.left = `${menuOverrideAnchorLeft.toFixed(0)}px`;
        this.locationOverrideAnchor.style.top = `${menuOverrideAnchorTop.toFixed(0)}px`;
      }
    }
  }
 
  /**
   * @ignore
   */
  private openPopupMenu(select: 'first' | 'last', moveFocus: boolean): void {
    const moveFocusMethod = () => {
      if (this.selectedItem) {
        this.moveFocusToSelectedItem();
      } else if (select === 'first') {
        this.moveFocusToFirstItem();
      } else {
        this.moveFocusToLastItem();
      }
    };
 
    const openedSiblingMenu =
      this.parentReference?.parentMenu.submenuComponents?.find(
        sm => sm.menuOpen && sm._menuId !== this._menuId,
      );
    if (openedSiblingMenu) {
      openedSiblingMenu.closePopupMenu(
        !this.parentReference?.parentMenu.menuHasFocus,
      );
    }
 
    if (!this.menuOpen) {
      this._currentSelectedItemIndex = -1;
      this.menuOpen = true;
      if (moveFocus) {
        this.postPopupVisibleBlock = () => {
          setTimeout(() => {
            moveFocusMethod();
          });
        };
      }
    } else if (moveFocus) {
      moveFocusMethod();
    }
  }
 
  /**
   * @ignore
   */
  private findItemByKey(itemKey: Key): Maybe<T> {
    if (this._isItemGroup(this.menuItems)) {
      const flatItems = this.menuItems.flatMap(i => i.items);
      return Maybe.maybe(flatItems.find(item => item.key === itemKey));
    } else {
      return Maybe.maybe(
        this.menuItems
          .flatMap(i => i as unknown as T)
          .find(item => item.key === itemKey),
      );
    }
  }
 
  /**
   * @ignore
   */
  private handleMenuItemSelect(itemKey: Key) {
    this.findItemByKey(itemKey).then(item => {
      if (!this.isItemHasChildren(item)) {
        this.closePopupMenu(true);
        this.findItemByKey(itemKey).then(
          this.onAction.emit.bind(this.onAction),
        );
      } else {
        const subMenu = this.submenuComponents?.find(
          menu => menu.parentReference?.itemOwnerKey === itemKey,
        );
        if (subMenu) {
          if (subMenu.menuOpen) {
            subMenu.closePopupMenu(true);
          } else {
            subMenu.openPopupMenu('first', true);
          }
        }
      }
    });
  }
 
  /**
   * @ignore
   */
  private moveFocusToIndex(index: number) {
    this._currentSelectedItemIndex = index;
 
    const el = this.menuItemElements.get(index)?.nativeElement;
 
    if (el) {
      this.focusElement(el);
    }
  }
 
  /**
   * Because we are position fixed focusing the element does not scroll it into view
   * and we need to do that manually
   * @ignore
   */
  private focusElement(el: HTMLElement) {
    // Make sure scrolling is never done when moving focus
    el.focus({ preventScroll: true });
    const topY = el.getBoundingClientRect().top;
    const bottomY = el.getBoundingClientRect().bottom;
 
    const bodyHeight = document.documentElement.getBoundingClientRect().height;
 
    if (bottomY > bodyHeight) {
      document.documentElement.scrollBy(0, bottomY - bodyHeight);
    } else if (topY < 0) {
      document.documentElement.scrollBy(0, topY);
    }
  }
 
  /**
   * @ignore
   */
  private moveFocusToFirstItem(): void {
    const idx = this.findNextFocusIndex(-1);
    if (idx >= 0) {
      this.moveFocusToIndex(idx);
    }
  }
 
  /**
   * @ignore
   */
  private moveFocusToLastItem(): void {
    const idx = this.findPrevFocusIndex(this.menuItemElements.length);
    if (idx >= 0) {
      this.moveFocusToIndex(idx);
    }
  }
 
  /**
   * @ignore
   */
  private moveFocusToNextItem(): void {
    const idx = this.findNextFocusIndex(this._currentSelectedItemIndex);
 
    if (idx >= this.menuItemElements.length) {
      this.moveFocusToFirstItem();
    } else {
      this.moveFocusToIndex(idx);
    }
  }
 
  /**
   * @ignore
   */
  private moveFocusToSelectedItem(): void {
    if (this.selectedItem === undefined) {
      this.moveFocusToFirstItem();
    } else {
      const idx = this.menuItems.findIndex(v => this.selectedItem === v.key);
      if (idx >= 0) {
        this.moveFocusToIndex(idx);
      }
    }
  }
 
  /**
   * @ignore
   */
  private moveFocusToPrevItem(): void {
    const idx = this.findPrevFocusIndex(this._currentSelectedItemIndex);
    if (idx === -1) {
      this.moveFocusToLastItem();
    } else {
      this.moveFocusToIndex(idx);
    }
  }
 
  /**
   * @ignore
   */
  private moveFocusToNextItemStartingWithChar(char: string): void {
    let idx = -1;
    if (this._isItemGroup(this.menuItems)) {
      const flatItems = this.menuItems.flatMap(i => i.items);
      idx = this.findItemIndexByItemStartingWithChar(char, flatItems);
    } else {
      idx = this.findItemIndexByItemStartingWithChar(char, this.menuItems);
    }
    if (idx !== -1) {
      this.moveFocusToIndex(idx);
    }
  }
 
  /**
   * @ignore
   */
  private findItemIndexByItemStartingWithChar(
    char: string,
    items: MenuItemType<T>,
  ): number {
    let idx = items.findIndex((item, indx) => {
      return (
        indx > this._currentSelectedItemIndex &&
        !this._isItemDisabled(item.key) &&
        item.label.toLocaleLowerCase().startsWith(char.toLocaleLowerCase())
      );
    });
    if (idx === -1) {
      idx = items.findIndex((item, indx) => {
        return (
          indx <= this._currentSelectedItemIndex &&
          !this._isItemDisabled(item.key) &&
          item.label.toLocaleLowerCase().startsWith(char.toLocaleLowerCase())
        );
      });
    }
    return idx;
  }
 
  /**
   * @ignore
   */
  private findNextFocusIndex(start: number): number {
    return start + 1;
  }
 
  /**
   * @ignore
   */
  private findPrevFocusIndex(end: number) {
    return end - 1;
  }
 
  /**
   * @ignore
   */
  private updateMenuOwnerAriaAttributes(): void {
    if (this.menuOwner && this.mouseEventType !== 'contextmenu') {
      const menuOwnerElement = this.menuOwner.nativeElement;
 
      if (this.menuOpen) {
        menuOwnerElement.setAttribute(ARIA_CONTROLS, this._menuId);
        menuOwnerElement.setAttribute(ARIA_EXPANDED, 'true');
      } else {
        menuOwnerElement.removeAttribute(ARIA_CONTROLS);
        menuOwnerElement.setAttribute(ARIA_EXPANDED, 'false');
      }
    }
  }
 
  /**
   * @ignore
   */
  private updateMenuOwnerId(): void {
    if (this.menuOwner) {
      const existingMenuOwnerId =
        this.menuOwner.nativeElement.getAttribute('id');
      if (existingMenuOwnerId) {
        this._menuOwnerId = existingMenuOwnerId;
      } else {
        this.menuOwner.nativeElement.setAttribute('id', this._menuOwnerId);
      }
    }
  }
 
  /**
   * @ignore
   */
  private determineOverlayContainerAnchor(): void {
    this.cleanupLocationOverrideAnchor();
    if (this.overlayContainer) {
      if (this.positionOverride && this.menuOwner) {
        this.locationOverrideAnchor = document.createElement('span');
        if (this.anchor) {
          this.anchor.nativeElement.appendChild(this.locationOverrideAnchor);
        } else {
          this.menuOwner.nativeElement.appendChild(this.locationOverrideAnchor);
        }
        this.locationOverrideAnchor.style.position = 'absolute';
        this.overlayContainer.anker = this.locationOverrideAnchor;
        void this.overlayContainer._handleAttach();
      } else {
        this.overlayContainer.anker = this.menuOwner;
      }
    }
  }
 
  private cleanupLocationOverrideAnchor() {
    if (this.locationOverrideAnchor?.parentNode) {
      this.locationOverrideAnchor.parentNode.removeChild(
        this.locationOverrideAnchor,
      );
      this.locationOverrideAnchor = undefined;
    }
  }
 
  /**
   * @ignore
   */
  private initMenuOwner(): void {
    this.menuOwnerCleanupCallbacks.forEach(cleanup => cleanup());
    this.menuOwnerCleanupCallbacks = [];
    if (this.menuOwner) {
      const menuOwnerElement = this.menuOwner.nativeElement;
 
      if (this.parentReference === undefined) {
        this.menuOwnerCleanupCallbacks.push(
          subscribe(
            menuOwnerElement,
            this.mouseEventType,
            this._handleOwnerAction.bind(this),
          ),
          subscribe(menuOwnerElement, 'blur', this._handleOwnerBlur.bind(this)),
          subscribe(
            menuOwnerElement,
            'keydown',
            this._handleOwnerKeyDown.bind(this),
          ),
        );
      } else {
        // We don't directly open the submenu when entering the control but only
        // if the user moves the mouse inside at least once because if the user
        // opens the menu via keyboard and the mouse pointer accidently is above
        // a menu item with a submenu we'd immediately trigger the opening
        let mouseMoveSubscription: Callback | undefined = undefined;
        this.menuOwnerCleanupCallbacks.push(
          subscribe(menuOwnerElement, 'mouseover', () => {
            mouseMoveSubscription = subscribe(
              menuOwnerElement,
              'mousemove',
              () => {
                void this._handleOwnerHover();
              },
              { once: true },
            );
          }),
        );
        // Make sure we never leave the listener installed even if no mouse move
        // is triggered after the mouseover
        this.menuOwnerCleanupCallbacks.push(
          subscribe(menuOwnerElement, 'mouseout', () => {
            if (mouseMoveSubscription) {
              mouseMoveSubscription();
            }
          }),
        );
      }
 
      if (this.mouseEventType !== 'contextmenu') {
        menuOwnerElement.setAttribute(ARIA_HASPOPUP, 'menu');
        this.menuOwnerCleanupCallbacks.push(() => {
          menuOwnerElement.removeAttribute(ARIA_HASPOPUP);
          menuOwnerElement.removeAttribute(ARIA_CONTROLS);
          menuOwnerElement.removeAttribute(ARIA_EXPANDED);
        });
      }
 
      this.updateMenuOwnerId();
      this.updateMenuOwnerAriaAttributes();
    }
  }
 
  /**
   * @ignore
   */
  private initPositionOverride(): void {
    if (this.mouseEventType === 'contextmenu') {
      this.positionOverride = true;
    } else {
      this.positionOverride = false;
    }
  }
}