All files / lib/combobox combobox.component.ts

95.81% Statements 1007/1051
94.52% Branches 207/219
92.85% Functions 65/70
95.81% Lines 1007/1051

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 10521x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 61x 61x 61x 1x 1x 1x 1x 1x 1x 70x 1x 1x 1x 16x 16x 27x 21x 21x 21x 16x 16x 16x 16x 16x 1x 1x 47x 47x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 124x 124x 124x 124x 124x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x             1x 1x 3533x 3533x 1x 1x 1x 1x 1x 3005x 3005x 3005x 1x 1x 57x 57x 56x 57x 57x 1x 1x 1x 63x 63x 63x 16x 47x 47x 63x 63x 1x 1x 1x 9578x 9578x 1x 1x 1x 3694x 3694x 1x 1x 1x 132x 8x 8x 132x 132x 1x 1x 1x 3730x 3730x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 70x 70x 1x 1x 1x 1x 114x 89x 25x 25x 114x 114x 1x 1x 1x 70x 70x 70x 1x 70x 70x 1x 1x 1x 141x 102x 102x 141x 141x 59x 141x 141x 1x 1x 5x 5x 5x   5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 126x 126x 126x 14x 14x 14x 126x 1x 1x 1x 1207x 1207x 1x 1x 1x     1x 1x 1x                 1x 1x 1x 489x 489x 489x 489x 489x 1x 1x 1x 4210x 4210x 4210x 4210x 535x 3675x 3675x 4210x 1x 1x 1x 25x 25x 25x 25x 25x 1x 1x 1x 25x 25x 1x 1x 1x 12969x 12969x 12969x 12969x 1x 1x 1x 4181x 3982x 3982x 3982x 4181x 4181x 4181x 1x 1x 1x 72x 72x 72x 72x 72x 72x 57x 72x 72x 72x 72x 1x 1x 1x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 17x 17x 17x 17x 17x 18x 1x 1x 1x 51x 51x 51x 51x 51x 1x 1x 1x 4181x 4181x 4181x 4181x 4181x 4181x 4181x 1x 1x 1x 1x 4231x 524x 3707x 3707x 3707x 4231x 1x 1x 1x 4181x 4181x 4181x 4181x 4181x 4181x 4181x 1x 1x 1x 8707x 7659x 7659x 7659x 7659x 8707x 8707x 8707x 8707x 8707x 1x 1x 1x     1x 1x 1x 19x 19x 1x 1x 1x 19x 18x 18x 18x 18x             18x 18x 18x 19x 19x 1x 1x 1x 12x 12x 1x 1x 1x 12x 12x 1x 1x 1x 2351x 2351x 1x 1x 1x 7759x 7759x 1x 1x 1x 18x 11x 18x 18x 18x 18x 18x 18x 18x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x     8x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 1x                   1x 1x 1x 10x 10x 1x 1x 1x 1x 1x 1x 1x 1x 1x 100x 100x 100x 100x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 100x 100x 100x 1x 1x 1x 24x 13x 13x 13x 13x 24x 24x 24x 24x 1x 1x 1x 21x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 21x 21x 1x 1x 1x 57x 45x 57x 57x 13x 13x 57x 57x 1x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x   16x 16x 16x 16x 1x 11x 11x 11x 11x 10x 10x 10x 10x 10x 3x 3x 7x 7x 7x 7x 7x 7x 7x 16x 16x 1x 1x 1x 31x 7x 3x 3x 3x 3x 3x 3x 24x 24x 24x 31x 31x 1x 1x 1x 115x 115x 115x 115x 115x 30x 115x 115x 1x 1x 1x 552x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 552x 536x 536x 536x 536x 536x 536x 536x 536x 536x 552x 1x 1x 1x 125x 125x 125x 125x 125x 125x 125x 86x 86x 38x 38x 38x 38x 38x 125x 125x 1x 1x 1x 114x 114x 114x 79x 35x 35x 114x 114x 1x 1x 1x 115x 1x 1x 115x 115x 115x 114x 114x 114x 115x 115x 1x 1x 1x 115x 115x 115x 114x 114x 114x 114x 114x 114x 114x 3x 115x 115x 115x 1x 1x 1x 126x 126x 126x 126x 126x 126x 126x 126x 1x 1x 1x 89x 89x 89x 89x 14x 9x 5x 5x 5x 14x 14x 14x 70x     77x 14x 6x 8x 8x 14x 14x 14x 33x       37x 1x 1x 1x 1x 89x 89x 89x 1x 1x 1x 25x   25x 25x 3x 3x 25x 25x 25x 1x 1x 1x 8x 8x 7x 7x 7x 7x 7x   8x 8x 8x 8x 8x 1x 1x 1x 132x 132x 132x 132x 132x 132x 14x 14x 14x 7x 7x 7x 14x 14x 14x 14x 118x 118x 118x 86x 118x 118x 118x 118x 118x 132x 132x 26x 132x 132x 132x 1x  
/*******************************************************************************
 * Copyright bei
 * Entwicklungs- und Pflegeverbund für das gemeinsame Fachverfahren gefa
 *
 *******************************************************************************/
import {
  AfterViewInit,
  Component,
  ContentChildren,
  Directive,
  ElementRef,
  EventEmitter,
  HostListener,
  Input,
  OnChanges,
  Optional,
  Output,
  QueryList,
  SimpleChanges,
  TemplateRef,
  ViewChild,
  ViewChildren,
} from '@angular/core';
 
import {
  IndexedItem,
  isOnlyAltPressedOrNothing,
} from '../utils/internal-utils';
import {
  Converter,
  FocusableElementOwner,
  FormControlStatus,
  InvalidControlValue,
  Item,
  Nullable,
  OptionalNullable,
  hasSublabel,
} from '../utils/util.types';
import {
  SoundType,
  isInvalidControlValue,
  isItem,
  playSound,
} from '../utils/utilities';
 
import { ElementInsertionContextService } from '../internal/element-insertion-context.service';
import {
  AutoIdDirective,
  LabelContainerComponent,
} from '../internal/label-container/label-container.component';
import { OverlayContainerComponent } from '../internal/overlay-container/overlay-container.component';
 
import { TextInputComponent } from '../text-input-field/text-input-field.component';
 
@Directive({
  selector: '[data-gc-combobox-option]',
})
export class ComboBoxOptionDirective<T, I extends Item> {
  @Input('data-gc-combobox-option')
  public item: IndexedItem<T, I> | undefined;
 
  constructor(private el: ElementRef) {}
 
  scrollIntoView(): void {
    const element = this.el.nativeElement as HTMLElement;
    element.scrollIntoView({ block: 'nearest', inline: 'nearest' });
  }
}
 
@Directive({
  selector: '[data-gc-combobox-list]',
})
export class ComboBoxListDirective<T, I extends Item> {
  @ContentChildren(ComboBoxOptionDirective)
  public options!: QueryList<ComboBoxOptionDirective<T, I>>;
 
  scrollIntoView(value: IndexedItem<T, I>): void {
    const valId = value.key;
    const found = this.options.find((op: ComboBoxOptionDirective<T, I>) => {
      if (op.item === undefined) {
        return false;
      }
      const opId = op.item.key;
      return valId == opId;
    });
 
    found?.scrollIntoView();
  }
 
  scrollToFirst(): void {
    this.options.get(0)?.scrollIntoView();
  }
}
 
const SELECT_ENTRY_MESSAGE =
  'Bitte wählen Sie einen Eintrag aus der Trefferliste aus';
 
interface ItemLoadWithDisabled<T> {
  result: readonly T[];
  disabledItems: ReadonlySet<string>;
}
type ItemLoadResult<T> = readonly T[] | ItemLoadWithDisabled<T>;
 
function isItemLoadWithDisabled<T>(
  result: ItemLoadResult<T>,
): result is ItemLoadWithDisabled<T> {
  return !Array.isArray(result);
}
 
/**
 * A ComboBox allowing the user to choose an item from a collapsible list of options by entering a text.
 */
@Component({
  selector: 'gc-combobox',
  templateUrl: './combobox.component.html',
  styleUrls: ['./combobox.component.css'],
})
export class ComboBoxComponent<T, I extends Item = Item>
  implements FocusableElementOwner, AfterViewInit, OnChanges
{
  /**
   * Custom ID to use
   */
  @Input()
  public id?: string;
 
  /**
   * Decides if the combobox will be rendered in a disabled/enabled state
   */
  @Input()
  public disabled = false;
 
  /**
   * Timeout (in milliseconds) to wait upon the user changed
   * the text value in the comboxbox-field
   */
  @Input()
  public refreshTriggerTimeout = 400;
 
  /**
   * Enables resetting the value i.e. the selection of a no-value (undefined) item.
   */
  @Input()
  public resetEnabled = true;
 
  /**
   * Informs about the change of the selection state
   */
  @Output()
  public readonly valueChange: EventEmitter<Nullable<T | InvalidControlValue>> =
    new EventEmitter<Nullable<T | InvalidControlValue>>();
 
  /**
   * Signals changes of the current (combined) status of the component, e.g. also reports errors triggered by internal
   * validation or input handling.
   */
  @Output()
  public readonly onStatusChange: EventEmitter<FormControlStatus> =
    new EventEmitter<FormControlStatus>(true);
 
  /**
   * Signals that the text value has changed. In contrast to "valueChange" this event is emitted immediately
   * and provides the current (unprocessed) text visible in the control
   */
  @Output()
  public readonly onInputChange: EventEmitter<string> =
    new EventEmitter<string>(true);
 
  /** The function that provides the items. */
  @Input()
  public items?: (searchVal: string) => Promise<ItemLoadResult<T>>;
 
  /** The adapter to convert the model items into Items. */
  @Input()
  public itemAdapter: Converter<T, I> | undefined;
 
  /** Optional icon provider to use for the selected entry */
  @Input()
  public iconProvider?: TemplateRef<unknown>;
 
  /** Optional icon provider to use for the entries in the popup list */
  @Input()
  public listIconProvider?: TemplateRef<unknown>;
 
  /** The label that shows on the input. */
  @Input()
  public label = '';
 
  /** Marks the input field as required. true == required */
  @Input()
  public required = false;
 
  /** A hint message that will appear below the combobox if set. */
  @Input()
  public hint = '';
 
  /** Decides whether large or small icons appearing. */
  @Input()
  public smallIcons = false;
 
  /**
   * Overrides the default text which is shown when the control is readonly and empty.
   */
  @Input()
  public readonlyEmptyValue = '';
 
  /**
   * If true, the component will be rendered in a slot-element mode.
   * This enables the component to be used in two-slot components (e.g. `gc-two-slot-label-container`).
   * @ignore
   */
  @Input()
  public _slotElementMode?: 'ext-search-single-field';
 
  /**
   * Error message id used when `_slotElementMode` is enabled.
   * @ignore
   */
  @Input()
  public _errorMessageId?: string;
 
  /** Fires if the combobox has focus. */
  @Output()
  public readonly onFocusEntered: EventEmitter<void> = new EventEmitter<void>();
 
  /** Fires if the combobox has lost focus. */
  @Output()
  public readonly onFocusLeft: EventEmitter<void> = new EventEmitter<void>();
 
  /** Fires if the combobox focus border visibility needs to be overridden. */
  @Output()
  public readonly _onHideFocusBorder: EventEmitter<boolean> =
    new EventEmitter<boolean>();
 
  /** @ignore */
  @ViewChild('popup')
  public popup?: OverlayContainerComponent;
 
  /** @ignore */
  @ViewChild(LabelContainerComponent)
  public labelContainer?: LabelContainerComponent;
 
  /** @ignore */
  @ViewChild('drawerSlot')
  public drawerSlot?: ElementRef;
 
  /** @ignore */
  @ViewChild('textInput')
  public textInput?: ElementRef<HTMLInputElement>;
 
  /** @ignore */
  @ViewChild('readonlyTextInput')
  public readonlyTextInput?: TextInputComponent;
 
  /** @ignore */
  @ViewChildren('li[role=option]')
  public options!: QueryList<ElementRef>;
 
  /** @ignore */
  @ViewChild(ComboBoxListDirective)
  public list!: ComboBoxListDirective<T, I>;
 
  /** The current selected value or undefined to clear it */
  @Input()
  public value: Nullable<T | InvalidControlValue> = null;
 
  /**
   * Enables setting of the value only when the Promise resolves with value "true".
   */
  @Input()
  public permitValueChange?: (
    v: T | null | InvalidControlValue,
  ) => Promise<boolean> | boolean;
 
  /** @ignore */
  @Input()
  public _sizeHelperValue = '';
 
  /** An error message that will appear below the combobox if set. */
  @Input()
  public set errorMessage(message: string) {
    if (this._errorMessage !== message) {
      this._errorMessage = message;
      this.emitStatusChange();
    }
  }
 
  public get errorMessage(): string {
    return this._errorMessage;
  }
 
  /**
   * Decides if the combobox renders in a readonly state.
   */
  @Input()
  public get readonly(): boolean {
    return this._readonly;
  }
 
  public set readonly(value: boolean) {
    this._readonly = value;
    if (!value) {
      this.connectPopup();
    }
  }
 
  /** @ignore */
  public set _impl_focusItem(value: OptionalNullable<IndexedItem<T, I>>) {
    this.__impl_focusItem = value;
 
    if (value) {
      this.list.scrollIntoView(value);
    } else {
      this.list.scrollToFirst();
    }
  }
 
  /** @ignore */
  public get _impl_focusItem(): OptionalNullable<IndexedItem<T, I>> {
    return this.__impl_focusItem;
  }
 
  /** @ignore */
  protected get _combinedErrorMessage(): string {
    return this.internalErrorMessage || this.errorMessage;
  }
 
  /** @ignore */
  private set internalErrorMessage(message: string) {
    if (message !== this._internalErrorMessage) {
      this._internalErrorMessage = message;
      this.emitStatusChange();
    }
  }
 
  /** @ignore */
  private get internalErrorMessage(): string {
    return this._internalErrorMessage;
  }
 
  /** @ignore */
  protected textValue = '';
 
  /** @ignore */
  protected disabledItems: ReadonlySet<string> = new Set();
 
  /** @ignore */
  protected _valueItem?: IndexedItem<T, I>;
 
  /** @ignore */
  protected _impl_loading = false;
 
  /** @ignore */
  protected _impl_empty = false;
 
  /** @ignore */
  protected _impl_showTextInput = false;
 
  /** @ignore */
  protected _impl_dropdownOpen = false;
 
  /** @ignore */
  protected _impl_speechMessage = '';
 
  /** @ignore */
  protected _impl_visibleItems: (IndexedItem<T, I> | undefined)[] = [];
 
  /** @ignore */
  protected __impl_focusItem: OptionalNullable<IndexedItem<T, I>>;
 
  /** @ignore */
  protected curSearchValue = '';
 
  /** @ignore */
  protected readonly inDialog: boolean; // Workaround for https://gitlab.bestsolution.at/gefa/gefa-web-controls/-/issues/2670
 
  /** @ignore */
  private curSearchTimeout?: number;
 
  /** @ignore */
  private clearMessageTimeout?: number;
 
  /** @ignore */
  private _readonly = false;
 
  /** @ignore */
  private _userInteraction = false;
 
  /** @ignore */
  private _lastLoadId = 0;
 
  /** @ignore */
  private _errorMessage = '';
 
  /** @ignore */
  private _internalErrorMessage = '';
 
  /** @ignore */
  private _cancel_selection_highlight = false;
 
  /** @ignore */
  private hasFocus = false;
 
  constructor(@Optional() eic: ElementInsertionContextService | null) {
    this.inDialog = eic?.parent.localName === 'dialog';
  }
 
  /** @ignore */
  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent): void {
    if (this._impl_dropdownOpen) {
      this.onKeyDownDropdownOpen(event);
    } else {
      this.onKeyDownDropdownClosed(event);
    }
  }
 
  /** @ignore */
  public ngAfterViewInit(): void {
    this.connectPopup();
 
    if (this._valueItem) {
      this.textValue = this._valueItem.label;
    }
  }
 
  /** @ignore */
  public ngOnChanges(changes: SimpleChanges): void {
    if ('value' in changes || 'itemAdapter' in changes) {
      // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
      this.updateValue(changes.value.currentValue, true);
    }
    if ('resetEnabled' in changes) {
      void this.updateItems();
    }
  }
 
  public focusChild(): boolean {
    if (this.disabled) {
      return false;
    } else if (this.readonly && this.readonlyTextInput) {
      return this.readonlyTextInput.focusChild();
    } else if (this.textInput) {
      this.textInput.nativeElement.focus();
      return true;
    } else {
      return false;
    }
  }
 
  /** @ignore */
  public getAnker(): ElementRef {
    if (this.labelContainer) {
      return this.labelContainer.drawerSlot;
    } else if (this.drawerSlot) {
      return this.drawerSlot;
    }
    throw new Error('Unable to find a drawer slot');
  }
 
  /** @ignore */
  public isFocused(): boolean {
    return this.hasFocus;
  }
 
  /** @ignore */
  protected button_onMouseDown(event: MouseEvent): void {
    event.preventDefault();
  }
 
  /** @ignore */
  protected button_onClick(event: MouseEvent): void {
    if (this._impl_dropdownOpen) {
      this.cancelAndClose();
      event.preventDefault();
    } else {
      this.open();
      event.preventDefault();
    }
  }
 
  /** @ignore */
  protected getFocusedItemId(autoId: AutoIdDirective): string | undefined {
    if (this._impl_focusItem === null) {
      return undefined;
    }
    return this.getItemId(autoId, this._impl_focusItem);
  }
 
  /** @ignore */
  protected getItemId(
    autoId: AutoIdDirective,
    item: IndexedItem<T, I> | undefined,
  ): string {
    if (item === undefined) {
      return autoId.autoId + '_s_' + 'emptyItem';
    }
    return autoId.autoId + '_k_' + item.key;
  }
 
  /** @ignore */
  protected input_onClick(event: MouseEvent): void {
    if (!this._impl_dropdownOpen) {
      this.open();
      event.preventDefault();
    }
  }
 
  /** @ignore */
  protected contentArea_onMouseDown(): void {
    this.textInput?.nativeElement.focus();
  }
 
  /** @ignore */
  protected isItemSelected(item?: IndexedItem<T, I>): boolean {
    return (
      !this._cancel_selection_highlight && this._valueItem?.key == item?.key
    );
  }
 
  /** @ignore */
  protected isItemFocused(item?: IndexedItem<T, I>): boolean {
    if (this._impl_focusItem === undefined && item === undefined) {
      return true;
    }
    return this._impl_focusItem && this._impl_focusItem.key == item?.key
      ? true
      : false;
  }
 
  /** @ignore */
  protected input_onInput(text: string): void {
    this.textValue = text;
    this.onInputChange.emit(text);
 
    // If the popup was not open it will trigger an item load
    // with exactly this key so there's no need to schedule
    if (!this.open()) {
      this.delayFilter();
    }
    this._cancel_selection_highlight = true;
    this._userInteraction = true;
  }
 
  /** @ignore */
  protected async _impl_onFocusLeft(): Promise<void> {
    this.cancelAndClose();
    this.onFocusLeft.emit();
 
    await this._impl_validate();
 
    const playError = () => {
      if (this._combinedErrorMessage.length > 0) {
        void playSound(SoundType.ERROR);
      }
    };
 
    if (!this._userInteraction) {
      this._impl_showTextInput = false;
      // We need to wait a tick so that the control is back
      // in a sync state
      setTimeout(playError);
      return;
    }
 
    // We need to wait a tick so that the control is back
    // in a sync state
    setTimeout(playError);
  }
 
  /** @ignore */
  protected input_onFocus(): void {
    this._impl_showTextInput = true;
    this.hasFocus = true;
 
    this.onFocusEntered.emit();
  }
 
  /** @ignore */
  protected itemTrackBy = (
    _index: number,
    item: IndexedItem<T, I> | undefined,
  ) => {
    if (item === undefined) {
      return undefined;
    }
    return item.item.key;
  };
 
  /** @ignore */
  protected getTitle(item: IndexedItem<T, I> | undefined): string {
    if (item === undefined) {
      return '\u2013'; // = '–'
    }
 
    return item.item.label;
  }
 
  /** @ignore */
  protected getAriaTitle(
    item: IndexedItem<T, I> | undefined,
  ): string | undefined {
    if (item === undefined) {
      return 'Keine Auswahl';
    }
    return undefined;
  }
 
  /** @ignore */
  protected getText(item: IndexedItem<T, I> | undefined): string | undefined {
    if (item === undefined) {
      return undefined;
    }
 
    if (hasSublabel(item.item)) {
      return item.item.sublabel;
    }
 
    return undefined;
  }
 
  /** @ignore */
  protected input_mousedown(event: MouseEvent): void {
    event.preventDefault();
  }
 
  /** @ignore */
  protected async input_onBlur(event: FocusEvent): Promise<void> {
    if (this._impl_dropdownOpen && event.relatedTarget === null) {
      this.hasFocus = true;
      setTimeout(() => {
        this.textInput?.nativeElement.focus();
      });
      this.cancelAndClose();
    } else if (
      event.relatedTarget &&
      (event.relatedTarget as HTMLElement).dataset.gcRefuseFocus === 'true'
    ) {
      // Workaround for https://gitlab.bestsolution.at/gefa/gefa-web-controls/-/issues/2670
      const el = event.target as HTMLElement;
      setTimeout(() => {
        el.focus();
      });
    } else {
      await this._impl_onFocusLeft();
      this.hasFocus = false;
      this._userInteraction = false;
    }
  }
 
  /** @ignore */
  protected item_mousedown(event: MouseEvent): void {
    event.preventDefault();
  }
 
  /** @ignore */
  protected item_mouseclick(item: IndexedItem<T, I> | undefined): void {
    this.selectAndClose(item);
  }
 
  /** @ignore */
  protected listboxId(autoId: AutoIdDirective): string {
    return autoId.autoId + '_listbox';
  }
 
  /** @ignore */
  protected _isDisabled(item: IndexedItem<T, I> | undefined): boolean {
    return item ? this.disabledItems.has(item.key) : false;
  }
 
  /** @ignore */
  private async _impl_validate(): Promise<void> {
    if (this._impl_showTextInput) {
      const found = await this._impl_autoSelect();
      if (found) {
        this._impl_showTextInput = false;
      } else {
        this._impl_showTextInput = true;
      }
    }
  }
 
  /** @ignore */
  private getRelative(
    ary: (IndexedItem<T, I> | undefined)[],
    cur: IndexedItem<T, I> | undefined,
    delta: number,
  ): IndexedItem<T, I> | undefined {
    const idx = ary.findIndex(item => item?.key === cur?.key) + delta;
    if (idx >= 0 && ary.length > idx) {
      return ary[idx];
    }
    return cur;
  }
 
  /** @ignore */
  private focusNextItem(): void {
    if (this._impl_focusItem !== null) {
      const next = this.getRelative(
        this._impl_visibleItems,
        this._impl_focusItem,
        +1,
      );
      this._impl_focusItem = next;
    }
  }
 
  /** @ignore */
  private focusPrevItem(): void {
    if (this._impl_focusItem !== null) {
      const next = this.getRelative(
        this._impl_visibleItems,
        this._impl_focusItem,
        -1,
      );
      this._impl_focusItem = next;
    }
  }
 
  /** @ignore */
  private focusFirstItem(): void {
    this._impl_focusItem = this._impl_visibleItems[0];
  }
 
  /** @ignore */
  private focusLastItem(): void {
    this._impl_focusItem =
      this._impl_visibleItems[this._impl_visibleItems.length - 1];
  }
 
  /** @ignore */
  private open(postUpdateBlock?: () => void): boolean {
    if (this.disabled) {
      return false;
    }
    if (!this._impl_dropdownOpen) {
      this._impl_dropdownOpen = true;
      this.curSearchValue = this.textValue;
      this._impl_showTextInput = true;
      this._impl_focusItem = null;
 
      void this.updateItems(postUpdateBlock);
 
      this._onHideFocusBorder.emit(this.isFocused());
 
      return true;
    }
    return false;
  }
 
  /** @ignore */
  private cancelAndClose(): void {
    if (this._impl_dropdownOpen) {
      this._impl_dropdownOpen = false;
      this._impl_showTextInput = true;
 
      this._onHideFocusBorder.emit(
        this.isFocused() && this._impl_focusItem !== null,
      );
    }
  }
 
  /** @ignore */
  private selectAndClose(item: IndexedItem<T, I> | undefined): void {
    if (this._isDisabled(item)) {
      this._impl_focusItem = item;
    } else if (this._impl_dropdownOpen) {
      this._impl_dropdownOpen = false;
      this._impl_showTextInput = false;
 
      this._onHideFocusBorder.emit(
        this.isFocused() && this._impl_focusItem !== null,
      );
 
      void this.updateUserValue(item?.value ?? null);
    }
  }
 
  /** @ignore */
  private delayFilter(): void {
    if (this.curSearchTimeout) {
      window.clearTimeout(this.curSearchTimeout);
    }
    this.curSearchTimeout = window.setTimeout(() => {
      this.curSearchValue = this.textValue;
      void this.updateItems();
    }, this.refreshTriggerTimeout);
  }
 
  /** @ignore */
  private async _impl_autoSelect(): Promise<boolean> {
    if (!this._userInteraction) {
      return isInvalidControlValue(this.value);
    }
 
    // If go empty or the loadItems resolves immediately we need to wait at tick so that the
    // final target element is selected otherwise the focus restore does not work properly
    // and we might endup on the body after the dialog is closed
    if (this.permitValueChange) {
      await new Promise(res => setTimeout(res));
    }
 
    if (this.textValue.trim() === '' && this.resetEnabled) {
      await this.updateUserValue(null);
      return !isInvalidControlValue(this.value);
    }
 
    const result = (await this.loadItems(this.textValue)).result;
    const exactResult = result
      .filter(item => !this.disabledItems.has(item.key))
      .filter(
        item => this.textValue.toLowerCase() === item.label.toLowerCase(),
      );
    if (exactResult.length === 1) {
      await this.updateUserValue(exactResult[0].value);
      return !isInvalidControlValue(this.value);
    } else {
      await this.updateUserValue({
        kind: 'InvalidControlInput',
        rawValue: this.textValue,
        errorMessage: SELECT_ENTRY_MESSAGE,
      } satisfies InvalidControlValue);
      return !isInvalidControlValue(this.value);
    }
  }
 
  /** @ignore */
  private async updateUserValue(val: Nullable<T | InvalidControlValue>) {
    if (this.permitValueChange) {
      const change = await this.permitValueChange(val);
      if (change) {
        this.updateValue(val);
      } else {
        this.updateValue(this.value, true);
        // Force the focus back on the control if vetoed
        this.focusChild();
      }
    } else {
      this.updateValue(val);
    }
  }
 
  /** @ignore */
  private readAriaLive(text: string) {
    this._impl_speechMessage = text;
 
    window.clearTimeout(this.clearMessageTimeout);
    this.clearMessageTimeout = undefined;
    this.clearMessageTimeout = window.setTimeout(() => {
      this._impl_speechMessage = '';
    }, 500);
  }
 
  /** @ignore */
  private adaptItem(value: T, index = -1): IndexedItem<T, I> {
    if (this.itemAdapter === undefined) {
      if (isItem(value)) {
        const item = value as unknown as I;
        return {
          index,
          key: item.key,
          value,
          item,
          label: item.label,
        };
      }
      throw new Error('missing itemAdapter');
    } else {
      const item = this.itemAdapter(value);
      return {
        index,
        key: item.key,
        value,
        item,
        label: item.label,
      };
    }
  }
 
  /** @ignore */
  private async loadItems(value: string) {
    if (this.items === undefined) {
      return { result: [], disabledItems: new Set<string>() };
    }
 
    const loaded = await this.items(value);
 
    if (isItemLoadWithDisabled(loaded)) {
      const result = loaded.result.map((val, idx) => this.adaptItem(val, idx));
      return { result, disabledItems: loaded.disabledItems };
    }
 
    return {
      result: loaded.map((val, idx) => this.adaptItem(val, idx)),
      disabledItems: new Set<string>(),
    };
  }
 
  /** @ignore */
  private loadVisibleItems(
    items: IndexedItem<T, I>[],
  ): (IndexedItem<T, I> | undefined)[] {
    if (this.textValue == '' && this.resetEnabled) {
      return [undefined, ...items];
    } else {
      return items;
    }
  }
 
  /** @ignore */
  private async loadItemsWithLoadingIndicator(value: string) {
    const loadingTimeout = window.setTimeout(() => {
      this._impl_loading = true;
      this.readAriaLive('Ergebnisse werden geladen');
    }, 200);
 
    return this.loadItems(value).then(result => {
      window.clearTimeout(loadingTimeout);
      this._impl_loading = false;
      return result;
    });
  }
 
  /** @ignore */
  private async updateItems(postUpdateBlock?: () => void) {
    const loadId = ++this._lastLoadId;
    const result = await this.loadItemsWithLoadingIndicator(this.textValue);
    if (loadId === this._lastLoadId) {
      this._impl_visibleItems = this.loadVisibleItems(result.result);
      this.disabledItems = result.disabledItems;
      this._impl_empty = this._impl_visibleItems.length == 0;
      this.readAriaLive(
        this._impl_visibleItems.length.toString() + ' Treffer gefunden.',
      );
      if (postUpdateBlock) {
        postUpdateBlock();
      }
    }
  }
 
  /** @ignore */
  private connectPopup(): void {
    // waits a tick after re-querying the popup in order for it to be available
    setTimeout(() => {
      if (this.popup) {
        this.popup.anker = this.getAnker();
        this.popup.scrollTargetElement = this.labelContainer?.boxEl;
      }
    });
  }
 
  /** @ignore */
  private onKeyDownDropdownOpen(event: KeyboardEvent): void {
    const key = event.key;
 
    switch (key) {
      case 'Enter':
        if (this._impl_focusItem !== null) {
          this.selectAndClose(this._impl_focusItem);
        } else {
          void this._impl_autoSelect().then(() => {
            this.cancelAndClose();
          });
        }
        break;
      case 'Escape':
        this.cancelAndClose();
        break;
      case 'ArrowDown':
        if (this._impl_focusItem === null) {
          this.focusFirstItem();
        } else {
          this.focusNextItem();
        }
        event.preventDefault();
        break;
      case 'ArrowUp':
        this.focusPrevItem();
        event.preventDefault();
        break;
      case 'Home':
        this.focusFirstItem();
        break;
      case 'End':
        this.focusLastItem();
        break;
    }
  }
 
  /** @ignore */
  private onKeyDownDropdownClosed(event: KeyboardEvent): void {
    if (event.key == 'Enter') {
      this.open();
    }
    if (event.key == 'ArrowDown' && isOnlyAltPressedOrNothing(event)) {
      this.open(() => {
        this.focusFirstItem();
      });
    }
  }
 
  /** @ignore */
  private emitStatusChange() {
    const status: FormControlStatus = {};
    if (this.internalErrorMessage || this.errorMessage) {
      status.error = [];
      if (this.internalErrorMessage) {
        status.error.push(this.internalErrorMessage);
      }
      if (this.errorMessage) {
        status.error.push(this.errorMessage);
      }
    }
 
    this.onStatusChange.emit(status);
  }
 
  /** @ignore */
  private updateValue(
    val: Nullable<T | InvalidControlValue>,
    skipEmit?: boolean,
  ) {
    this._cancel_selection_highlight = false;
 
    if (isInvalidControlValue(val)) {
      if (
        this._valueItem === undefined &&
        this.internalErrorMessage === val.errorMessage &&
        this.textValue === val.rawValue
      ) {
        skipEmit = true;
      }
      this._valueItem = undefined;
      this.textValue = val.rawValue;
      this.internalErrorMessage = SELECT_ENTRY_MESSAGE; // only one possible error message exists at the moment
    } else {
      const newValueItem = val ? this.adaptItem(val) : undefined;
      if (this._valueItem?.value === newValueItem?.value) {
        skipEmit = true;
      }
      this._valueItem = newValueItem;
      this.textValue = this._valueItem ? this.getTitle(this._valueItem) : '';
      this.internalErrorMessage = '';
    }
 
    if (!skipEmit) {
      this.valueChange.emit(val);
    }
    this.onInputChange.emit(this.textValue);
  }
}