All files / element-ng/filtered-search si-filtered-search.component.ts

98.31% Statements 234/238
94.67% Branches 160/169
97.1% Functions 67/69
99.08% Lines 216/218

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                                                                              1x 1x                                                                                   1115x           171x         171x               171x             171x             171x           171x           171x               171x               171x             171x               171x             171x             171x                   171x           171x           171x                     171x           171x                 171x                   171x                   171x 171x                     171x 171x             171x           171x           171x               171x                       171x                         171x 171x                                           171x   171x   171x   171x     171x 171x 174x 174x   171x   171x   171x   171x 171x 171x 171x 171x   171x           171x 167x     171x 171x     171x 171x 184x 184x 10x   174x       171x   37x 37x 17x   20x                   171x   22x     171x 293x             171x   170x 9x   38x   33x         161x   252x           777x   777x 285x               326x 174x   326x       176x         171x 1x     170x   22x       462x                     121x   106x 83x       23x 23x 3x     20x       176x 176x     100x             100x   100x 4x     100x       100x                       176x             3x     3x     3x 3x 3x 3x       12x             12x 16x     16x 12x 12x 2x   10x   12x 8x         19x 16x         812x 773x   39x               550x   385x       550x 266x   550x               99x 4x     95x     99x 21x 21x 4x     74x         8x     66x 66x 6x 6x 1x   5x 5x               60x       82x           82x 82x 82x             60x 60x     12x       60x 60x 7x   53x           166x       9x 9x             6x 2x   4x 4x 4x             362x       1109x 362x 324x       37x 37x 25x           1109x                       285x 279x   6x             33x 69x         33x 33x 6x             33x                 193x 193x 193x 193x         1x 1x 1x                 17x 16x                   59x 59x 170x   59x 59x 49x           171x 69x         60x 60x       13x 13x 1x   12x 12x         226x 226x       226x 226x 41x         23x 23x 17x        
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { formatDate } from '@angular/common';
import {
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  DestroyRef,
  ElementRef,
  inject,
  input,
  LOCALE_ID,
  model,
  OnChanges,
  OnInit,
  output,
  signal,
  SimpleChanges,
  viewChild,
  viewChildren
} from '@angular/core';
import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';
import { elementCancel, elementSearch } from '@siemens/element-icons';
import {
  BackgroundColorVariant,
  defaultConnectedOverlayScrollStrategyFactory,
  isRTL
} from '@siemens/element-ng/common';
import { getDatepickerFormat, isValid, parseDate } from '@siemens/element-ng/datepicker';
import { addIcons, SiIconComponent } from '@siemens/element-ng/icon';
import {
  injectSiTranslateService,
  SiTranslatePipe,
  t,
  TranslatableString
} from '@siemens/element-translate-ng/translate';
import { merge, Observable, Subject, switchMap } from 'rxjs';
import { debounceTime, map } from 'rxjs/operators';
 
import {
  differenceByName,
  findOption,
  InternalCriterionDefinition,
  toInternalCriteria,
  toTranslatedOptions
} from './si-filtered-search-helper';
import { SiFilteredSearchInputComponent } from './si-filtered-search-input.component';
import { SiFilteredSearchValueComponent } from './si-filtered-search-value.component';
import {
  CriterionDefinition,
  CriterionValue,
  DisplayedCriteriaEventArgs,
  OptionType,
  SearchCriteria
} from './si-filtered-search.model';
 
interface InternalCriterion {
  config: InternalCriterionDefinition;
  value: CriterionValue;
  editOnCreation: boolean;
  initialValueText?: string;
}
 
@Component({
  selector: 'si-filtered-search',
  imports: [
    SiIconComponent,
    SiTranslatePipe,
    SiFilteredSearchInputComponent,
    SiFilteredSearchValueComponent
  ],
  templateUrl: './si-filtered-search.component.html',
  styleUrl: './si-filtered-search.component.scss',
  changeDetection: ChangeDetectionStrategy.Eager,
  host: {
    '[class.disabled]': 'disabled()',
    '[class.dark-background]': "colorVariant() === 'base-0'"
  }
})
export class SiFilteredSearchComponent implements OnInit, OnChanges {
  /**
   * Factory for CDK scroll strategies used by filtered-search overlays.
   *
   * @defaultValue defaultConnectedOverlayScrollStrategyFactory()
   */
  readonly scrollStrategy = input(defaultConnectedOverlayScrollStrategyFactory());
  /**
   * Output callback event that provides an object describing the
   * selected criteria and additional filter text.
   */
  readonly doSearch = output<SearchCriteria>();
  /**
   * If this is set to `true`, the search triggers for each input (implicit search).
   * By default, the search is triggered when the user submits by pressing the
   * search button or by pressing enter.
   *
   * @defaultValue false
   */
  readonly doSearchOnInputChange = input(false, {
    transform: booleanAttribute
  });
  /**
   * In addition to lazy loaded value, you can also lazy load the criteria itself
   */
  readonly lazyCriterionProvider =
    input<(typed: string, searchCriteria?: SearchCriteria) => Observable<CriterionDefinition[]>>();
  /**
   * In many cases, your application defines the criteria, but the values need
   * to be loaded from a server. In this case you can provide a function that
   * returns the possible criterion options as an Observable.
   */
  readonly lazyValueProvider =
    input<(criterionName: string, typed: string | string[]) => Observable<OptionType[]>>();
  /**
   * Disable any interactivity.
   *
   * @defaultValue false
   */
  readonly disabled = input(false, { transform: booleanAttribute });
  /**
   * Limit criteria to the predefined ones.
   *
   * @defaultValue false
   */
  readonly strictCriterion = input(false, { transform: booleanAttribute });
 
  /**
   * Limit criterion options to the predefined ones. `[strictValue]`
   * enforces `[strictCriterion]` to true automatically.
   *
   * @defaultValue false
   */
  readonly strictValue = input(false, { transform: booleanAttribute });
 
  /**
   * Limit criterion options to the predefined ones and prevent typing. `[onlySelectValue]`
   * enforces `[strictValue]` and `[strictCriterion]` to true automatically.
   *
   * @defaultValue false
   */
  readonly onlySelectValue = input(false, { transform: booleanAttribute });
 
  /**
   * Custom debounce time for lazy loading of criteria data.
   *
   * @defaultValue 500
   */
  readonly lazyLoadingDebounceTime = input(500);
  /**
   * Custom debounce time (in mills) to delay the search emission.
   * (Default is 0 as in most cases a users manually triggers a search.
   * Recommended to increase a bit when using doSearchOnInputChange=true)
   *
   * @defaultValue 0
   */
  readonly searchDebounceTime = input(0);
 
  /**
   * The placeholder for input field.
   *
   * @defaultValue ''
   */
  readonly placeholder = input('');
 
  /**
   * Defines the number of criteria, criteria values and operators visible at once.
   *
   * @defaultValue 10
   */
  readonly optionsInScrollableView = input(10);
 
  /**
   * The current selected search criteria and entered search text.
   *
   * @defaultValue
   * ```
   * { criteria: [], value: '' }
   * ```
   */
  readonly searchCriteria = model<SearchCriteria>({ criteria: [], value: '' });
  /**
   * Predefine criteria options.
   *
   * @defaultValue []
   */
  readonly criteria = input<CriterionDefinition[]>([]);
  /**
   * Opt-in to search for each criterion only once.
   *
   * @defaultValue false
   */
  readonly exclusiveCriteria = input(false, {
    transform: booleanAttribute
  });
 
  /**
   * Limit the number of possible criteria. The default is undefined so that any number of criteria can be used.
   * For example, setting the value to 1 let you only select one criterion that you need to remove before being
   * able to set another one.
   *
   * @defaultValue undefined
   */
  readonly maxCriteria = input<number | undefined>(undefined);
  /**
   * Defines the maximum options within one criterion. The default is 20 and 0 means unlimited.
   *
   * @defaultValue 20
   */
  readonly maxCriteriaOptions = input(20);
  /**
   * Search input aria label, Needed by a11y
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_FILTERED_SEARCH.SEARCH:Search…`)
   * ```
   */
  readonly searchLabel = input(t(() => $localize`:@@SI_FILTERED_SEARCH.SEARCH:Search…`));
 
  /**
   * Clear button aria label. Needed for a11y
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_FILTERED_SEARCH.CLEAR:Clear`)
   * ```
   */
  readonly clearButtonLabel = input(t(() => $localize`:@@SI_FILTERED_SEARCH.CLEAR:Clear`));
 
  /**
   * The accessible label of the search button.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_FILTERED_SEARCH.SUBMIT_BUTTON:Apply search criteria`)
   * ```
   */
  readonly submitButtonLabel = input(
    t(() => $localize`:@@SI_FILTERED_SEARCH.SUBMIT_BUTTON:Apply search criteria`)
  );
  /**
   * Items count text appended to the count in case of multi-selection of values.
   * Translation key, `{{itemCount}}` in the translation will be replaced with the actual value.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_FILTERED_SEARCH.ITEM_COUNT:{{itemCount}} selected`)
   * ```
   */
  readonly itemCountText = input<TranslatableString>(
    t(() => $localize`:@@SI_FILTERED_SEARCH.ITEM_COUNT:{{itemCount}} selected`)
  );
  /**
   * Color variant to determine component background
   *
   * @defaultValue 'base-1'
   */
  readonly colorVariant = input<BackgroundColorVariant>('base-1');
  /**
   * Disables the free text search to only use the criterion for filtering.
   *
   * @defaultValue false
   */
  readonly disableFreeTextSearch = input(false, { transform: booleanAttribute });
  /**
   * Limit on the number of criteria/criteria value to be displayed by the typeahead
   *
   * @defaultValue 20
   */
  readonly typeaheadOptionsLimit = input(20);
  /**
   * By default, the Filtered Search will treat `:` as a special character
   * to submit the current input in the freetext and immediately create a criterion.
   * Use this input to disable this behavior.
   *
   * @defaultValue false
   */
  readonly disableSelectionByColonAndSemicolon = input(false, { transform: booleanAttribute });
  /**
   * Criterion definition for free-text pills.
   * When set, free-text values will be added as a pill with this criterion.
   * If not set, free-text pills are disabled.
   *
   * Enabling this will only emit valueChange events when the free-text pill is created.
   * When the text input is blurred and there is text inside, a free-text pill will be created.
   *
   *
   * @experimental
   */
  readonly freeTextCriterion = input<CriterionDefinition>();
  /**
   * The value to be shown for creating free-text pills.
   * Use the `{{query}}` placeholder to show the user input in the label.
   *
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_FILTERED_SEARCH.SEARCH_FOR_FREE_TEXT:Search for "{{query}}"`)
   * ```
   *
   * @experimental
   */
  readonly searchForFreeTextLabel = input(
    t(() => $localize`:@@SI_FILTERED_SEARCH.SEARCH_FOR_FREE_TEXT:Search for "{{query}}"`)
  );
 
  /**
   * The interceptor is called when the list of criteria is shown as soon as the user starts typing in the input field.
   * The interceptor's {@link DisplayedCriteriaEventArgs.allow} method can be used to filter the list of displayed criteria.
   *
   * **Note:** The interceptor is called as long as the {@link searchCriteria} does not exceed {@link maxCriteria}.
   * Further, the interceptor is not called when using the {@link lazyCriterionProvider}.
   *
   * @example
   * ```
   * <si-filtered-search
   *   [criteria]="[{ name: 'foo', label: 'Foo' }, { name: 'bar', label: 'Bar' }]"
   *   (interceptDisplayedCriteria)="$event.allow(
   *       $event.searchCriteria.criteria.some(s => s.name === 'foo')
   *         ? $event.criteria.filter(c => c !== 'foo')
   *         : $event.criteria
   *     )">
   * </si-filtered-search>
   * ```
   */
  readonly interceptDisplayedCriteria = output<DisplayedCriteriaEventArgs>();
 
  private readonly freeTextInput = viewChild.required(SiFilteredSearchInputComponent);
 
  private readonly scrollContainer = viewChild.required('scrollContainer', { read: ElementRef });
 
  private readonly valueComponents = viewChildren(SiFilteredSearchValueComponent);
  protected dataSource: Observable<InternalCriterionDefinition[]>;
 
  protected readonly values = signal<InternalCriterion[]>([]);
  protected readonly maxCriteriaReached = computed(() => {
    const maxCriteria = this.maxCriteria();
    return maxCriteria !== undefined && this.values().length >= maxCriteria;
  });
  protected readonly searchValue = signal('');
  /** Internal criteria model */
  protected internalCriterionDefinitions: InternalCriterionDefinition[] = [];
 
  protected readonly icons = addIcons({ elementCancel, elementSearch });
  /** Used to debounce the Search emissions */
  private searchEmitQueue = new Subject<SearchCriteria | undefined>();
  private readonly destroyRef = inject(DestroyRef);
  private readonly translateService = injectSiTranslateService();
  private readonly locale = inject(LOCALE_ID).toString();
  private readonly freeTextFocused = new Subject<void>();
 
  protected readonly allowFreeTextCache = signal<boolean>(true);
  // Angular also calls ngOnChanges if we emitted a change and then two-way-databinding writes back our own change.
  // We use this to ensure that we do not write our own change back to the input.
 
  private lastEmittedSearchCriteria?: SearchCriteria;
 
  protected readonly isStrictOrOnlySelectValue = computed(() => {
    return this.strictValue() || this.onlySelectValue();
  });
 
  private readonly strictCriterionOrValue = computed(() => {
    return this.strictCriterion() || this.isStrictOrOnlySelectValue();
  });
 
  private readonly lazyLoadedCriteria = signal<CriterionDefinition[] | undefined>(undefined);
  private readonly loadedCriteria = computed(() => {
    const lazyLoadedCriteria = this.lazyLoadedCriteria();
    if (lazyLoadedCriteria) {
      return lazyLoadedCriteria;
    } else {
      return this.criteria() ?? [];
    }
  });
 
  private readonly internalFreeTextCriterion = computed<InternalCriterionDefinition | undefined>(
    () => {
      const freeTextDef = this.freeTextCriterion();
      if (!freeTextDef) {
        return undefined;
      }
      return {
        ...freeTextDef,
        label: freeTextDef.label ?? freeTextDef.name,
        translatedLabel: freeTextDef.label ?? freeTextDef.name,
        type: 'free-text'
      };
    }
  );
 
  constructor() {
    const typeaheadInputChange = merge(
      toObservable(this.searchValue),
      this.freeTextFocused.pipe(map(() => this.searchValue()))
    );
 
    const criteriaRestrictions = toObservable(
      computed(() => ({
        maxCriteria: this.maxCriteria(),
        values: this.values(),
        exclusiveCriteria: this.exclusiveCriteria()
      }))
    );
 
    this.dataSource = toObservable(this.lazyCriterionProvider).pipe(
      switchMap(lazyCriterionProvider => {
        if (lazyCriterionProvider) {
          return typeaheadInputChange.pipe(
            switchMap(value =>
              this.lazyCriterionProvider()!(value, this.searchCriteria()).pipe(
                debounceTime(this.lazyLoadingDebounceTime()),
                map(result => this.getCriteriaToDisplayFromSubscription(result))
              )
            )
          );
        } else {
          return criteriaRestrictions.pipe(
            map(({ maxCriteria, values, exclusiveCriteria }) =>
              this.getFilteredTypeaheadCriteria(maxCriteria, values, exclusiveCriteria)
            )
          );
        }
      }),
      switchMap(criteria => {
        return this.translateService.translateAsync(criteria.map(c => c.label)).pipe(
          map(translations => {
            criteria.forEach(c => (c.translatedLabel = translations[c.label] ?? c.label ?? c.name));
            return criteria;
          })
        );
      })
    );
  }
 
  ngOnChanges(changes: SimpleChanges<this>): void {
    if (changes.criteria) {
      this.initCriteria();
    }
    if (
      (changes.searchCriteria && this.searchCriteria() !== this.lastEmittedSearchCriteria) ||
      changes.criteria
    ) {
      this.initValue();
    }
  }
 
  ngOnInit(): void {
    if (this.strictCriterionOrValue() && this.internalCriterionDefinitions.length === 0) {
      throw new Error('strict criterion mode activated without predefined criteria!');
    }
 
    this.searchEmitQueue
      .pipe(debounceTime(this.searchDebounceTime()), takeUntilDestroyed(this.destroyRef))
      .subscribe(searchCriteria => this.doSearch.emit(searchCriteria!));
  }
 
  private initCriteria(): void {
    this.internalCriterionDefinitions = this.loadedCriteria().map(c => toInternalCriteria(c));
  }
 
  /**
   * Finds a criterion config for a given criterion value.
   * Checks internalCriterionDefinitions first, then freeTextCriterion.
   * Returns undefined if no config was found.
   */
  private findCriterionConfig(
    criterionValue: CriterionValue
  ): InternalCriterionDefinition | undefined {
    const config = this.internalCriterionDefinitions.find(ic => ic.name === criterionValue.name);
 
    if (config) {
      return config;
    }
 
    // Check if this matches the freeTextCriterion
    const freeTextDef = this.internalFreeTextCriterion();
    if (freeTextDef?.name === criterionValue.name) {
      return freeTextDef;
    }
 
    return undefined;
  }
 
  private initValue(): void {
    this.searchValue.set(this.searchCriteria()?.value ?? '');
    this.values.set(
      this.searchCriteria()?.criteria.map(c => {
        const config =
          this.findCriterionConfig(c) ??
          ({
            name: c.name,
            label: c.name,
            translatedLabel: c.name
          } as InternalCriterionDefinition);
 
        let value = c.value ?? '';
        // Fix input, in case the user provided the value as string for the multi-select use case.
        if (config.multiSelect && typeof value === 'string') {
          value = value !== '' ? [value] : [];
        }
 
        const dateValue = this.isDateCriterion(config)
          ? (c.dateValue ?? this.parseModelDate(value))
          : undefined;
 
        return {
          value: {
            name: c.name,
            value,
            ...(dateValue ? { dateValue } : {}),
            ...(c.operator ? { operator: c.operator } : {})
          },
          config,
          editOnCreation: false
        };
      }) ?? []
    );
    this.lastEmittedSearchCriteria = this.searchCriteria();
  }
 
  /**
   * Deletes all currently selected criteria and effectively resets the filtered search.
   */
  deleteAllCriteria(event?: MouseEvent): void {
    Iif (this.disabled()) {
      return;
    }
    event?.stopPropagation();
 
    // Reset search criteria
    this.values.set([]);
    this.searchValue.set('');
    this.emitChangeEvent();
    this.submit();
  }
 
  protected deleteCriterion(index: number, event: { triggerSearch: boolean } | void): void {
    Iif (this.disabled()) {
      return;
    }
 
    // Close any active overlays before deleting the criterion
    // This could happen in case when user has opened a multiselect pill
    // and then clicks on clear button of other pill.
    this.valueComponents().forEach(component => {
      component.closeOverlay();
    });
 
    this.values.update(v => v.filter((_, i) => i !== index));
    this.emitChangeEvent();
    if (this.values().length !== index) {
      this.valueComponents()[index + 1].edit('value');
    } else {
      this.freeTextInput().focus();
    }
    if (event?.triggerSearch) {
      this.submit();
    }
  }
 
  protected submit(): void {
    if (!this.doSearchOnInputChange()) {
      this.doSearch.emit(this.searchCriteria()!);
    }
  }
 
  protected validateCriterionLabel(criterion: InternalCriterionDefinition): boolean {
    if (!this.strictCriterionOrValue()) {
      return true;
    }
    return this.internalCriterionDefinitions.includes(criterion);
  }
 
  /**
   * Converts the internally used data model to the external model.
   * In case options for Criterion is Option[] map to the value from the label.
   */
  private convertToExternalModel(): SearchCriteria {
    const correctedCriteria: SearchCriteria = {
      value: this.searchValue(),
      criteria: this.values().map(v => v.value)
    };
    // When free text search is disabled or free text pills are being used,
    // we must not return any free text value.
    if (this.disableFreeTextSearch() || this.freeTextCriterion()) {
      correctedCriteria.value = '';
    }
    return correctedCriteria;
  }
 
  private addCriterion(
    config: InternalCriterionDefinition,
    value?: string,
    editOnCreation = true
  ): boolean {
    if (this.maxCriteriaReached()) {
      return false;
    }
 
    const criterionValue: CriterionValue = { name: config.name, value: value ?? '' };
    let initialValueText: string | undefined;
 
    if (config.type === 'free-text') {
      this.getAllowedCriteria(this.values(), this.exclusiveCriteria());
      if (!this.allowFreeTextCache()) {
        return false;
      }
    } else {
      if (
        !this.validateCriterionLabel(config) ||
        (this.internalCriterionDefinitions.includes(config) &&
          !this.getAllowedCriteria(this.values(), this.exclusiveCriteria()).includes(config))
      ) {
        return false;
      }
 
      initialValueText = value;
      if (this.isDateCriterion(config)) {
        const dateValue = this.parseInputDate(value, config);
        if (!dateValue) {
          return false;
        }
        criterionValue.dateValue = dateValue;
        criterionValue.value = value
          ? value.trim()
          : formatDate(
              dateValue,
              getDatepickerFormat(this.locale, config.datepickerConfig),
              this.locale
            );
      } else {
        criterionValue.value = this.resolveValue(value, config);
      }
    }
 
    const criterion = {
      config,
      value: criterionValue,
      editOnCreation,
      initialValueText
    };
    this.values.update(values => [...values, criterion]);
    this.emitChangeEvent();
    return true;
  }
 
  private resolveValue(
    value: string | undefined,
    config: InternalCriterionDefinition
  ): string | string[] {
    const trimmedValue = value?.trim() ?? '';
    const matchingOption = trimmedValue
      ? findOption(
          trimmedValue,
          toTranslatedOptions(config.options, label => this.translateService.translateSync(label)),
          true
        )
      : undefined;
    const normalizedValue = matchingOption?.value ?? trimmedValue;
    if (config.multiSelect) {
      return normalizedValue ? [normalizedValue] : [];
    }
    return normalizedValue;
  }
 
  private isDateCriterion(
    config: InternalCriterionDefinition
  ): config is InternalCriterionDefinition & { validationType: 'date' | 'date-time' } {
    return config.validationType === 'date' || config.validationType === 'date-time';
  }
 
  private parseModelDate(value: CriterionValue['value']): Date | undefined {
    const dateValue = value ? new Date(value.toString()) : new Date();
    return isValid(dateValue) ? dateValue : undefined;
  }
 
  private parseInputDate(
    value: string | undefined,
    config: InternalCriterionDefinition
  ): Date | undefined {
    if (!value) {
      return new Date();
    }
    const format = getDatepickerFormat(this.locale, config.datepickerConfig);
    const dateValue = parseDate(value, format, this.locale);
    return isValid(dateValue) ? dateValue : undefined;
  }
 
  private getAllowedCriteria(
    values: InternalCriterion[],
    exclusiveCriteria: boolean
  ): InternalCriterionDefinition[] {
    const allowedCriteria = !exclusiveCriteria
      ? this.internalCriterionDefinitions
      : differenceByName(this.internalCriterionDefinitions, values);
 
    let allowedCriterionNames = allowedCriteria.map(c => c.name);
    if (!this.lazyCriterionProvider()) {
      this.interceptDisplayedCriteria.emit({
        criteria: allowedCriterionNames,
        searchCriteria: this.convertToExternalModel(),
        allow: (criteriaNamesToDisplay, allowFreeTextSearch) => {
          allowedCriterionNames = criteriaNamesToDisplay;
          if (allowFreeTextSearch !== undefined) {
            this.allowFreeTextCache.set(allowFreeTextSearch);
          }
        }
      });
    }
 
    return allowedCriteria.filter(c => allowedCriterionNames.includes(c.name));
  }
 
  /**
   * Get criteria list to be shown in typeahead.
   * @returns list of criteria to be shown in typeahead.
   */
  private getFilteredTypeaheadCriteria(
    maxCriteria: number | undefined,
    values: InternalCriterion[],
    exclusiveCriteria: boolean
  ): InternalCriterionDefinition[] {
    if (maxCriteria === undefined || values.length < maxCriteria) {
      return this.getAllowedCriteria(values, exclusiveCriteria);
    } else {
      return [];
    }
  }
 
  private getCriteriaToDisplayFromSubscription(
    result: CriterionDefinition[]
  ): InternalCriterionDefinition[] {
    this.lazyLoadedCriteria.set(result);
    this.internalCriterionDefinitions = this.loadedCriteria().map(c => toInternalCriteria(c));
    // It's necessary to update the criteria configuration since consuming applications may change the options.
    // A common case are criteria which depend on each other like Country, Site and Building. If the user change
    // the site the building options might become invalid.
    // KEEP THE REFERENCE, otherwise CD is broken
    this.values.update(currentValues =>
      currentValues.map(v =>
        Object.assign(v, {
          value: v.value,
          config: this.findCriterionConfig(v.value) ?? v.config
        })
      )
    );
 
    return this.getFilteredTypeaheadCriteria(
      this.maxCriteria(),
      this.values(),
      this.exclusiveCriteria()
    );
  }
 
  protected freeTextFocus(): void {
    // Ensure that the free text input is fully visible in the scroll container
    const scrollDirection = isRTL() ? -1 : 1;
    const position = scrollDirection * this.scrollContainer().nativeElement.scrollWidth;
    this.scrollContainer().nativeElement.scrollLeft = position;
    this.freeTextFocused.next();
  }
 
  protected freeTextBackspace(): void {
    // edit last criterion if a user presses backspace in empty search input.
    const valueComponents = this.valueComponents();
    Eif (valueComponents.length) {
      valueComponents[valueComponents.length - 1].edit('value');
    }
  }
 
  protected onCreateCriterion(event: {
    criterion: InternalCriterionDefinition;
    value?: string;
    accept: () => void;
  }): void {
    if (this.addCriterion(event.criterion, event.value)) {
      event.accept();
    }
  }
 
  protected onCreateCriterionByName(event: {
    criterionName: string;
    value?: string;
    editOnCreation?: boolean;
    accept: () => void;
  }): void {
    const normalizedName = event.criterionName.toLocaleLowerCase();
    const configuredCriterion = this.internalCriterionDefinitions.find(
      criterion => criterion.translatedLabel.toLocaleLowerCase() === normalizedName
    );
    const config = configuredCriterion ?? toInternalCriteria({ name: event.criterionName });
    if (this.addCriterion(config, event.value, event.editOnCreation)) {
      event.accept();
    }
  }
 
  protected onSearchValueChange(): void {
    // Only emit a change event if free text pills are not enabled and the free text search is enabled.
    if (!this.disableFreeTextSearch() && !this.freeTextCriterion()) {
      this.emitChangeEvent();
    }
  }
 
  protected valueChange(value: CriterionValue, criterion: InternalCriterion): void {
    criterion.value = value;
    this.emitChangeEvent();
  }
 
  protected focusNext(index: number, event: { freeText: string } | void): void {
    const next = this.valueComponents()[index + 1];
    if (next) {
      next.edit();
    } else {
      this.searchValue.set(event?.freeText ?? this.searchValue());
      this.freeTextInput().focus();
    }
  }
 
  private updateAndEmitSearchCriteria(): void {
    this.searchCriteria.set(this.convertToExternalModel());
    this.lastEmittedSearchCriteria = this.searchCriteria();
  }
 
  private emitChangeEvent(): void {
    this.updateAndEmitSearchCriteria();
    if (this.doSearchOnInputChange()) {
      this.searchEmitQueue.next(this.searchCriteria());
    }
  }
 
  protected createFreeTextPill(event: { query: string; accept: () => void }): void {
    const freeTextDefinition = this.internalFreeTextCriterion();
    if (freeTextDefinition && this.addCriterion(freeTextDefinition, event.query, false)) {
      event.accept();
    }
  }
}