All files / select si-select.component.ts

91.3% Statements 42/46
93.33% Branches 14/15
88.88% Functions 8/9
90.9% Lines 40/44

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                                                                                                              1x 1x                 114x           114x           114x                 114x                 114x 114x     114x           114x           114x   114x   114x   114x         114x         114x         114x               114x                     114x   114x 114x 114x   114x 114x             114x     118x 11x         114x         40x 5x   35x 35x 35x         18x 18x 18x         18x 18x                 125x           3x            
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { CdkOverlayOrigin, OverlayModule } from '@angular/cdk/overlay';
import {
  AfterContentInit,
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  contentChild,
  ElementRef,
  inject,
  input,
  OnChanges,
  output,
  signal,
  SimpleChanges,
  TemplateRef,
  viewChild
} from '@angular/core';
import { SI_FORM_ITEM_CONTROL, SiFormItemControl } from '@siemens/element-ng/form';
import { t, TranslatableString } from '@siemens/element-translate-ng/translate';
 
import { SiSelectComplexOptionsDirective } from './options/si-select-complex-options.directive';
import { SI_SELECT_OPTIONS_STRATEGY } from './options/si-select-options-strategy';
import { SiSelectInputComponent } from './select-input/si-select-input.component';
import { SiSelectListHasFilterComponent } from './select-list/si-select-list-has-filter.component';
import { SiSelectListComponent } from './select-list/si-select-list.component';
import { SiSelectSelectionStrategy } from './selection/si-select-selection-strategy';
import { SiSelectActionsDirective } from './si-select-actions.directive';
import { SiSelectGroupTemplateDirective } from './si-select-group-template.directive';
import { SiSelectOptionTemplateDirective } from './si-select-option-template.directive';
import { SelectGroup, SelectItem, SelectOption } from './si-select.types';
 
@Component({
  selector: 'si-select',
  imports: [
    OverlayModule,
    SiSelectInputComponent,
    SiSelectListComponent,
    SiSelectListHasFilterComponent
  ],
  templateUrl: './si-select.component.html',
  styleUrl: './si-select.component.scss',
  providers: [{ provide: SI_FORM_ITEM_CONTROL, useExisting: SiSelectComponent }],
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    class: 'dropdown',
    '[class.readonly]': 'readonly()',
    '[class.open]': 'isOpen()',
    '[class.si-select-has-filter]': 'hasFilter()'
  }
})
export class SiSelectComponent<T> implements OnChanges, AfterContentInit, SiFormItemControl {
  private static idCounter = 0;
  /**
   * Unique identifier.
   *
   * @defaultValue
   * ```
   * `__si-select-${SiSelectComponent.idCounter++}`
   * ```
   */
  readonly id = input(`__si-select-${SiSelectComponent.idCounter++}`);
  /**
   * Aria label of the select.
   *
   * @defaultValue null
   */
  readonly ariaLabel = input<string | null>(null);
  /**
   * Aria labelledby of the select.
   * @defaultValue undefined
   */
  // eslint-disable-next-line @angular-eslint/no-input-rename
  readonly labelledbyInput = input<string | undefined>(undefined, { alias: 'labelledby' });
  /**
   * Placeholder for search input field.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_SELECT.SEARCH-PLACEHOLDER:Search...`)
   * ```
   */
  readonly filterPlaceholder = input(t(() => $localize`:@@SI_SELECT.SEARCH-PLACEHOLDER:Search...`));
  /**
   * Label if no item can be found.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_SELECT.NO-RESULTS-FOUND:No results found`)
   * ```
   */
  readonly noResultsFoundLabel = input(
    t(() => $localize`:@@SI_SELECT.NO-RESULTS-FOUND:No results found`)
  );
  /** Placeholder text to display when no options are selected. */
  readonly placeholder = input<TranslatableString>();
  /**
   * Readonly state. Similar to disabled but with higher contrast *
   *
   * @defaultValue false
   */
  readonly readonly = input(false, { transform: booleanAttribute });
 
  /**
   * Emits on selection dropdown close.
   * @deprecated Use {@link openChange} instead.
   */
  readonly dropdownClose = output<void>();
  /** Emits when the dropdown open state changes. */
  readonly openChange = output<boolean>();
 
  protected readonly isOpen = signal(false);
 
  protected readonly optionTemplate = contentChild<
    SiSelectOptionTemplateDirective,
    TemplateRef<{ $implicit: SelectOption<T> }>
  >(SiSelectOptionTemplateDirective, { read: TemplateRef });
 
  protected readonly groupTemplate = contentChild<
    SiSelectGroupTemplateDirective,
    TemplateRef<{ $implicit: SelectGroup<T> }>
  >(SiSelectGroupTemplateDirective, { read: TemplateRef });
 
  protected readonly actionsTemplate = contentChild<SiSelectActionsDirective, TemplateRef<any>>(
    SiSelectActionsDirective,
    { read: TemplateRef }
  );
 
  private readonly trigger = viewChild.required<CdkOverlayOrigin, ElementRef<HTMLDivElement>>(
    CdkOverlayOrigin,
    {
      read: ElementRef
    }
  );
 
  /** @internal */
  readonly labelledby = computed(() => this.labelledbyInput() ?? this.id() + '-label');
  /**
   * This ID will be bound to the `aria-describedby` attribute of the select.
   * Use this to reference the element containing the error message(s) for the select.
   * It will be picked by the {@link SiFormItemComponent} if the select is used inside a form item.
   *
   * @defaultValue
   * ```
   * `${this.id()}-errormessage`
   * ```
   */
  readonly errormessageId = input(`${this.id()}-errormessage`);
 
  protected rows: readonly SelectItem<T>[] = [];
  protected overlayWidth = 0;
  protected readonly selectionStrategy = inject(SiSelectSelectionStrategy<T>);
 
  private backdropClicked = false;
  private readonly selectOptions = inject(SI_SELECT_OPTIONS_STRATEGY);
 
  /**
   * Enables the filter input
   * @defaultValue false
   * @defaultref {@link SiSelectComponent#_hasFilter}
   */
  readonly hasFilter = input(false, { transform: booleanAttribute });
 
  ngOnChanges(changes: SimpleChanges): void {
    if (changes.hasFilter && this.hasFilter()) {
      this.verifyValueProvider();
    }
  }
 
  ngAfterContentInit(): void {
    this.verifyValueProvider();
  }
 
  /** Opens the `si-select`. */
  open(): void {
    if (this.readonly() || this.selectionStrategy.disabled()) {
      return;
    }
    this.overlayWidth = this.trigger().nativeElement.getBoundingClientRect().width + 2; // 2px border
    this.isOpen.set(true);
    this.openChange.emit(true);
  }
 
  /** Closes the `si-select`. */
  close(): void {
    this.isOpen.set(false);
    if (!this.backdropClicked) {
      this.trigger().nativeElement.focus();
    } else E{
      this.backdropClicked = false;
      this.selectionStrategy.onTouched();
    }
    this.dropdownClose.emit();
    this.openChange.emit(false);
  }
 
  protected backdropClick(): void {
    this.backdropClicked = true;
    this.isOpen.set(false);
  }
 
  private verifyValueProvider(): void {
    if (
      this.hasFilter() &&
      this.optionTemplate() &&
      this.selectOptions instanceof SiSelectComplexOptionsDirective &&
      !this.selectOptions.valueProvider()
    ) {
      console.error(
        'A valueProvider is required when [hasFilter]="true" and having custom option template on si-select'
      );
    }
  }
}