All files / accordion si-collapsible-panel.component.ts

92.3% Statements 48/52
70% Branches 14/20
90% Functions 9/10
92.15% Lines 47/51

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                                                        1x                                                                     1x       38x           38x           38x           38x           38x       38x           38x   38x         38x       38x           38x   38x 33x   38x 38x 38x 38x 38x   38x 38x 38x     38x 38x 38x 38x     38x 38x     8x   5x       49x 43x   6x                 23x 23x   23x 15x 15x     8x         12x       12x 12x 12x 12x 12x 12x                      
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { animate, query, style, transition, trigger } from '@angular/animations';
import { NgClass } from '@angular/common';
import {
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  DestroyRef,
  ElementRef,
  inject,
  input,
  model,
  output,
  viewChild
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { areAnimationsDisabled, BackgroundColorVariant } from '@siemens/element-ng/common';
import { addIcons, elementDown2, SiIconComponent } from '@siemens/element-ng/icon';
import { SiTranslatePipe, TranslatableString } from '@siemens/element-translate-ng/translate';
import { filter } from 'rxjs';
 
import { SiAccordionHCollapseService } from './si-accordion-hcollapse.service';
import { SiAccordionService } from './si-accordion.service';
 
let controlIdCounter = 1;
 
@Component({
  selector: 'si-collapsible-panel',
  imports: [NgClass, SiIconComponent, SiTranslatePipe],
  templateUrl: './si-collapsible-panel.component.html',
  styleUrl: './si-collapsible-panel.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    '[class]': 'colorVariant()',
    '[class.opened]': 'opened()',
    '[class.hcollapsed]': 'hcollapsed()',
    '[class.full-height]': 'fullHeight()'
  },
  animations: [
    trigger('showHide', [
      transition('*=>hide', [
        style({ overflow: 'hidden' }),
        query(
          ':leave',
          [style({ blockSize: '*' }), animate('0.5s ease', style({ blockSize: '0' }))],
          { optional: true }
        )
      ]),
      transition('*=>show', [
        style({ overflow: 'hidden' }),
        query(
          ':enter',
          [style({ blockSize: '0' }), animate('0.5s ease', style({ blockSize: '*' }))],
          { optional: true }
        )
      ])
    ])
  ]
})
export class SiCollapsiblePanelComponent {
  /**
   * Heading for the collapsible panel.
   */
  readonly heading = input<TranslatableString>();
  /**
   * Additional CSS classes for the top element.
   *
   * @defaultValue ''
   */
  readonly headerCssClasses = input('');
  /**
   * Additional CSS classes for the collapsible content region.
   *
   * @defaultValue ''
   */
  readonly contentBgClasses = input('');
  /**
   * Additional CSS classes for the wrapping content element.
   *
   * @defaultValue ''
   */
  readonly contentCssClasses = input('');
  /**
   * Expand/collapse the panel.
   *
   * @defaultValue false
   */
  readonly opened = model(false);
  /**
   * The icon to be displayed besides the heading.
   */
  readonly icon = input<string>();
  /**
   * Whether the si-collapsible-panel is disabled.
   *
   * @defaultValue false
   */
  readonly disabled = input(false, { transform: booleanAttribute });
  /** Color to use for component background */
  readonly colorVariant = input<BackgroundColorVariant>();
  /**
   * Defines the content of the optional badge. Should be a number or something like "100+".
   * if undefined or empty string, no badge is displayed
   */
  readonly badge = input<string | number>();
  /**
   * Defines the background color of the badge. Default is specific to Element flavour.
   */
  readonly badgeColor = input<string>();
 
  /**
   * An event emitted when the user triggered expand/collapse and emit with the new open state.
   * The event is emitted before the animation happens.
   */
  readonly panelToggle = output<boolean>();
 
  protected readonly hcollapsed = computed(
    () => this.accordionHCollapseService?.hcollapsed() ?? false
  );
  protected readonly fullHeight = computed(() => this.accordionService?.fullHeight() ?? false);
  protected controlId = '__si-collapsible-' + controlIdCounter++;
  protected headerId = this.controlId + '-header';
  protected isHCollapsible = false;
  protected readonly icons = addIcons({ elementDown2 });
 
  private readonly destroyRef = inject(DestroyRef);
  private readonly accordionService = inject(SiAccordionService, { optional: true });
  private readonly accordionHCollapseService = inject(SiAccordionHCollapseService, {
    optional: true
  });
  private enableAnimation = true;
  private readonly animationsGloballyDisabled = areAnimationsDisabled();
  private lastScrollPos = 0;
  private readonly contentRef = viewChild.required<ElementRef<HTMLElement>>('content');
 
  constructor() {
    this.isHCollapsible = !!this.accordionHCollapseService;
    this.accordionService?.toggle$
      .pipe(
        takeUntilDestroyed(this.destroyRef),
        filter(item => item !== this)
      )
      .subscribe(() => this.openClose(false));
  }
 
  protected get showHide(): string {
    if (this.enableAnimation && !this.animationsGloballyDisabled) {
      return this.opened() ? 'show' : 'hide';
    }
    return 'disabled';
  }
 
  /**
   * Expand/collapse panel.
   * @param open - indicate the panel shall open or close
   * @param enableAnimation - with animation
   */
  openClose(open: boolean, enableAnimation = true): void {
    this.opened.set(open);
    this.enableAnimation = enableAnimation;
 
    if (open) {
      setTimeout(() => {
        this.contentRef().nativeElement.scrollTop = this.lastScrollPos;
      });
    } else {
      this.lastScrollPos = this.contentRef().nativeElement.scrollTop;
    }
  }
 
  protected doToggle(event?: Event): void {
    Iif (this.disabled()) {
      return;
    }
 
    event?.preventDefault();
    const opened = this.opened();
    this.panelToggle.emit(!opened);
    this.openClose(this.hcollapsed() || !opened);
    this.accordionService?.toggle$.next(this);
    Iif (this.hcollapsed()) {
      this.accordionHCollapseService?.open$.next(this);
    }
  }
 
  protected keydown(event: KeyboardEvent): void {
    Iif (event.key === 'Enter' || event.key === 'Space' || event.key === ' ') {
      this.doToggle(undefined);
    }
  }
}