All files / lib/tree base-tree.component.ts

98.03% Statements 697/711
96.66% Branches 174/180
98.52% Functions 67/68
98.03% Lines 697/711

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 7121x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 195x 195x 195x 195x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 49x 49x 44x 5x 49x 1x 1x 195x 195x 195x 1x 1x 1x 1x 1x 1x 1x 7810x 7810x 1x 1x 1x 1x 1x 1x 6810x 6810x 1x 1x 1x 1x 1x 1x 39458x 39458x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 344x 225x 225x 225x 35x 344x 344x 191x 191x 191x 191x 191x 344x 344x 187x 101x 187x 187x 52x 344x 344x 344x 1x 1x 1x 1x 1x 1x 190x 190x 1x 1x 1x 8x   8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 102x 102x 102x 102x 102x 102x 57x 102x 102x 102x 102x 1x 1x 1x 394x 394x 394x 394x 1x 1x 1x 26086x 26086x 1x 1x 1x 44x 44x 1x 1x 1x 750x 750x 1x 1x 1x 160x 126x 125x 125x 1x 1x 34x 34x 34x 28x 6x 6x 160x 160x 160x 1x 1x 1x 20x 20x 1x 1x 1x 155398x 155398x 1x 1x 1x 66313x 66313x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 86x 86x 86x 16x 16x 16x 27x 3x 3x 3x 53x 14x 14x 14x 32x 3x 3x 3x 45x 2x 2x 51x 3x 3x 3x 3x 3x 3x 3x 51x 2x 2x 62x 2x 2x 1x 2x 2x 2x 86x 38x 38x 86x 86x 1x 1x 1x 22x 225x 225x 330x 330x 330x 225x 225x 22x 22x 22x 22x 22x 22x 1x 1x 1x 3793x 3114x 3114x 3114x 3114x     3793x 3793x 3793x 1x 1x 1x 3x 3x 3x 3x 1x 1x 1x 3x 3x 3x 3x 3x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 3x 1x 1x 3x 3x 1x 1x 1x 16x 16x 16x 16x 1x 1x 1x 19x 14x 19x 19x 19x 19x 11x 11x 11x 11x 11x 11x 14x 14x 14x 14x 14x 14x 11x 3x 3x 3x 3x       14x 14x 11x 19x 1x 1x 1x 14x 14x 14x 14x 1x 1x 1x 14x 14x 3x 3x 3x 14x 14x 14x 1x 1x 1x 3x 3x 3x 3x 1x 1x 1x 3x 3x             3x 1x 1x 1x 3x 3x 3x 3x 1x 1x 1x 4x 7x 7x 7x 7x 7x 7x 7x 6x 3x 3x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 1x 1x 1x 38x 30x 38x 38x 38x 38x 9x 38x 38x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 9x 9x 9x 9x 9x 140x 140x 140x 15x 125x 140x 140x 140x 140x 140x 140x 65x 65x 65x 75x 75x 140x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 11x 29x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 2893x 2893x 2893x 2893x 2893x 2893x 2893x 2893x 2893x 2893x 2893x 2893x 3684x 3684x 2499x 1185x 3684x 3684x 3684x 3684x 3684x 3684x 3684x 3684x 3684x 3684x 3684x 3684x 3684x 3684x 3684x 2893x 2893x 2893x 2893x 2893x 1x 1x 1x 225x 225x 225x 225x 225x 225x 225x 225x 225x 394x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 298x 227x 227x 227x 227x 227x 227x 227x 227x 225x 225x 225x 225x 225x 225x 225x 225x 225x 225x 225x 225x 225x 225x 33x 225x 225x 225x 225x 225x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
/*******************************************************************************
 * Copyright bei
 * Entwicklungs- und Pflegeverbund für das gemeinsame Fachverfahren gefa
 *
 *******************************************************************************/
import {
  AfterViewInit,
  Directive,
  Input,
  OnChanges,
  OnDestroy,
  SimpleChanges,
} from '@angular/core';
 
import { Converter, Key, TreeItemBasic } from '../utils/util.types';
import { isItemGroup } from '../utils/utilities';
 
import { TreeItemGroup } from './tree.component';
 
export interface TreeItemBasicAdvancedKeys<T>
  extends Omit<TreeItemBasic<T>, 'key'> {
  key: string | symbol;
}
 
export type RecursiveBaseTreeItem<T> = TreeItemBasicAdvancedKeys<
  RecursiveBaseTreeItem<T>
> & { parent: RecursiveBaseTreeItem<T> | undefined; value: T | undefined };
 
function isReadonlyArray<I>(i: I | readonly I[]): i is readonly I[] {
  // workaround for https://github.com/microsoft/TypeScript/issues/17002
  return Array.isArray(i);
}
 
/**
 * Internal base class to implement trees.
 * @template T type of data entities
 * @template B base tree item class to which (external) converters will transform T, still has children of type T
 * @template I main representation of tree items used internally, references other internal tree items
 */
@Directive()
export abstract class BaseTreeComponent<
    T,
    B extends TreeItemBasicAdvancedKeys<T>,
    I extends TreeItemBasicAdvancedKeys<I> & {
      parent: I | undefined;
      value: T | undefined;
    },
  >
  implements OnChanges, AfterViewInit, OnDestroy
{
  /**
   * Data that will be rendered as tree items/nodes.
   */
  @Input()
  public items: readonly (T | TreeItemGroup<T>)[] = [];
 
  /** Adapts the domain type T to the internal TreeItem structure */
  @Input()
  public itemAdapter?: Converter<T, B>;
 
  /**
   * The value represents the selected item.
   */
  @Input()
  public get value(): T | undefined {
    return this._selectedItemKey !== undefined
      ? this.getValueByKey(this._selectedItemKey)
      : undefined;
  }
 
  public set value(value: T | undefined) {
    this._selectedItemKey =
      value !== undefined ? this.convert(value).key : undefined;
  }
 
  /**
   * Number of items within each category, not including the category item itself. Only used if `items` contain
   * groups.
   * @ignore
   */
  protected get categoryItemCount(): ReadonlyMap<Key | symbol, number> {
    return this._categoryItemCount;
  }
 
  /**
   * Total number of items. Does not count group items if `items` represent groups, only their children.
   * @ignore
   */
  protected get totalEntryCount(): number {
    return this._totalEntryCount;
  }
 
  /**
   * Internal representation of `items` after conversion.
   * @ignore
   */
  protected get _items(): readonly I[] {
    return this.convertedItems;
  }
 
  /**
   * Key of the currently selected item.
   * @ignore
   */
  protected _selectedItemKey?: Key | symbol;
 
  /** @ignore */
  private expandedKeys: Set<Key | symbol> = new Set();
 
  /** @ignore */
  private _categoryItemCount: ReadonlyMap<Key | symbol, number> = new Map();
  /** @ignore */
  private _totalEntryCount = 0;
 
  /** @ignore */
  private convertedItems: readonly I[] = [];
 
  /**
   * @ignore
   * map to effeciently lookup a data entity for a specific item key
   */
  private _itemKeys: ReadonlyMap<Key | symbol, { value: T; item: I }> =
    new Map();
 
  /** @ignore */
  private inputTimeout?: ReturnType<typeof setTimeout>;
 
  /** @ignore */
  private textInput = '';
 
  constructor(private rootItemsExpanded: boolean) {}
 
  /** @ignore */
  public ngOnChanges(changes: SimpleChanges): void {
    if ('items' in changes || 'itemAdapter' in changes) {
      this.updateItems();
      if (
        changes.items.firstChange ||
        (isReadonlyArray(changes.items.previousValue) &&
          changes.items.previousValue.length === 0)
      ) {
        const expandedItems = this._items.filter(
          i => this.rootItemsExpanded || this.isTreeItemGroupKey(i.key), // root items start as expanded
        );
        this.expandedKeys = new Set(expandedItems.map(i => i.key));
      }
    }
    if ('value' in changes) {
      if (this._selectedItemKey) {
        this.expandItem(this._selectedItemKey);
      }
      if (!changes.value.firstChange) {
        this.scrollToSelectedItem();
      }
    }
  }
 
  /**
   * ngAfterViewInit must be used because scrolling is done upon an HTML element which must be rendered.
   * @ignore
   */
  ngAfterViewInit(): void {
    this.scrollToSelectedItem();
  }
 
  /** @ignore */
  public ngOnDestroy(): void {
    if (this.inputTimeout !== undefined) {
      clearTimeout(this.inputTimeout);
    }
  }
 
  /** Expands all items of the tree. */
  public expandAll(): void {
    this.setExpandedStateForAllItems(true);
  }
 
  /** Collapses all items of the tree. */
  public collapseAll(): void {
    this.setExpandedStateForAllItems(false);
  }
 
  /** Expands the tree item and all of its parents. */
  public expandItem(key: Key | symbol): void {
    const foundItem = this.getItemByKey(key);
    let tempParent = foundItem?.parent;
 
    const itemsToExpand = [];
    while (tempParent !== undefined) {
      itemsToExpand.push(tempParent);
      tempParent = tempParent.parent;
    }
 
    this.setExpandedState(itemsToExpand, true);
  }
 
  /** @ignore */
  protected isTreeItemGroup(
    item: TreeItemGroup<T> | T,
  ): item is TreeItemGroup<T> {
    return isItemGroup(item);
  }
 
  /** @ignore */
  protected isTreeItemGroupKey(key: Key | symbol): boolean {
    return this._categoryItemCount.has(key);
  }
 
  /** @ignore */
  protected getValueByKey(key: Key | symbol): T | undefined {
    return this._itemKeys.get(key)?.value;
  }
 
  /** @ignore */
  protected getItemByKey(key: Key | symbol): I | undefined {
    return this._itemKeys.get(key)?.item;
  }
 
  /** @ignore */
  protected setExpandedState(items: I | readonly I[], expanded: boolean) {
    if (isReadonlyArray(items)) {
      if (expanded) {
        // check outside of the following loop for more efficient handling of many items
        items.forEach(i => this.expandedKeys.add(i.key));
      } else {
        items.forEach(i => this.expandedKeys.delete(i.key));
      }
    } else {
      if (expanded) {
        this.expandedKeys.add(items.key);
      } else {
        this.expandedKeys.delete(items.key);
      }
    }
  }
 
  /** @ignore */
  protected toggleExpandedState(item: I) {
    this.setExpandedState(item, !this.isExpanded(item));
  }
 
  /** @ignore */
  protected isExpanded(item: I): boolean {
    return this.expandedKeys.has(item.key);
  }
 
  /** @ignore */
  protected isEndNode(item: I): boolean {
    return item.children === undefined || item.children.length === 0;
  }
 
  /**
   * Handle common keyboard events on an item. Events specific to subclasses should
   * be handled first before calling this function, this function may 'consume' any event which
   * is passed to it.
   * @param event the keyboard event to handle
   * @param focusedItem the currently focused item where the event occurred
   * @return `true` if the event has been handled and actions have been performed, `false` otherwise
   * @ignore
   */
  protected handleItemKeyEvent(event: KeyboardEvent, focusedItem: I): boolean {
    const key = event.key;
    switch (key) {
      case 'ArrowDown':
        this.handleArrowDown(focusedItem, event);
        event.preventDefault();
        return true;
      case 'ArrowUp':
        this.handleArrowUp(focusedItem, event);
        event.preventDefault();
        return true;
      case 'ArrowRight':
        this.handleArrowRight(focusedItem, event);
        event.preventDefault();
        return true;
      case 'ArrowLeft':
        this.handleArrowLeft(focusedItem, event);
        event.preventDefault();
        return true;
      case '*':
        this.expandFocusedElementSiblings(focusedItem);
        return true;
      case 'Home':
        this.focusFirstVisibleItem();
        event.preventDefault();
        return true;
      case 'End':
        this.focusLastVisibleItem(this._items);
        event.preventDefault();
        return true;
      case 'Shift':
        // ignore key for proper text input
        return false;
      case 'Tab':
        // focus leaves the component -> cancel any ongoing text input processing
        if (this.inputTimeout) {
          clearTimeout(this.inputTimeout);
        }
        // input not fully handled by the base class, thus report as unhandled
        return false;
      default:
        this.processTextInput(key, focusedItem.key);
        return true;
    }
  }
 
  /** @ignore */
  protected setExpandedStateForAllItems(expanded: boolean): void {
    const flattenChildren = (items: readonly I[]): readonly I[] =>
      items.reduce<readonly I[]>(
        (acc, val) => [
          ...acc,
          val,
          ...(val.children ? flattenChildren(val.children) : []),
        ],
        [],
      );
    const flatItems = flattenChildren(this._items).filter(
      i => !this.isEndNode(i),
    );
    this.setExpandedState(flatItems, expanded);
  }
 
  /** @ignore */
  protected convert(value: T): B {
    if (this.itemAdapter === undefined) {
      if (this.isBaseItem(value)) {
        return value;
      }
      console.error('Missing converter for ', value);
      throw new Error('missing converter');
    } else {
      return this.itemAdapter(value);
    }
  }
 
  /** @ignore */
  private handleArrowUp(focusedItem: I, event: KeyboardEvent): void {
    if (!event.shiftKey) {
      this.handleArrowUpNavigation(focusedItem);
    }
  }
 
  /** @ignore */
  private handleArrowUpNavigation(focusedItem: I) {
    const currentLevelItems = focusedItem.parent?.children ?? this._items;
    const itemIndexInParent = currentLevelItems.findIndex(
      c => c.key === focusedItem.key,
    );
    if (itemIndexInParent > 0) {
      // if there is an immediate sibling preceeding the current item on the same level, select the last visible item within that sibling...
      const previousItemOnLevel = currentLevelItems[itemIndexInParent - 1];
      if (
        !this.isEndNode(previousItemOnLevel) &&
        previousItemOnLevel.children &&
        this.isExpanded(previousItemOnLevel)
      ) {
        this.focusLastVisibleItem(previousItemOnLevel.children);
      } else {
        // ... or the sibling itself if it has no visible children
        this._focusItem(previousItemOnLevel);
      }
    } else if (focusedItem.parent) {
      // element is already the first one on the current level -> focus the parent
      this._focusItem(focusedItem.parent);
    }
  }
 
  /** @ignore */
  private handleArrowDown(focusedItem: I, event: KeyboardEvent): void {
    if (!event.shiftKey) {
      this.handleArrowDownNavigation(focusedItem);
    }
  }
 
  /** @ignore */
  private handleArrowDownNavigation(startItem: I): void {
    const getCurrentLevelItems = (parent: I | undefined) =>
      parent ? parent.children : this._items; // at the top level there's no parent, thus "current level" are top level items
 
    if (startItem.children && this.isExpanded(startItem)) {
      // item has a direct (visible) child
      this._focusItem(startItem.children[0]);
    } else {
      // find the next direct sibling following the element by checking via the parent
      let item = startItem;
      let parent = item.parent;
      let currentLevelItems = getCurrentLevelItems(parent);
      while (currentLevelItems) {
        const itemIndexInParent = currentLevelItems.findIndex(
          c => c.key === item.key,
        );
        if (itemIndexInParent < currentLevelItems.length - 1) {
          this._focusItem(currentLevelItems[itemIndexInParent + 1]);
          return;
        } else if (parent) {
          // item is the last element on its level -> repeat check one level higher if one exists
          item = parent;
          parent = item.parent;
          currentLevelItems = getCurrentLevelItems(parent);
        } else {
          // already at the top level, no higher level to check -> current item is already the last one
          currentLevelItems = undefined;
        }
      }
    }
  }
 
  /** @ignore */
  private handleArrowRight(focusedItem: I, event: KeyboardEvent): void {
    if (!event.shiftKey) {
      this.handleArrowRightNavigation(focusedItem);
    }
  }
 
  /** @ignore */
  private handleArrowRightNavigation(focusedItem: I) {
    if (!this.isEndNode(focusedItem)) {
      if (!this.isExpanded(focusedItem)) {
        this.setExpandedState(focusedItem, true);
      } else {
        this.handleArrowDownNavigation(focusedItem);
      }
    }
  }
 
  /** @ignore */
  private handleArrowLeft(focusedItem: I, event: KeyboardEvent): void {
    if (!event.shiftKey) {
      this.handleArrowLeftNavigation(focusedItem);
    }
  }
 
  /** @ignore */
  private handleArrowLeftNavigation(focusedItem: I) {
    if (!this.isEndNode(focusedItem) && this.isExpanded(focusedItem)) {
      this.setExpandedState(focusedItem, false);
    } else {
      const parent = focusedItem.parent;
      if (parent) {
        this._focusItem(parent);
      }
    }
  }
 
  /** @ignore */
  private focusFirstVisibleItem() {
    if (this._items.length > 0) {
      this._focusItem(this._items[0]);
    }
  }
 
  /** @ignore */
  private focusLastVisibleItem(items: readonly I[]): void {
    const findLastVisible = (entries: readonly I[]): I | null => {
      if (entries.length < 1) {
        return null;
      }
 
      const lastEntryAtCurrentLevel = entries[entries.length - 1];
      if (
        lastEntryAtCurrentLevel.children &&
        this.isExpanded(lastEntryAtCurrentLevel)
      ) {
        return findLastVisible(lastEntryAtCurrentLevel.children);
      } else {
        return lastEntryAtCurrentLevel;
      }
    };
 
    const lastVisibleElement = findLastVisible(items);
    if (lastVisibleElement) {
      this._focusItem(lastVisibleElement);
    }
  }
 
  /** @ignore */
  private expandFocusedElementSiblings(focusedItem: I): void {
    let level = 1;
    let parent = focusedItem.parent;
    while (parent !== undefined) {
      level += 1;
      parent = parent.parent;
    }
 
    let itemsToExpand = this._items;
    for (; level > 1; level--) {
      itemsToExpand = itemsToExpand.flatMap(i => {
        if (this.isExpanded(i)) {
          return i.children?.filter(i => !this.isEndNode(i)) ?? [];
        } else {
          return [];
        }
      });
    }
 
    this.setExpandedState(itemsToExpand, true);
  }
 
  /** @ignore */
  private processTextInput(key: string, startItemKey: Key | symbol): void {
    if (this.inputTimeout) {
      clearTimeout(this.inputTimeout);
    }
 
    this.textInput = this.textInput.concat(key);
    this.inputTimeout = setTimeout(() => {
      this.focusListItemByInput(startItemKey);
    }, 1000);
  }
 
  /** @ignore */
  private focusListItemByInput(startItemKey: Key | symbol): void {
    const foundItem = this.findTreeItemByInput(startItemKey);
    if (foundItem) {
      this._focusItem(foundItem);
    }
 
    this.textInput = '';
  }
 
  /** @ignore */
  private findTreeItemByInput(startItemKey: Key | symbol): I | undefined {
    interface Collector {
      items: I[];
      startSearchAt?: number;
    }
    const collectSearchable = (collected: Collector, item: I): Collector => {
      // only add the current item if it's not a group separator, as those are not included in the search
      const addItems =
        item.parent === undefined && this.isTreeItemGroupKey(item.key)
          ? collected.items
          : collected.items.concat(item);
      // remember the start index in the collected data if the current element is the start item
      const startSearchAt =
        startItemKey === item.key ? addItems.length : collected.startSearchAt;
 
      // recursively include visible children
      if (item.children && this.isExpanded(item)) {
        return item.children.reduce<Collector>(collectSearchable, {
          items: addItems,
          startSearchAt,
        });
      } else {
        return { items: addItems, startSearchAt };
      }
    };
 
    // determine list of searchable items and start index within that list
    const { items, startSearchAt } = this._items.reduce(collectSearchable, {
      items: [],
      startSearchAt: undefined,
    });
 
    const findItemByInputFromIdx = (startIndex: number): I | undefined => {
      return items.slice(startIndex, undefined).find(i => {
        return i.label.toLowerCase().includes(this.textInput.toLowerCase());
      });
    };
 
    if (startSearchAt !== undefined) {
      // determine the first element which matches starting at the specified index, wrap search and start at the beginning if not found
      return findItemByInputFromIdx(startSearchAt) ?? findItemByInputFromIdx(0);
    } else {
      return undefined;
    }
  }
 
  /** @ignore */
  private convertItems(items: readonly T[]): {
    items: I[];
    itemKeys: [string | symbol, { value: T; item: I }][];
    totalCount: number;
  } {
    interface ReducerData {
      itemKeys: [string | symbol, { value: T; item: I }][];
      items: I[];
      totalCount: number;
    }
 
    return items.reduce<ReducerData>(
      (acc, entry) => {
        const converted = this.convert(entry);
        const children = converted.children
          ? this.convertItems(converted.children)
          : undefined;
 
        const treeItem: I = this.createItem(
          entry,
          converted,
          undefined,
          children?.items,
        );
        treeItem.children?.forEach(c => (c.parent = treeItem));
 
        return {
          itemKeys: acc.itemKeys.concat(children?.itemKeys ?? [], [
            [converted.key, { value: entry, item: treeItem }],
          ]),
          items: acc.items.concat(treeItem),
          totalCount: acc.totalCount + (children?.totalCount ?? 0) + 1,
        };
      },
      { itemKeys: [], items: [], totalCount: 0 },
    );
  }
 
  /** @ignore */
  private updateItems() {
    interface ReducerData {
      itemKeys: [string | symbol, { value: T; item: I }][];
      items: I[];
      categoryCounts: [string, number][];
      totalCount: number;
    }
 
    const convertedItems = this.items.reduce<ReducerData>(
      (acc, entry) => {
        if (this.isTreeItemGroup(entry)) {
          const groupData = this.convertItems(entry.items);
 
          const { key, label } = entry;
          const groupItem: I = this.createGroupItem({
            key,
            label,
            children: groupData.items,
            parent: undefined,
            value: undefined,
          });
          groupItem.children?.forEach(c => (c.parent = groupItem));
          return {
            itemKeys: acc.itemKeys.concat(groupData.itemKeys),
            items: acc.items.concat([groupItem]),
            categoryCounts: acc.categoryCounts.concat([
              [entry.key, groupData.totalCount],
            ]),
            totalCount: acc.totalCount + groupData.totalCount,
          };
        } else {
          const convertedEntry = this.convertItems([entry]);
          return {
            itemKeys: acc.itemKeys.concat(convertedEntry.itemKeys),
            items: acc.items.concat(convertedEntry.items),
            categoryCounts: acc.categoryCounts,
            totalCount: acc.totalCount + convertedEntry.totalCount,
          };
        }
      },
      { itemKeys: [], items: [], categoryCounts: [], totalCount: 0 },
    );
 
    this.convertedItems = convertedItems.items;
    this._itemKeys = new Map(convertedItems.itemKeys);
    this._categoryItemCount = new Map(convertedItems.categoryCounts);
    this._totalEntryCount = convertedItems.totalCount;
 
    // delete expanded keys which don't exist anymore
    const itemKeys = this._itemKeys;
    function* filterExisting(keys: Iterable<Key | symbol>) {
      for (const key of keys) {
        if (itemKeys.has(key)) {
          yield key;
        }
      }
    }
    this.expandedKeys = new Set(filterExisting(this.expandedKeys.values()));
  }
 
  /**
   * @ignore
   * Typeguard for checking whether an item is of type `B` (i.e. to determine if conversion is required).
   * @param x the item to check
   */
  protected abstract isBaseItem(x: unknown): x is B;
 
  /**
   * @ignore
   * Create an internal representation for a group item. Implementations must create a new item which contains
   * all information from the passed base item.
   * @param base base for creating the item
   */
  protected abstract createGroupItem(base: RecursiveBaseTreeItem<unknown>): I;
 
  /**
   * @ignore
   * Create an internal representation for a converted item. Implementations must create a new item which contains
   * the information from the passed item and properties, with any extra information filled in to satisfy the type `I`.
   * @param value the original value
   * @param converted the converted item which should be used as base
   * @param parent the parent to set on the new item
   * @param children the children to set on the new item
   */
  protected abstract createItem(
    value: T,
    converted: B,
    parent: I | undefined,
    children: I[] | undefined,
  ): I;
 
  /**
   * @ignore
   * Transfer focus to an item.
   * @param item the item to focus.
   */
  protected abstract _focusItem(item: I): void;
 
  /**
   * Scrolls to the selected tree item.
   */
  protected abstract scrollToSelectedItem(): void;
}