All files / lib/list list.component.ts

91.04% Statements 946/1039
89.65% Branches 156/174
88.57% Functions 62/70
91.04% Lines 946/1039

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 10401x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15620x 15620x 15620x 1x 1x 134x 134x 1x 1x 1x       1x 1x 49x 49x 1x 1x 1x 1x 1x 244x 244x 244x 1x 1x 160x 160x 1x 1x 1x 1x 1x 27x 27x 27x 1x 1x 50x 50x 1x 1x 1x 1x 1x 1x       1x 1x 51x 51x 51x 1x 1x 1x 4446x 4446x 4446x 35368x 1304x 34064x 34064x 4446x 4446x 4446x 4446x 1x 1x 1x 192x 18x 174x 174x 192x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 98x 98x 98x 98x 98x 98x 146x 146x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 1x 1x 1x 191x 134x 191x 191x 191x 131x 131x 191x 191x 191x 191x 141x 54x 54x 54x 191x 191x 191x 1x 1x 1x               1x 1x 1x 98x 98x 98x 98x 1x 1x 1x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 31x 8x 39x 39x 1x 1x 2x 2x 1x 1x 1x 2x 2x 2x 2x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 39x 39x 39x 39x 5x 39x 39x 39x 39x 1x 1x 1x 34x 29x 29x 34x 34x 1x 1x 1x 27572x 27572x 27572x 27572x 27572x 1x 1x 27572x 2700x 24872x 24872x 27572x 1x 1x 17928x 17928x 9184x 17928x 17928x 1x 1x 1x 53784x 53784x 1x 1x 1x 90x 90x 1x 1x 1x 180x 180x 1x 1x 1x 18712x 1x 1x 1x 1x 1225x 1225x 1x 1x 1x 53784x 53784x 1x 1x 1x 2424x 2424x 1x 1x 1x 2424x 2424x 1x 1x 1x 22171x 22171x 1x 1x 1x 3290x 3290x 3290x 3290x 3290x 3290x 1x 1x 1x 2424x 2424x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16189x 16189x 1x 1x 1x 10x 8x 2x 2x 10x 10x 1x 1x 1x 29x 29x 29x 29x 29x 29x 29x 4x 4x 4x 4x 8x 2x 2x 2x 15x 3x 3x 3x 3x 3x 3x 3x 16x 4x 4x 4x 8x       18x 2x 2x 2x     19x 1x 1x 29x 10x 29x 29x 29x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 3x 3x 3x 3x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                 4x 2x 2x 2x 2x 3x         13x 13x 9x 9x 14x 14x 1x 1x 1x 1x 6723x 6723x 6723x 6723x 6723x 1x 1x 1x 36060x 36060x 36060x 36060x 1x 1x 1x 1x 44x 44x 1x 1x 1x 1711x 1711x 627x 627x 1654x 1654x 1654x 1654x 1711x 1x 1x 1x               1x 1x 1x 19x   19x 19x 1x 1x 1x                                         1x 1x 1x     1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 135x 135x 1x 1x 1x 19x 19x 19x 19x 19x 16x 19x 19x 19x 19x 9x 19x 19x 1x 1x 1x 283x 32x 32x 32x 32x 32x 32x 283x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 36x 36x 36x 36x 14x 36x 9x 9x 9x 9x 4x 4x 4x 4x 5x 5x 9x 9x 9x 9x 36x 36x 36x 36x 36x   36x 36x 36x 36x 9x 9x 9x 9x 9x 1x 1x 1x 10x 10x 10x 10x 19x 10x 10x 1x 1x 1x 134x 134x 134x 134x 134x       134x 134x 134x 134x 1x 1x 1x 39x 34x 34x 34x 39x 39x 39x 39x 39x 10x 39x 10x 10x 10x 10x 5x 5x         10x 10x 29x 39x 39x 1x 1x 1x                       1x 1x 1x 39x 39x 39x 1x 1x 1x             1x 1x 1x 39x 39x 39x 39x 39x 39x 39x 39x 1x  
/*******************************************************************************
 * Copyright bei
 * Entwicklungs- und Pflegeverbund für das gemeinsame Fachverfahren gefa
 *
 *******************************************************************************/
import {
  AfterViewInit,
  Component,
  ElementRef,
  EventEmitter,
  HostBinding,
  Input,
  IterableDiffers,
  NgZone,
  OnChanges,
  OnDestroy,
  Output,
  QueryList,
  SimpleChanges,
  TemplateRef,
  ViewChild,
  ViewChildren,
} from '@angular/core';
 
import {
  IndexedItem,
  ItemStorage,
  observeElementSize,
  subscribeWindow,
} from '../utils/internal-utils';
import {
  BadgeStatus,
  BadgeVariant,
  Callback,
  Consumer,
  Converter,
  FocusableElementOwner,
  Item,
  ItemGroup,
  Key,
  ListItem,
  StructuredControlState,
  hasSublabel,
  hasSublabels,
} from '../utils/util.types';
import {
  createWidgetKeySet,
  isItemGroup,
  isWithBagde,
  isWithHighlight,
  itemTrack,
} from '../utils/utilities';
 
import {
  ListboxSelectEvent,
  VirtualListBoxDirective,
} from '../internal/virtual-listbox.directive';
 
export type SortDirection = 'asc' | 'desc';
 
/**
 * `gc-list` shows a list of elements similar to `<select>`
 */
@Component({
  selector: 'gc-list',
  templateUrl: './list.component.html',
  styleUrls: [
    '../utils/styles/reset-list.css',
    '../utils/styles/patterns.css',
    './list.component.css',
  ],
})
export class ListComponent<T, I extends ListItem = ListItem>
  implements OnDestroy, AfterViewInit, OnChanges, FocusableElementOwner
{
  /** If set to true it disables selection of items */
  @Input()
  public disabled = false;
 
  /** Pager template slot*/
  @Input()
  public pagerTemplate: TemplateRef<unknown> | null = null;
 
  /** Used to display a confirmation-banner on top of the list. */
  @Input()
  public confirmationBannerTemplate: TemplateRef<unknown> | null = null;
 
  /** Inform about the change of the selection state */
  @Output()
  public readonly valueChange: EventEmitter<T | undefined> = new EventEmitter<
    T | undefined
  >();
 
  /** Optional icon provider to use for the selected entry */
  @Input()
  public iconProvider?: TemplateRef<unknown>;
 
  /** Decides the size which the icons will be rendered in. */
  @Input()
  public iconSize: 'large' | 'small' = 'large';
 
  /** label to associate with the control */
  @Input()
  public label = '';
 
  /**
   * show the entry count
   * @deprecated - property no longer needs to be an input and will be removed in future as such. (will remain a static property)
   */
  @Input()
  public showEntryCount = true;
 
  /**
   * Override the total number of entries, if not set the current number of items is used.
   * Count may be different from the number of current items in case of pagination.
   */
  @Input()
  public totalEntryCount?: number;
 
  /**
   * items displayed to sort elements inside the list
   */
  @Input()
  public sortItems: readonly Item[] = [];
 
  /**
   * Inform about changes to the sort type
   */
  @Output()
  public readonly activeSortItemChange: EventEmitter<Item | undefined> =
    new EventEmitter<Item | undefined>();
 
  /**
   * the sort direction
   */
  @Input()
  public sortDirection: SortDirection = 'asc';
 
  /**
   * Set to true if there is no data available at all
   * @deprecated - use new *state* input instead to achieve desired state.
   */
  @Input()
  public isNoData = false;
 
  /** Text to highlight in the items */
  @Input()
  public highlightString = '';
 
  /**
   * Enables setting of the value only when the Promise resolves with value "true".
   */
  @Input()
  public permitValueChange?: (v: T) => Promise<boolean> | boolean;
 
  /**
   * Icon provider for badge
   */
  @Input()
  public badgeIconProvider?: TemplateRef<unknown>;
 
  /**
   * Changes the state of the list.
   * Possible optional states are:
   * - loading: indicates that the list is in a loading state.
   * - search: indicates that the list is in an ongoing search context/state.
   */
  @Input()
  public state: StructuredControlState = {
    loading: false,
    search: false,
  };
 
  /**
   * Inform about the change to the sort direction
   */
  @Output()
  public readonly sortDirectionChange: EventEmitter<SortDirection> =
    new EventEmitter<SortDirection>();
 
  /**
   * Event emitted when an open gesture is detected on the item (eg pressing return)
   */
  @Output()
  readonly onOpenItem: EventEmitter<T> = new EventEmitter<T>();
 
  /**
   * Fires upon selection of an action of a list item.
   */
  @Output()
  public readonly onAction: EventEmitter<{
    data: T;
    action: NonNullable<I['actions']>[number];
  }> = new EventEmitter<{
    data: T;
    action: NonNullable<I['actions']>[number];
  }>();
 
  /** @ignore */
  @HostBinding('class.gc-list-small')
  protected _smallList = false;
 
  /** @ignore */
  @HostBinding('class.gc-list-xsmall')
  protected _xSmallList = false;
 
  /** @ignore */
  @HostBinding('class.gc-list-with-sticky-header')
  protected _stickyHeader = true;
 
  /** @ignore */
  @ViewChild(VirtualListBoxDirective)
  private listBoxDirective?: VirtualListBoxDirective;
 
  /** @ignore */
  @ViewChildren('treeItem')
  private treeItems?: QueryList<ElementRef<HTMLElement>>;
 
  /** @ignore */
  @ViewChildren('focusableItem')
  private focusableItems?: QueryList<ElementRef<HTMLElement>>;
 
  /** @ignore */
  @ViewChild('focusTarget')
  private focusTarget?: ElementRef<HTMLElement>;
 
  /** The items to display in the selection list */
  @Input()
  public get items(): readonly T[] {
    return this.storage.values;
  }
 
  public set items(items: readonly T[]) {
    this._items = items;
  }
 
  /** Adapts the domain type T to the internal Item structure */
  @Input()
  public get itemAdapter(): Converter<T, I> | undefined {
    return this.storage.converter;
  }
 
  public set itemAdapter(itemAdapter: Converter<T, I> | undefined) {
    this.storage.converter = itemAdapter;
  }
 
  /**
   * The value represents the selected value
   */
  @Input()
  public get value(): T | undefined {
    return this.storage.selected;
  }
 
  public set value(value: T | undefined) {
    this._value = value;
  }
 
  /**
   * The active sort item
   */
  @Input()
  public get activeSortItem(): Item | undefined {
    return this._activeSortItem;
  }
 
  public set activeSortItem(item: Item | undefined) {
    this._activeSortItem = item;
  }
 
  /**
   * Set to true if the data is currently loading.
   * @deprecated - use new *state* input instead.
   */
  @Input()
  public get isLoading(): boolean {
    return this._isLoading;
  }
 
  public set isLoading(value: boolean) {
    this._isLoading = value;
    this.state = { ...this.state, loading: value ? 'default' : false };
  }
 
  /** @ignore */
  public get _totalEntryCount(): number {
    return (
      this.totalEntryCount ??
      this.storage.indexItems.reduce((prev, curr) => {
        if (this._hasItems(curr.item)) {
          return prev + curr.item.items.length;
        } else {
          return prev + 1;
        }
      }, 0)
    );
  }
 
  /** @ignore */
  protected get emptyListText(): string {
    if (this.state.search) {
      return 'Kein Treffer für diese Such- und Filterkriterien gefunden.';
    }
    return 'Keine Einträge vorhanden';
  }
 
  /** @ignore */
  public readonly storage: ItemStorage<T, I>;
 
  /** @ignore */
  public readonly widgetKeys = createWidgetKeySet('gc-list');
 
  /** @ignore */
  public _expandedItems: Set<string> = new Set();
 
  /** @ignore */
  protected _lastFocusedItemKey?: Key;
 
  /** @ignore */
  protected readonly _defaultActions = [
    {
      key: this.widgetKeys.widgetKey + '-list-default',
      label: 'Keine Aktion verfügbar',
    },
  ];
 
  /** @ignore */
  protected readonly _disabledActionKeySet = new Set([
    this._defaultActions[0].key,
  ]);
 
  /** @ignore */
  protected _contextMenuItems: readonly Item[] = this._defaultActions;
 
  /** @ignore */
  protected _contextMenuOwner?: ElementRef<HTMLElement>;
 
  /** @ignore */
  protected _contextMenuLabelledBy?: string;
 
  /** @ignore */
  protected _contextMenuOffset = 0;
 
  /** @ignore */
  protected _menuAnchor?: ElementRef<HTMLElement>;
 
  /** @ignore */
  protected LIST_IS_LOADING_MESSAGE = 'Liste wird geladen';
 
  /** @ignore */
  protected SEARCH_IS_LOADING_MESSAGE = 'Ergebnisse werden geladen';
 
  /** @ignore */
  private _activeSortItem?: Item;
 
  /** @ignore */
  private _resizeObserver: Callback;
 
  /** @ignore */
  private _windowResizeObserver: Callback;
 
  /** @ignore */
  private _isLoading = false;
 
  /** @ignore */
  private textInput = '';
 
  /** @ignore */
  private inputTimeout?: ReturnType<typeof setTimeout>;
 
  /** @ignore */
  private _items: readonly T[] = [];
 
  /** @ignore */
  private _value?: T;
 
  constructor(
    itDiff: IterableDiffers,
    el: ElementRef<HTMLElement>,
    zone: NgZone,
  ) {
    this.storage = new ItemStorage<T, I>(itDiff);
    const resizeHandler: Consumer<ResizeObserverEntry> = entry => {
      this._smallList = entry.contentRect.width < 400;
      this._xSmallList = entry.contentRect.width < 320;
    };
    this._resizeObserver = observeElementSize(
      el.nativeElement,
      zone,
      resizeHandler.bind(this),
    );
 
    const windowResizeHandler = () => {
      this._stickyHeader = window.innerHeight >= 400;
    };
    this._windowResizeObserver = subscribeWindow('resize', windowResizeHandler);
    windowResizeHandler(); // invoke immediately to set initial values before first resize occurs
  }
 
  /** @ignore */
  ngOnChanges(changes: SimpleChanges): void {
    if ('items' in changes || 'itemAdapter' in changes) {
      this.updateItems();
    }
 
    if ('value' in changes || 'itemAdapter' in changes) {
      this.storage.selected = this._value;
      this.syncFocusIndexWithSelection();
    }
 
    if (
      ('isLoading' in changes && !changes.isLoading.currentValue) ||
      'state' in changes
    ) {
      setTimeout(() => {
        this.syncFocusIndexWithSelection();
      });
    }
  }
 
  /** @ignore */
  ngOnDestroy(): void {
    this._resizeObserver();
    this._windowResizeObserver();

    if (this.inputTimeout) {
      clearTimeout(this.inputTimeout);
    }
  }
 
  /** @ignore */
  ngAfterViewInit(): void {
    setTimeout(() => {
      this.syncFocusIndexWithSelection();
    });
  }
 
  /** @ignore */
  onListKeypress() {
    const vFocusedListItem = this.listBoxDirective?.children?.find(
      c => c.focused,
    );
    const item: ListItem | undefined = vFocusedListItem?.item.item;
    this._contextMenuOwner = this.focusTarget;
 
    if (item) {
      this.determineMenuAnchor(item);
      this._contextMenuItems =
        item.actions && item.actions.length > 0
          ? item.actions
          : this._defaultActions;
    }
  }
 
  focusChild(): boolean {
    if (this.focusTarget) {
      this.focusTarget.nativeElement.focus();
      return true;
    } else {
      const target = this.focusableItems?.find(
        item => item.nativeElement.tabIndex != -1,
      );
      if (target) {
        target.nativeElement.focus();
        return true;
      }
    }
    return false;
  }
 
  /** @ignore */
  protected _impl_onSortItemChange(item: Item | null) {
    this.activeSortItemChange.emit(item ?? undefined);
  }
 
  /** @ignore */
  protected async _impl_onSelect(item: ListboxSelectEvent): Promise<void> {
    const value = this.storage.getValueByKey(item.key);
    if (value !== undefined) {
      // wait one tick in case of an item group in order to sync with render
      if (this._isItemGroup(this.items)) {
        await new Promise(res => setTimeout(res));
      }
      await this.resolveSelection(value, item);
    }
  }
 
  /** @ignore */
  protected _impl_handleChange(value: T): void {
    if (this.value !== value) {
      this.value = value;
      this.valueChange.emit(value);
    }
  }
 
  /** @ignore */
  protected _getSubLabel(item: IndexedItem<T, I>): string | undefined {
    if (hasSublabel(item.item)) {
      return item.item.sublabel;
    }
    return undefined;
  }
 
  protected getSubLabels(item: IndexedItem<T, I>): readonly string[] {
    if (hasSublabels(item.item)) {
      return item.item.sublabels;
    }
    return [];
  }
 
  protected hasSublabelArea(item: IndexedItem<T, I>): boolean {
    return (
      hasSublabel(item.item) ||
      (hasSublabels(item.item) && item.item.sublabels.length > 0)
    );
  }
 
  /** @ignore */
  protected _hasHighlight(item: IndexedItem<T, I>): boolean {
    return isWithHighlight(item.item);
  }
 
  /** @ignore */
  protected _itemHighlightColor(item: IndexedItem<T, I>): string {
    return isWithHighlight(item.item) ? item.item.highlight.color : '';
  }
 
  /** @ignore */
  protected _itemHighlightVariant(item: IndexedItem<T, I>): string {
    return isWithHighlight(item.item) ? item.item.highlight.variant : '';
  }
  // Force binding to the component
  /** @ignore */
  protected getItemId = (item: Item): string => {
    return this.widgetKeys.baseKey + '-item-' + item.key;
  };
 
  /** @ignore */
  protected getItemGroupId(item: Item): string {
    return this.widgetKeys.baseKey + '-group-' + item.key;
  }
 
  /** @ignore */
  protected _hasBadge(item: IndexedItem<T, I>): boolean {
    return isWithBagde(item.item);
  }
 
  /** @ignore */
  protected _itemBadgeLabel(item: IndexedItem<T, I>): string {
    return isWithBagde(item.item) ? item.item.badge.label : 'H';
  }
 
  /** @ignore */
  protected _itemBadgeVariant(item: IndexedItem<T, I>): BadgeVariant {
    return isWithBagde(item.item) ? item.item.badge.variant : 'primary';
  }
 
  /** @ignore */
  protected _itemBadgeStatus(item: IndexedItem<T, I>): BadgeStatus {
    return isWithBagde(item.item) ? item.item.badge.status : 'basic';
  }
 
  /** @ignore */
  protected _itemBadgeShowIcon(item: IndexedItem<T, I>): boolean {
    if (isWithBagde(item.item)) {
      return item.item.badge.showIcon ?? false;
    } else {
      return false;
    }
  }
 
  /** @ignore */
  protected _itemBadgeKey(item: IndexedItem<T, I>): string {
    return 'badge-' + item.item.key;
  }
 
  /** @ignore */
  protected _flipDirection() {
    this.sortDirection = this.sortDirection === 'desc' ? 'asc' : 'desc';
    this.sortDirectionChange.emit(this.sortDirection);
  }
 
  /** @ignore */
  protected _trackBy(index: number, item: Item): string {
    return itemTrack(item);
  }
 
  /** @ignore */
  protected _onExpandClick(headerKey: Key): void {
    if (this._expandedItems.has(headerKey)) {
      this._expandedItems.delete(headerKey);
    } else {
      this._expandedItems.add(headerKey);
    }
  }
 
  /** @ignore */
  protected _onHeaderKeydown(
    event: KeyboardEvent,
    headerElement: HTMLElement,
    headerItem: IndexedItem<T, I>,
  ): void {
    const key = event.key;
    switch (key) {
      case 'Enter':
      case ' ':
        this._onExpandClick(headerItem.key);
        event.preventDefault();
        break;
      case 'ArrowRight':
        this.handleHeaderArrowRight(headerItem);
        event.preventDefault();
        break;
      case 'ArrowLeft':
        this.handleHeaderArrowLeft(headerItem.key);
        event.preventDefault();
        break;
      case 'ArrowUp':
        this.focusPrevious(headerElement);
        event.preventDefault();
        break;
      case 'ArrowDown':
        this.focusNext(headerElement);
        event.preventDefault();
        break;
      case 'Home':
        this.focusableItems?.first.nativeElement.focus();
        event.preventDefault();
        break;
      case 'End':
        this.handleEndButtonPress();
        break;
      case 'Shift':
        // ignore key for proper text input
        break;
      case '*':
        this.expandAll();
        break;
      default:
        this.handleInputFromElement(key, headerItem.key);
        break;
    }
  }
 
  /** @ignore */
  protected handleHeaderArrowRight(headerItem: IndexedItem<T, I>): void {
    const headerKey = headerItem.key;
    if (this._expandedItems.has(headerKey)) {
      const groupElement = document.getElementById(
        this.getItemGroupId(headerItem),
      );
      // child item may be the special "empty" item without an ID, thus query first treeitem from DOM
      groupElement?.querySelector<HTMLElement>('[role="treeitem"]')?.focus();
    } else {
      this._expandedItems.add(headerKey);
    }
  }
 
  /** @ignore */
  protected handleHeaderArrowLeft(itemKey: Key): void {
    if (this._expandedItems.has(itemKey)) {
      this._expandedItems.delete(itemKey);
    }
  }
 
  /** @ignore */
  protected focusPrevious(element: HTMLElement): void {
    const currIdx = this.focusableItems
      ?.toArray()
      .findIndex(el => el.nativeElement === element);
 
    if (currIdx !== undefined) {
      this.focusableItems?.get(currIdx - 1)?.nativeElement.focus();
    }
  }
 
  /** @ignore */
  protected focusNext(element: HTMLElement): void {
    const currIdx = this.focusableItems
      ?.toArray()
      .findIndex(el => el.nativeElement === element);
 
    if (currIdx !== undefined) {
      this.focusableItems?.get(currIdx + 1)?.nativeElement.focus();
    }
  }
 
  /**
   * Keyboard event handler for grouped list (non-Virtual List)
   * @ignore
   */
  protected async _onGroupedListItemKeydown(
    event: KeyboardEvent,
    headerElement: HTMLElement,
    headerKey: Key,
    listItem: HTMLLIElement,
    itemKey?: Key,
  ): Promise<void> {
    const key = event.key;
    switch (key) {
      case 'ArrowLeft':
        headerElement.focus();
        event.preventDefault();
        event.stopPropagation();
        break;
      case 'ArrowUp':
        this.focusPrevious(listItem);
        event.preventDefault();
        event.stopPropagation();
        break;
      case 'Home':
        this.focusableItems?.first.nativeElement.focus();
        event.preventDefault();
        break;
      case 'End':
        this.handleEndButtonPress();
        event.preventDefault();
        break;
      case 'Enter':
        if (itemKey) {
          await this._impl_onSelect({ key: itemKey, open: true });
        }
        event.stopPropagation();
        break;
      case ' ':
        listItem.click();
        event.stopPropagation();
        break;
      case 'Shift':
        // ignore key for proper text input
        break;
      case 'ArrowDown':
        this.focusNext(listItem);
        event.preventDefault();
        event.stopPropagation();
        break;
      case 'ContextMenu':
        if (itemKey) {
          this.handleContextMenuPress(itemKey);
        }
        break;
 
      default:
        this.handleInputFromElement(key, headerKey, itemKey);
        event.stopPropagation();
    }
  }
 
  // type guard written as class member to allow using it within the template
  /** @ignore */
  protected _isItemGroup(
    items: readonly T[] | readonly ItemGroup<T>[],
  ): items is readonly ItemGroup<T>[] {
    const item = items[0];
    return item !== undefined ? isItemGroup(item) : false;
  }
 
  /** @ignore */
  protected _hasItems(
    item: ItemGroup<IndexedItem<T, I>> | Item,
  ): item is ItemGroup<IndexedItem<T, I>> {
    return isItemGroup(item);
  }
 
  // used only in case of ItemGroup
  /** @ignore */
  protected onListItemFocus(key: Key): void {
    this._lastFocusedItemKey = key;
  }
 
  /** @ignore */
  protected isKeyboardFocusOwner(key: Key) {
    if (
      this._lastFocusedItemKey === undefined &&
      (this.storage.selectedItem?.key === key ||
        this.storage.indexItems[0]?.key === key)
    ) {
      return true;
    }
    return this._lastFocusedItemKey === key;
  }
 
  /** @ignore */
  protected _onMenuAction(listItem: IndexedItem<T, I>, action: Item) {
    const value = listItem.value;
    if (value !== undefined) {
      this.onAction.emit({ data: value, action });
    } else {
      console.error('failed to lookup list data for item', listItem);
    }
  }
 
  /** @ignore */
  protected _onPointerDown(event: MouseEvent, item: IndexedItem<T, I>): void {
    if (event.button === 2) {
      this.determineContextMenuOwner(item.item);
    }
  }
 
  /** @ignore */
  protected _onContextMenuAction(action: Item): void {
    const lastFocusedItem: IndexedItem<unknown> | undefined =
      this.listBoxDirective?.children?.find(c => c.focused)?.item;
    const lastFocusedItemValueInGroup = this.storage.getValueByKey(
      this._lastFocusedItemKey,
    );
    if (lastFocusedItem) {
      if (lastFocusedItem.value) {
        this.onAction.emit({ data: lastFocusedItem.value as T, action });
      } else {
        console.error('missing value in lastFocusedItem', lastFocusedItem);
      }
    } else if (lastFocusedItemValueInGroup) {
      this.onAction.emit({ data: lastFocusedItemValueInGroup, action });
    } else {
      console.error(
        'missing value in lastFocusedItemValueInGroup',
        this.storage.getItemByKey(this._lastFocusedItemKey),
      );
    }
  }
 
  /** @ignore */
  protected _onMenuClosedFocusCallback(): void {
    this.focusTarget?.nativeElement.focus();
  }
 
  /** @ignore */
  private handleEndButtonPress() {
    const lastItemKey =
      this.storage.indexItems[this.storage.indexItems.length - 1].key;
 
    if (this.treeItems && this._expandedItems.has(lastItemKey)) {
      this.treeItems.last.nativeElement.focus();
    } else {
      this.focusableItems?.last.nativeElement.focus();
    }
  }
 
  /** @ignore */
  private expandAll(): void {
    this.storage.indexItems.forEach(i => this._expandedItems.add(i.key));
  }
 
  /** @ignore */
  private handleInputFromElement(
    input: string,
    startHeaderKey: Key,
    startListItemKey?: Key,
  ): void {
    if (this.inputTimeout) {
      clearTimeout(this.inputTimeout);
    }
 
    this.textInput = this.textInput.concat(input);
    this.inputTimeout = setTimeout(() => {
      this.focusListItemByString(startHeaderKey, startListItemKey);
    }, 1000);
  }
 
  /** @ignore */
  private syncFocusIndexWithSelection() {
    if (this.listBoxDirective && this.value !== undefined) {
      const idx = this.storage.values.indexOf(this.value);
      const listBoxDirective = this.listBoxDirective;
      if (idx >= 0) {
        listBoxDirective.updateFocusedIndex(idx);
      }
    }
  }
 
  /** @ignore */
  private focusListItemByString(
    startHeaderKey: Key,
    startListItemKey?: Key,
  ): void {
    const { items, startSearchAt } = this.determineSearchableGroupedListItems(
      startHeaderKey,
      startListItemKey,
    );
 
    if (startSearchAt !== undefined) {
      const foundItem =
        this.findListItemByInputFromIdx(items, startSearchAt) ??
        this.findListItemByInputFromIdx(items, 0);
 
      if (foundItem) {
        document.getElementById(this.getItemId(foundItem))?.focus();
      }
    }
 
    this.textInput = '';
  }
 
  /**
   * collect currently visible list items (without group headers),
   * and map the specified starting header/item key to an index within the returned array
   * @ignore
   */
  private determineSearchableGroupedListItems(
    startHeaderKey: Key,
    startListItemKey?: Key,
  ) {
    interface Collector {
      items: IndexedItem<T, I>[];
      startSearchAt?: number;
    }
    return this.storage.indexItems.reduce<Collector>(
      (collected, groupIndexedItem) => {
        let startIndex = collected.startSearchAt;
 
        if (
          collected.startSearchAt === undefined &&
          startHeaderKey === groupIndexedItem.key
        ) {
          // if the currently processed item is the start category, (optionally) calculate the offset for the list item
          // within the group if it's visible
          const listItemOffset =
            startListItemKey !== undefined &&
            this._expandedItems.has(groupIndexedItem.key) &&
            this._hasItems(groupIndexedItem.item)
              ? groupIndexedItem.item.items.findIndex(
                  i => i.key === startListItemKey,
                )
              : -1;
          startIndex =
            collected.items.length +
            (listItemOffset >= 0 ? listItemOffset + 1 : 0);
        }
 
        const addItems =
          this._expandedItems.has(groupIndexedItem.key) &&
          this._hasItems(groupIndexedItem.item)
            ? groupIndexedItem.item.items
            : [];
 
        return {
          items: collected.items.concat(addItems),
          startSearchAt: startIndex,
        };
      },
      { items: [], startSearchAt: undefined },
    );
  }
 
  /** @ignore */
  private findListItemByInputFromIdx(
    items: Item[],
    startIndex: number,
  ): Item | undefined {
    return items.slice(startIndex, undefined).find(i => {
      return i.label.toLowerCase().includes(this.textInput.toLowerCase());
    });
  }
 
  /** @ignore */
  private updateItems(): void {
    this.storage.values = this._items;
 
    // reset the previously focused item if it's not in the list anymore
    if (
      this._lastFocusedItemKey !== undefined &&
      this.storage.getItemByKey(this._lastFocusedItemKey) === undefined
    ) {
      this._lastFocusedItemKey = undefined;
    }
 
    this.expandAll();
  }
 
  /** @ignore */
  private async resolveSelection(value: T, item: ListboxSelectEvent) {
    const doChange = () => {
      this._impl_handleChange(value);
      if (item.open) {
        this.onOpenItem.emit(value);
      }
    };
 
    if (
      this.permitValueChange !== undefined &&
      this.storage._selectedKey !== item.key
    ) {
      const permit = this.permitValueChange(value);
      if (typeof permit !== 'boolean') {
        // permit is of type Promise<boolean>
        const proceed = await permit;
        if (proceed) {
          doChange();
        }
      } else if (permit) {
        // permit is of type boolean
        doChange();
      }
    } else {
      doChange();
    }
  }
 
  /** @ignore */
  private determineContextMenuOwner(item: ListItem): void {
    this._contextMenuItems =
      item.actions && item.actions.length > 0
        ? item.actions
        : this._defaultActions;
    const liElement = this.getNativeElementForItem(item);

    this._contextMenuOwner = new ElementRef(liElement);
    this.determineMenuAnchor(item);

    this._contextMenuLabelledBy = item.key;
  }
 
  /** @ignore */
  private determineMenuAnchor(item: ListItem) {
    this._menuAnchor = new ElementRef(this.getNativeElementForItem(item));
    console.log(item);
  }
 
  /** @ignore */
  private handleContextMenuPress(itemKey: Key): void {
    const vListItem = this.storage.getItemByKey(itemKey);

    if (vListItem) {
      this.determineContextMenuOwner(vListItem);
    }
  }
 
  /** @ignore */
  private getNativeElementForItem(item: ListItem): HTMLElement {
    const element = document.getElementById(this.getItemId(item));
 
    if (!element) {
      throw new Error(`failed to find HTML element for item ${item.key}`);
    } else {
      return element;
    }
  }
}