All files / column-selection-dialog si-column-selection-dialog.component.ts

93% Statements 93/100
83.33% Branches 15/18
94.11% Functions 32/34
93.54% Lines 87/93

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                                                                              1x                                             1x 17x 17x 17x             17x 17x               17x 17x               17x 17x               17x 17x               17x 17x     17x 17x             17x               17x     17x                   17x 17x                 17x     17x                   17x 17x     17x   17x   17x   17x   17x     17x   17x   17x 17x     17x                 2x       1x 5x 1x       1x 1x 1x 1x         1x       1x 1x           1x 1x 1x 1x 1x       1x 1x 1x           1x                   1x 1x             1x 1x               3x 3x 3x 3x 2x     3x 2x 2x   2x 2x 2x   1x           6x       1x 5x 3x 1x 5x   1x       17x 75x 75x       3x             1x       4x 4x     4x        
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { LiveAnnouncer } from '@angular/cdk/a11y';
import {
  CDK_DRAG_CONFIG,
  CdkDrag,
  CdkDragDrop,
  CdkDropList,
  moveItemInArray
} from '@angular/cdk/drag-drop';
import { CdkListbox, CdkOption } from '@angular/cdk/listbox';
import { CdkScrollableModule } from '@angular/cdk/scrolling';
import {
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  ElementRef,
  inject,
  input,
  model,
  OnInit,
  viewChild,
  viewChildren
} from '@angular/core';
import { addIcons, elementCancel, SiIconComponent } from '@siemens/element-ng/icon';
import { ModalRef } from '@siemens/element-ng/modal';
import {
  injectSiTranslateService,
  SiTranslatePipe,
  t,
  TranslatableString
} from '@siemens/element-translate-ng/translate';
import { first } from 'rxjs/operators';
 
import { SiColumnSelectionEditorComponent } from './column-selection-editor/si-column-selection-editor.component';
import { Column, ColumnSelectionDialogResult } from './si-column-selection-dialog.types';
 
const dragConfig = {
  dragStartThreshold: 0,
  pointerDirectionChangeThreshold: 5,
  zIndex: 10000
};
 
@Component({
  selector: 'si-column-selection-dialog',
  imports: [
    CdkDrag,
    CdkDropList,
    CdkListbox,
    CdkOption,
    CdkScrollableModule,
    SiIconComponent,
    SiTranslatePipe,
    SiColumnSelectionEditorComponent
  ],
  templateUrl: './si-column-selection-dialog.component.html',
  styleUrl: './si-column-selection-dialog.component.scss',
  providers: [{ provide: CDK_DRAG_CONFIG, useValue: dragConfig }],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class SiColumnSelectionDialogComponent implements OnInit {
  readonly titleId = input<string>();
  readonly heading = input<TranslatableString>();
  readonly bodyTitle = input<TranslatableString>();
  /**
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_COLUMN_SELECTION_DIALOG.SUBMIT:Apply`)
   * ```
   */
  readonly submitBtnName = input<TranslatableString>(
    t(() => $localize`:@@SI_COLUMN_SELECTION_DIALOG.SUBMIT:Apply`)
  );
  /**
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_COLUMN_SELECTION_DIALOG.CANCEL:Cancel`)
   * ```
   */
  readonly cancelBtnName = input<TranslatableString>(
    t(() => $localize`:@@SI_COLUMN_SELECTION_DIALOG.CANCEL:Cancel`)
  );
  /**
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_COLUMN_SELECTION_DIALOG.RESTORE_TO_DEFAULT:Restore to default`)
   * ```
   */
  readonly restoreToDefaultBtnName = input<TranslatableString>(
    t(() => $localize`:@@SI_COLUMN_SELECTION_DIALOG.RESTORE_TO_DEFAULT:Restore to default`)
  );
  /**
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_COLUMN_SELECTION_DIALOG.HIDDEN:Hidden`)
   * ```
   */
  readonly hiddenText = input<TranslatableString>(
    t(() => $localize`:@@SI_COLUMN_SELECTION_DIALOG.HIDDEN:Hidden`)
  );
  /**
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_COLUMN_SELECTION_DIALOG.VISIBLE:Visible`)
   * ```
   */
  readonly visibleText = input<TranslatableString>(
    t(() => $localize`:@@SI_COLUMN_SELECTION_DIALOG.VISIBLE:Visible`)
  );
  /** @defaultValue false */
  readonly restoreEnabled = input(false, { transform: booleanAttribute });
  readonly columns = model.required<Column[]>();
  /**
   * @defaultValue
   * ```
   * {}
   * ```
   */
  readonly translationParams = input<Record<string, unknown>>({});
 
  /**
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_COLUMN_SELECTION_DIALOG.LIST_ARIA_LABEL:List of possible columns. Items can be moved using Alt+ArrowUp or Alt+ArrowDown. Press Enter to rename supported items.`)
   * ```
   */
  readonly listAriaLabel = input(
    t(
      () =>
        $localize`:@@SI_COLUMN_SELECTION_DIALOG.LIST_ARIA_LABEL:List of possible columns. Items can be moved using Alt+ArrowUp or Alt+ArrowDown. Press Enter to rename supported items.`
    )
  );
 
  /**
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_COLUMN_SELECTION_DIALOG.RENAME_INPUT_ARIA_LABEL:Rename column`)
   * ```
   */
  readonly renameInputAriaLabel = input(
    t(() => $localize`:@@SI_COLUMN_SELECTION_DIALOG.RENAME_INPUT_ARIA_LABEL:Rename column`)
  );
 
  /**
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_COLUMN_SELECTION_DIALOG.ITEM_MOVED:Item is now at position {{targetPosition}}`)
   * ```
   */
  readonly a11yItemMovedMessage = input<TranslatableString>(
    t(
      () =>
        $localize`:@@SI_COLUMN_SELECTION_DIALOG.ITEM_MOVED:Item is now at position {{targetPosition}}`
    )
  );
  /**
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_COLUMN_SELECTION_DIALOG.ITEM_NOT_MOVED:Item was not moved`)
   * ```
   */
 
  readonly a11yItemNotMovedMessage = input<TranslatableString>(
    t(() => $localize`:@@SI_COLUMN_SELECTION_DIALOG.ITEM_NOT_MOVED:Item was not moved`)
  );
  /** @defaultValue true */
  readonly columnVisibilityConfigurable = input(true, { transform: booleanAttribute });
 
  private readonly listOptions = viewChildren(CdkOption);
 
  private readonly modalBodyElement = viewChild.required<ElementRef<HTMLDivElement>>('modalBody');
 
  private tempHeaderData: Column[] = [];
 
  protected readonly modalRef = inject(
    ModalRef<SiColumnSelectionDialogComponent, ColumnSelectionDialogResult>
  );
  protected readonly icons = addIcons({ elementCancel });
 
  protected visibleIds: string[] = [];
 
  private readonly liveAnnouncer = inject(LiveAnnouncer);
  private readonly translateService = injectSiTranslateService();
 
  ngOnInit(): void {
    this.setupColumnData();
  }
 
  /** @internal */
  get backupColumns(): Column[] {
    return this.tempHeaderData;
  }
 
  protected submitColumnSelection(): void {
    this.modalRef.hide({ type: 'ok', columns: this.columns() });
  }
 
  protected cancelColumnSelection(): void {
    this.columns.set([]);
    this.tempHeaderData.forEach(element => this.columns.update(a => [...a, element]));
    this.modalRef.hide({ type: 'cancel', columns: this.columns() });
  }
 
  protected drop(event: CdkDragDrop<string[]>): void {
    const columns = this.columns();
    if (columns[event.currentIndex].draggable) {
      moveItemInArray(columns, event.previousIndex, event.currentIndex);
      this.emitChange();
    }
  }
 
  protected restoreToDefault(): void {
    this.modalRef.hidden.next({
      type: 'restoreDefault',
      columns: this.columns(),
      updateColumns: columns => {
        this.columns.set(columns);
        this.setupColumnData();
      }
    });
  }
 
  protected moveDown(index: number, event: Event): void {
    const columns = this.columns();
    const listOptions = this.listOptions();
    if (columns[index].draggable) {
      let targetIndex = index + 1;
      while (columns[targetIndex] && !columns[targetIndex].draggable) {
        targetIndex++;
      }
 
      if (targetIndex !== index && columns[targetIndex]?.draggable) {
        event.preventDefault();
        moveItemInArray(columns, index, targetIndex);
 
        // When moving the first partially visible item down,
        // the browser tries to keep its position stable within the viewport by automatically scrolling down.
        // This behavior is not wanted here, so we restore the previous scroll after moving the item
        // TODO: check if this could be solved easier
        Iif (
          listOptions.at(index)!.element.getBoundingClientRect().top <=
          this.modalBodyElement().nativeElement.getBoundingClientRect().top
        ) {
          const previousScrollTop = this.modalBodyElement().nativeElement.scrollTop;
          setTimeout(() => (this.modalBodyElement().nativeElement.scrollTop = previousScrollTop));
        }
 
        // When moving the last visible element down, the scroll position is not adopted. So its scroll out of view.
        // We correct this manually by scrolling it back into view
        const targetElement = listOptions.at(targetIndex)!.element;
        Iif (
          targetElement.getBoundingClientRect().bottom >
          this.modalBodyElement().nativeElement.getBoundingClientRect().bottom
        ) {
          targetElement.scrollIntoView({ block: 'end' });
        }
 
        this.announceSuccessfulMove(targetIndex);
        this.emitChange();
      } else E{
        this.announceNotSuccessfulMove();
      }
    }
  }
 
  protected moveUp(index: number, event: Event): void {
    const columns = this.columns();
    if (columns[index].draggable) {
      let targetIndex = index - 1;
      while (columns[targetIndex] && !columns[targetIndex].draggable) {
        targetIndex--;
      }
 
      if (targetIndex !== index && columns[targetIndex]?.draggable) {
        event.preventDefault();
        moveItemInArray(columns, index, targetIndex);
        // it seems like this is only necessary for move up. Don't know why
        setTimeout(() => this.listOptions().at(targetIndex)!.focus());
        this.announceSuccessfulMove(targetIndex);
        this.emitChange();
      } else {
        this.announceNotSuccessfulMove();
      }
    }
  }
 
  protected emitChange(): void {
    this.modalRef.hidden.next({ type: 'instant', columns: this.columns() });
  }
 
  protected updateVisibility(): void {
    const value = this.listOptions()
      .filter(option => option.isSelected())
      .map(option => option.value);
    for (const column of this.columns()) {
      column.visible = value.includes(column.id);
    }
    this.emitChange();
  }
 
  private setupColumnData(): void {
    const columns = this.columns();
    this.tempHeaderData = columns.map(x => Object.assign({}, x));
    this.visibleIds = columns.filter(column => column.visible).map(column => column.id);
  }
 
  private announceSuccessfulMove(index: number): void {
    this.announceMove(this.a11yItemMovedMessage(), {
      ...this.translationParams,
      targetPosition: index + 1
    });
  }
 
  private announceNotSuccessfulMove(): void {
    this.announceMove(this.a11yItemNotMovedMessage(), this.translationParams());
  }
 
  private announceMove(message?: string, translationParams?: Record<string, unknown>): void {
    if (message) {
      this.translateService
        .translateAsync(message, translationParams)
        .pipe(first())
        .subscribe(translatedMessage => this.liveAnnouncer.announce(translatedMessage));
    }
  }
}