All files / sort-bar si-sort-bar.component.ts

100% Statements 17/17
100% Branches 4/4
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                                                  1x                 4x       4x       4x           4x   4x 4x 4x     4x 4x 4x         7x 2x     7x   7x       7x      
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { HttpParams } from '@angular/common/http';
import { Component, input, OnInit, output } from '@angular/core';
import {
  addIcons,
  elementSortDown,
  elementSortUp,
  SiIconComponent
} from '@siemens/element-ng/icon';
import { SiTranslatePipe, t, TranslatableString } from '@siemens/element-translate-ng/translate';
 
export interface SortCriteria {
  name: TranslatableString;
  key: number | string;
}
 
@Component({
  selector: 'si-sort-bar',
  imports: [SiIconComponent, SiTranslatePipe],
  templateUrl: './si-sort-bar.component.html',
  styleUrl: './si-sort-bar.component.scss'
})
export class SiSortBarComponent implements OnInit {
  /**
   * Custom sort title.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_SORT_BAR.TITLE:Sort by`)
   * ```
   */
  readonly sortTitle = input(t(() => $localize`:@@SI_SORT_BAR.TITLE:Sort by`));
  /**
   * List of sort criteria.
   */
  readonly sortCriteria = input.required<SortCriteria[]>();
  /**
   * `key` which sortCriteria is active by default.
   */
  readonly defaultSortCriteria = input.required<SortCriteria['key']>();
 
  /**
   * Output callback event will provide you with a HttpParams object if active
   * sortCriteria change.
   */
  readonly sortChange = output<HttpParams>();
 
  protected readonly icons = addIcons({ elementSortDown, elementSortUp });
  protected activeSortCriteria: SortCriteria['key'] = '';
  protected sortIsDescending = false;
 
  ngOnInit(): void {
    const defaultSortCriteria = this.defaultSortCriteria();
    if (defaultSortCriteria) {
      this.setActive(defaultSortCriteria);
    }
  }
 
  protected setActive(key: SortCriteria['key']): void {
    if (this.activeSortCriteria === key) {
      this.sortIsDescending = !this.sortIsDescending;
    }
 
    this.activeSortCriteria = key;
 
    const searchParams = new HttpParams()
      .set('sort', this.activeSortCriteria)
      .set('order', this.sortIsDescending ? 'desc' : 'asc');
 
    this.sortChange.emit(searchParams);
  }
}