All files / lib/list list.component.ts

92.99% Statements 797/857
87.05% Branches 121/139
85.96% Functions 49/57
92.99% Lines 797/857

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 8581x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 49x 49x 343x   343x 343x 49x 49x 49x 49x 49x 1x 1x 1x 1x 1x 371x 371x 371x       371x 371x 371x 1x 1x 168x 168x 1x 1x 1x 1x 1x 22x 22x 22x 1x 1x 50x 50x 1x 1x 1x 1x 1x 1x       1x 1x 52x 52x 52x 1x 1x 1x 4606x 4606x 4564x 37204x 37204x 37204x 37204x 37204x 37204x 4564x 4606x 4606x 1x 1x 1x 208x 24x 184x 184x 208x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 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 133x 133x 133x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 204x 141x 204x 204x 204x 135x 135x 204x 204x 204x 204x 154x 56x 56x 56x 56x 204x 204x 98x 98x 98x                   98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 21x 21x 21x 21x 21x 21x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 56x 56x 56x 56x 56x 56x 56x 56x 37x 19x 56x 56x 98x 98x 8x 8x 8x 8x   8x 8x 8x 8x   8x 8x 8x 8x 98x 98x 98x 1x 1x 98x 98x 98x 45x 45x 45x 45x 7x 45x 45x 45x 45x 45x 45x 98x 98x 98x 40x 33x 33x 40x 40x 98x 98x 98x 28327x 28327x 28327x 28327x 28327x 98x 98x 20266x 2700x 17566x 17566x 20266x 98x 98x 18466x 18466x 9505x 18466x 18466x 98x 98x 98x 55398x 55398x 98x 98x 98x 90x 90x 98x 98x 98x 180x 180x 98x 98x 98x 20196x 1x 1x 1x 1x     1x 1x 1x 36932x 36932x 1x 1x 1x 2584x 2584x 1x 1x 1x 2584x 2584x 1x 1x 1x 22073x 22073x 22073x 22073x 1x 1x 1x 3510x 3510x     3510x 3510x 1x 1x 1x 2584x 2584x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1320x 1320x 1x 1x 1x 1x 2500x 2500x 2500x 2500x 2500x 1x 1x 1x 37890x 37890x 37890x 37890x 1x 1x 1x 3385x 3385x 3385x 3385x 3385x 1x 1x 1x               1x 1x 1x 24x   24x 24x 1x 1x 1x                   1x 1x 1x     1x 1x 1x 119x 119x 119x 119x 119x 119x 119x 119x 119x 119x 1x 1x 1x 1x 1x 1x 126x 126x 844x 844x 844x 844x 3659x 844x 844x 844x 126x   126x 126x 1x 1x 1x 289x 42x 42x 42x 42x 42x 289x 1x 1x 1x 141x 14x 14x 14x 53x 53x 53x 53x 13x 40x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 53x 53x 53x 53x 90x 90x 90x 348x 348x 62x 90x 53x 14x 14x 14x 14x 14x 14x 127x 141x 141x 1x 1x 1x 37705x 37705x 1x 1x 1x 45x 40x 40x 18x 40x 40x 45x 45x 45x 10x 45x 10x 10x 10x 10x 5x 5x         10x 10x 35x 45x 45x 1x 1x 1x                       1x 1x 1x 56x 56x 1x 1x 1x 56x 56x 56x 56x 56x 56x 56x 56x 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 { Subscription } from 'rxjs';
 
import {
  IndexedItem,
  ItemStorage,
  observeElementOutsideAngular,
  observeElementSize,
  subscribeWindow,
} from '../utils/internal-utils';
import {
  BadgeColor,
  BadgeStatus,
  BadgeVariant,
  Callback,
  Consumer,
  Converter,
  FocusableElementOwner,
  Item,
  ItemGroup,
  ListItem,
  StructuredControlState,
  hasSublabel,
  hasSublabels,
} from '../utils/util.types';
import {
  createWidgetKeySet,
  isItem,
  isItemGroup,
  isObject,
  isWithBagde,
  isWithHighlight,
  itemTrack,
} from '../utils/utilities';
 
import { VirtualListBoxItemDirective } from '../internal/virtual-listbox-item.directive';
import { ListboxSelectEvent } from '../internal/virtual-listbox.directive';
import { VirtualListboxService } from '../internal/virtual-listbox.service';
 
export type SortDirection = 'asc' | 'desc';
 
/** A group of list items. */
export interface ListItemGroup<T> extends ItemGroup<T> {
  /**
   * Override the total number of entries within the group, if not set the current number of items is used.
   * Count may be different from the number of current items in case of pagination.
   */
  entryCount?: {
    /** Total number of items in this group. */
    totalEntryCount: number;
    /** Index of the first item in the current list within the complete group. */
    offset: number;
  };
}
 
/** Helper type for distinguishing empty list items */
interface EmptyListItem extends ListItem {
  isEmpty?: boolean;
}
 
/**
 * `gc-list` shows a list of elements similar to `<select>`
 */
@Component({
  selector: 'gc-list',
  templateUrl: './list.component.html',
  styleUrls: [
    '../utils/styles/reset-list.css',
    './list.component.css',
    '../utils/styles/patterns.css',
  ],
  providers: [VirtualListboxService],
  standalone: false,
})
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 = '';
 
  /**
   * 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;
 
  /** The items to display in the selection list */
  @Input()
  public items: readonly T[] | readonly ListItemGroup<T>[] = [];
 
  /**
   * 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 */
  @ViewChildren(VirtualListBoxItemDirective)
  private listBoxItems?: QueryList<VirtualListBoxItemDirective>;
 
  /** @ignore */
  @ViewChildren('focusableItem')
  private focusableItems?: QueryList<ElementRef<HTMLElement>>;
 
  /** @ignore */
  @ViewChild('focusTarget')
  private focusTarget?: ElementRef<HTMLElement>;
 
  /**
   * @ignore
   * is always a single element but we need to use QueryList to be able to subscribe to changes
   */
  @ViewChildren('listItemParent')
  private listItemParents?: QueryList<ElementRef<HTMLElement>>;
 
  /** 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) {
    if (itemAdapter) {
      const adapter = (item: ListItem | T): I => {
        if (isItem(item)) {
          return item as I;
        } else {
          return itemAdapter(item);
        }
      };
      this.storage.converter = adapter;
    }
  }
 
  /**
   * The value represents the selected value
   */
  @Input()
  public get value(): T | undefined {
    const v = this.storage.selected;
    if (v !== undefined && this.isEmptyListItem(v)) {
      console.error('empty item has been selected');
      return undefined;
    } else {
      return v;
    }
  }
 
  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 {
          const itemCount = this.isEmptyListItem(curr.item) ? 0 : 1;
          return prev + itemCount;
        }
      }, 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 | EmptyListItem, I>;
 
  /** @ignore */
  public readonly widgetKeys = createWidgetKeySet('gc-list');
 
  /** @ignore */
  public _expandedItems: Set<string> = new Set();
 
  /** @ignore */
  protected groupedItemsToRender: ListItemGroup<
    IndexedItem<T | EmptyListItem>
  >[] = [];
 
  /** @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 inputTimeout?: ReturnType<typeof setTimeout>;
 
  /** @ignore */
  private _value?: T;
 
  /** @ignore */
  private listMutationObserver?: Callback;
 
  /** @ignore */
  private listItemParentsSubscription?: Subscription;
 
  constructor(
    itDiff: IterableDiffers,
    el: ElementRef<HTMLElement>,
    private readonly zone: NgZone,
    private readonly vls: VirtualListboxService,
  ) {
    this.storage = new ItemStorage<T | EmptyListItem, 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();
    this.listMutationObserver?.();
    this.listItemParentsSubscription?.unsubscribe();

    if (this.inputTimeout) {
      clearTimeout(this.inputTimeout);
    }
  }
 
  /** @ignore */
  ngAfterViewInit(): void {
    if (this.listItemParents) {
      this.updateVirtualListboxItems();
      this.updateListMutationObserver(
        this.listItemParents.first.nativeElement,
        this.updateVirtualListboxItems.bind(this),
      );
    }
 
    /**
     * Syncs the order of virtual listbox  with rendered state of items.
     * NgOnChanges happens before the QueryList elements are available so we cannot call *updateVirtualListboxItems* from there.
     */
    this.listItemParentsSubscription = this.listItemParents?.changes.subscribe(
      (c: QueryList<ElementRef<HTMLElement>>) => {
        this.updateVirtualListboxItems();
 
        this.updateListMutationObserver(
          c.first.nativeElement,
          this.updateVirtualListboxItems.bind(this),
        );
      },
    );
 
    setTimeout(() => {
      this.syncFocusIndexWithSelection();
    });
  }
 
  /** @ignore */
  onListKeypress() {
    const vFocusedListItem = this.listBoxItems?.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));
      }
      if (!this.isEmptyListItem(value)) {
        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 | BadgeColor {
    return isWithBagde(item.item) ? item.item.badge.color : '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(item: Item | ListItemGroup<IndexedItem<T, I>>): string {
    return itemTrack(item);
  }
 
  // type guard written as class member to allow using it within the template
  /** @ignore */
  protected _isItemGroup(
    items: readonly T[] | readonly ListItemGroup<T>[],
  ): items is readonly ListItemGroup<T>[] {
    const item = items[0];
    return item !== undefined ? isItemGroup(item) : false;
  }
 
  /** @ignore */
  protected _hasItems(
    item: ListItemGroup<IndexedItem<T, I>> | Item,
  ): item is ListItemGroup<IndexedItem<T, I>> {
    return isItemGroup(item);
  }
 
  /** @ignore */
  protected isEmpty(indexedItem: ListItemGroup<IndexedItem<T, I>>): boolean {
    const item = this.items.find(
      i => this.storage.convert(i).key === indexedItem.key,
    );
    return isItemGroup(item) && item.items.length === 0;
  }
 
  /** @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.listBoxItems?.find(c => c.focused)?.item;

    if (lastFocusedItem?.value) {
      this.onAction.emit({ data: lastFocusedItem.value as T, action });
    } else {
      console.error('missing value in lastFocusedItem', lastFocusedItem);
    }
  }
 
  /** @ignore */
  protected _onMenuClosedFocusCallback(): void {
    this.focusTarget?.nativeElement.focus();
  }
 
  /** @ignore */
  private updateListMutationObserver(el: HTMLElement, callback: Callback) {
    this.listMutationObserver?.();
    this.listMutationObserver = observeElementOutsideAngular(
      el,
      {
        childList: true,
      },
      this.zone,
      callback,
    );
  }
 
  /**
   * Needed because the @ViewChildren query doesn't guarantee the order of items as they are rendered.
   * @ignore
   */
  private updateVirtualListboxItems() {
    const sortedListboxItems = this.listBoxItems
      ? this.listBoxItems.toArray().sort((a, b) => {
          const indexA = this.storage.indexItems.findIndex(
            item => item.key === a.item.key,
          );
          const indexB = this.storage.indexItems.findIndex(item => {
            return item.key === b.item.key;
          });
 
          return indexA - indexB;
        })
      : [];
    this.vls.setItems(sortedListboxItems);
  }
 
  /** @ignore */
  private syncFocusIndexWithSelection() {
    if (this.value !== undefined) {
      const idx = this.storage.values.indexOf(this.value);
      if (idx >= 0) {
        this.vls.updateFocusedIndex(idx);
      }
    }
  }
 
  /** @ignore */
  private updateItems(): void {
    if (this._isItemGroup(this.items)) {
      // inserts placeholder item in empty groups for indexing
      const itemsWithEmptyItem: ListItemGroup<EmptyListItem | T>[] =
        this.items.map(i => {
          return {
            ...i,
            items:
              i.items.length === 0
                ? [{ key: i.key + '-empty', label: '', isEmpty: true }]
                : i.items,
          };
        });
 
      // indexes only child items (including placeholder items for empty groups) into storage
      const childrenOnly = itemsWithEmptyItem.map(i => i.items).flat();
      this.storage.values = childrenOnly;
 
      // creates an array of item groups that contain indexed items (including the placholder item for emtpy groups)
      const itemGroupsWithIndexedEmptyItem: ListItemGroup<
        IndexedItem<EmptyListItem | T, I>
      >[] = itemsWithEmptyItem.map(i => {
        return {
          ...i,
          items: i.items.map(
            child =>
              // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- item will certainly exist as it is inserted into the storage in the previous step
              this.storage.indexItems.find(
                indexedItem =>
                  indexedItem.key ===
                  (this.isEmptyListItem(child)
                    ? child.key
                    : this.storage.getItemByValue(child)?.key),
              )!,
          ),
        };
      });
 
      this.groupedItemsToRender = itemGroupsWithIndexedEmptyItem;
    } else {
      this.storage.values = this.items;
    }
  }
 
  /** @ignore */
  private isEmptyListItem(item: EmptyListItem | T): item is EmptyListItem {
    return isObject(item) && 'isEmpty' in item;
  }
 
  /** @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));
  }
 
  /** @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;
    }
  }
}