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

98.13% Statements 999/1018
96.38% Branches 213/221
96.66% Functions 58/60
98.13% Lines 999/1018

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 10191x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 975x 975x 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1039x 1039x 1039x 1039x 1039x 219x 820x 1039x 1x 1x 7875x 7875x 1x 1x 1x 1x 1x 78950x 78950x 78950x 1x 1x 7633x 7633x 7633x 798x 798x 6835x 6835x 6835x 7633x 7633x 7633x 7633x 7633x 1x 1x 1x 1x 1x 4356x 4356x 1x 1x 1x 1x 1x 229x 229x 229x 229x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 975x 975x 975x 975x 975x 1x 1x 1x 1x 1x 7758x 294x 7758x 7758x 7758x 1039x 7758x 7758x 7758x 7758x 6831x 6831x 930x 930x 930x 7758x 7758x 7758x 1039x 7758x 7758x 7758x 7758x 7756x 7733x 7658x 798x       7758x 7758x 7758x 1x 1x 1x 1x 1x 120x 120x 120x 1x 1x 1x 1x 1x 109x 91x 91x 109x 109x 1x 1x 1x 1x 1x 84x   84x 84x 15x 84x 84x 84x 84x 84x 15x 84x 84x 1x 1x 1x 1x 1x 18x 18x 1x 1x 1x 1x 1x 64x 64x 64x 64x 64x 27x 2x 2x 2x 3x 3x 3x 3x 6x       27x 22x     64x 64x 64x 64x 64x 64x 5x 5x 64x 64x 1x 1x 1x 1x 1x 61308x 61308x 1x 1x 1x 1x 1x 145x 145x 145x 145x 145x 145x 145x 145x 1x 1x 1x 1x 1x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 59x 59x 59x 59x 59x 59x 59x 59x 130x 1x 1x 1x 1x 1x 164x 164x 1x 1x 1x 1x 1x 42x 4x 4x 4x 4x 38x 38x 38x 38x 38x 42x 1x 1x 1x 1x 1x 83x 83x 83x 83x 83x 26x 22x 22x 22x 22x 22x 41x 1x 1x 1x 1x 1x 1x 1x 56x 19x 19x 19x 26x 7x 7x 7x 30x     57x 2x 2x 2x 2x 1x 1x 1x 1x 1x 8x 20x 3x 3x 3x 11x 11x 3x 3x 3x 82x 25x 25x 25x 83x 83x 83x 83x 83x 83x 83x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 331x 331x 1x 1x 1x 1x 1x 121521x 121521x 1x 1x 1x 1x 1x 118944x 118944x 1x 1x 1x 1x 1x 54744x 54744x 1x 1x 1x 4728x 4728x 1x 1x 1x 1x 1x 50934x 50934x 50934x 50934x 50934x 1x 1x 1x 1x 1x 17754x 17754x 17754x 17754x 1x 1x 1x 1x 1x 215159x 215159x 215159x 215159x 1x 1x 1x 1x 1x 59472x 59472x 59472x 2975x 59472x 59472x 1x 1x 1x 1x 1x 120x 120x 53x 120x 120x 120x 4x 120x 120x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 60x 60x 60x 60x 55x 55x 4x 4x 4x 56x 56x 56x 56x 56x 1x 1x 1x 1x 1x 55x 55x 55x 60x 60x 1x 1x 145x 145x 145x 145x 145x 145x 145x 145x 92x 92x 145x 145x 15x 145x 145x 145x 145x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x 3x 3x 3x 3x 12x 12x 12x 12x 12x 15x 15x 15x 15x 15x 15x 15x 1x 1x 1x 1x 1x 124x 106x 2x 104x 101x 3x 106x 124x 124x 124x 124x 124x 124x 124x 124x 2x 2x 124x 124x 124x 124x 15x 15x 15x 91x 91x 91x 91x 15x 15x 15x 15x 124x 124x 1x 1x 1x 1x 1x 110x 8x 8x 8x 110x 102x 102x 102x 110x 110x 110x 1x 1x 1x 1x 1x 61x 61x 17x 17x 17x 17x 17x 17x 17x 17x 61x 61x 61x 1x 1x 1x 1x 1x 146x 146x 146x 1x 1x 1x 1x 1x 104x 104x 104x 104x 104x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 19x 19x 19x   19x 19x 19x 19x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 7x 7x 1x 6x 6x 7x 7x 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 25x 25x 25x 25x 25x 1x 1x 1x 1x 1x 123x 123x 1x 1x 1x 1x 1x 14x 14x 1x 1x 1x 1x 1x 1113x 851x 851x 851x 94x 94x 757x 757x 757x 851x 851x 1113x 1x 1x 1x 1x 1x 884x 884x 884x 884x 144x 740x 740x 884x 884x 884x 1x 1x 1x 1x 1x 1039x 1039x 1039x 203x 203x 203x 203x 203x 836x 836x 1039x 1039x 1039x 1x 1x 1159x 61x 61x 61x 61x 1159x 1159x 1x 1x 1x 1x 1x 1039x 1039x 1039x 884x 884x 884x 804x 804x 804x 804x 804x 804x 804x 804x 804x 804x 804x 80x 80x 80x 80x 80x 80x 80x 80x 884x 884x 884x 884x 884x 681x 681x 99x 99x 99x 884x 884x 884x 884x 884x 884x 1039x 1x 1x 1x 1x 1x 294x 294x 294x 294x 294x 294x 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,
} 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]',
})
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'],
})
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>();
 
  /**
   * 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;
 
  /** @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) {
      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 _handleOwnerHover(): void {
    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) {
        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) {
      this.menuOwner?.nativeElement.focus();
    }
    const childSubmenu = this.submenuComponents?.find(el => el.menuOpen);
    if (childSubmenu) {
      childSubmenu.closePopupMenu(false);
    }
  }
 
  /**
   * @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.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 {
        this.submenuComponents
          ?.find(menu => menu.parentReference?.itemOwnerKey === itemKey)
          ?.openPopupMenu('first', true);
      }
    });
  }
 
  /**
   * @ignore
   */
  private moveFocusToIndex(index: number) {
    this._currentSelectedItemIndex = index;
    this.menuItemElements.get(index)?.nativeElement.focus();
  }
 
  /**
   * @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');
        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 {
        this.menuOwnerCleanupCallbacks.push(
          subscribe(
            menuOwnerElement,
            'mouseover',
            this._handleOwnerHover.bind(this),
          ),
        );
      }
 
      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;
    }
  }
}