All files / tabs si-tab.component.ts

100% Statements 16/16
100% Branches 9/9
100% Functions 3/3
100% Lines 16/16

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                                                                      1x           43x           43x         43x     6x 6x 5x           7x 7x 2x 2x 1x     6x 6x 6x         1x      
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { ChangeDetectionStrategy, Component, input, model, OnDestroy } from '@angular/core';
import { SiIconComponent } from '@siemens/element-ng/icon';
import { SiTranslatePipe } from '@siemens/element-translate-ng/translate';
 
import { SiTabBadgeComponent } from './si-tab-badge.component';
import { SiTabBaseDirective } from './si-tab-base.directive';
 
/**
 * Creates a normal tab that can contain any content.
 *
 * @example
 * ```html
 * <si-tabset>
 *   <si-tab heading="Tab 1">
 *     <p>Content of Tab 1</p>
 *   </si-tab>
 * </si-tabset>
 * ```
 */
@Component({
  selector: 'si-tab',
  imports: [SiIconComponent, SiTranslatePipe, SiTabBadgeComponent],
  templateUrl: './si-tab.component.html',
  styleUrl: './si-tab.component.scss',
  providers: [{ provide: SiTabBaseDirective, useExisting: SiTabComponent }],
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    '(click)': 'selectTabByUser()',
    '(keydown.enter)': 'selectTabByUser()'
  }
})
export class SiTabComponent extends SiTabBaseDirective implements OnDestroy {
  /**
   * Whether the tab is active or not.
   * If set to `true`, the tab will be selected and its content will be displayed.
   * @defaultValue false
   * */
  override readonly active = model(false);
 
  /**
   * Guard to check if the tab can be activated.
   * If not provided, the tab can always be activated.
   */
  readonly canActivate = input<() => boolean>();
  /**
   * Guard to check if the tab can be deactivated.
   * If not provided, the tab can always be deactivated.
   */
  readonly canDeactivate = input<() => boolean>();
 
  protected selectTabByUser(): void {
    const canActivate = this.canActivate();
    if (!this.active() && (canActivate ? canActivate() : true)) {
      this.selectTab();
    }
  }
 
  /** {@inheritDoc} */
  override selectTab(retainFocus?: boolean): void {
    const activeTab = this.tabset.activeTab();
    if (activeTab instanceof SiTabComponent) {
      const canDeactivate = activeTab?.canDeactivate();
      if (canDeactivate ? !canDeactivate() : false) {
        return;
      }
    }
    this.tabset.activeTab()?.deSelectTab();
    this.active.set(true);
    super.selectTab(retainFocus);
  }
 
  /** @internal */
  override deSelectTab(): void {
    this.active.set(false);
  }
}