All files / src/components/widget-catalog si-widget-catalog.component.ts

85.94% Statements 159/185
72.22% Branches 78/108
96.29% Functions 52/54
84.61% Lines 143/169

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 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459                                                                                                                        406x           77x                     77x 77x               77x               77x                 77x               77x               77x   77x 75x 75x 24x     75x     112x     112x                               77x 77x 77x       77x   77x     75x   94x           77x 77x 99x 99x     77x 93x     77x 77x   77x         210x     77x 77x 77x 77x 77x 77x 77x 77x     77x   77x   77x 77x   77x   77x   77x 77x   77x 77x     77x 88x     77x 88x         83x   77x 86x   77x 22x 22x 22x                       77x     77x 77x 90x 90x 55x     77x 88x 88x 88x 18x             66x 66x 51x 52x   51x         18x 6x 6x   12x 12x 12x 33x 33x     18x     18x 18x   18x       2x 2x                                       9x 9x                   4x     4x 4x                                       9x 9x     9x 9x 9x   9x   5x     4x           4x 4x 4x 4x       9x 8x 8x 2x     6x 3x 3x     3x 3x     4x 3x 3x     1x 1x 1x                                   134x 134x 134x 134x 124x         187x       18x 18x 14x     18x 4x 4x     14x 11x   14x       4x 4x 1x   3x      
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { CdkListbox, CdkOption } from '@angular/cdk/listbox';
import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  booleanAttribute,
  Component,
  computed,
  effect,
  inject,
  input,
  isSignal,
  linkedSignal,
  OnInit,
  output,
  signal,
  untracked
} from '@angular/core';
import { debounce, form, FormField } from '@angular/forms/signals';
import { elementSpecialObject } from '@siemens/element-icons';
import { SiActionDialogService } from '@siemens/element-ng/action-modal';
import { SiBadgeComponent } from '@siemens/element-ng/badge';
import { SiEmptyStateComponent } from '@siemens/element-ng/empty-state';
import { addIcons, SiIconComponent } from '@siemens/element-ng/icon';
import { SiSearchBarComponent, SiSearchBarInputDirective } from '@siemens/element-ng/search-bar';
import {
  injectSiTranslateService,
  SiTranslatePipe,
  t
} from '@siemens/element-translate-ng/translate';
 
import { createWidgetConfig, Widget, WidgetConfig } from '../../model/widgets.model';
import { SiWidgetEditorBase } from '../si-widget-editor-base';
 
/**
 * Default widget catalog implementation to show all available widgets that can be added
 * to a dashboard. It consists of a list view, that lists all available widgets and after
 * selection, a host in which the widget specific editor is loaded. Applications can either
 * stay with the default catalog or implement their own by extending this class.
 */
@Component({
  selector: 'si-widget-catalog',
  imports: [
    SiSearchBarComponent,
    SiSearchBarInputDirective,
    FormField,
    SiIconComponent,
    SiBadgeComponent,
    SiEmptyStateComponent,
    SiTranslatePipe,
    CdkListbox,
    CdkOption
  ],
  templateUrl: './si-widget-catalog.component.html',
  styleUrl: './si-widget-catalog.component.scss',
  changeDetection: ChangeDetectionStrategy.Eager
})
export class SiWidgetCatalogComponent extends SiWidgetEditorBase implements OnInit {
  /**
   * Option to enable multi-select in the widget catalog.
   * When enabled, the user can select multiple widgets to add to the dashboard at once.
   * @defaultValue false
   * */
  readonly multiSelect = input(false, {
    transform: booleanAttribute
  });
  /**
   * Placeholder text for the search input field in the widget catalog.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@DASHBOARD.WIDGET_LIBRARY.SEARCH_PLACEHOLDER:Search…`)
   * ```
   */
  readonly searchPlaceholder = input(
    t(() => $localize`:@@DASHBOARD.WIDGET_LIBRARY.SEARCH_PLACEHOLDER:Search…`)
  );
  /**
   * Emits when the catalog is `closed`, either by canceling or by adding or saving
   * widget configurations. On cancel `undefined` is emitted, otherwise an array of
   * the related widget configurations is emitted. In single-select mode the array
   * always contains exactly one entry.
   */
  readonly closed = output<Omit<WidgetConfig, 'id'>[] | undefined>();
 
  /**
   * View defines if the catalog widget list or the widget editor is visible.
   *
   * @internal
   * @defaultValue 'list'
   */
  readonly view = signal<'list' | 'editor' | 'editor-only'>('list');
 
  /**
   * Property to provide the available widgets to the catalog. The flexible
   * dashboard creates the catalog by Angular's `createComponent()` method
   * and sets the available widgets to this attribute.
   *
   * @deprecated This property will be removed in v52. Use the signal `widgetList` instead.
   * @defaultValue [] */
  widgetCatalog: Widget[] = [];
 
  /**
   * Property to provide the available widgets to the catalog. The flexible
   * dashboard creates the catalog by Angular's `createComponent()` method
   * and sets the available widgets to this attribute.
   *
   * @defaultValue [] */
  readonly widgetList = signal<Widget[]>([]);
 
  /**
   * Current visible widget instances on the dashboard, used to enforce
   * `maxInstances` limits and display the added state in the catalog.
   *
   * @defaultValue []
   */
  readonly visibleWidgetInstances = input<WidgetConfig[]>([]);
 
  protected readonly widgetStates = computed(() => {
    const counts = new Map<string, number>();
    for (const instance of this.visibleWidgetInstances()) {
      counts.set(instance.widgetId, (counts.get(instance.widgetId) ?? 0) + 1);
    }
 
    return new Map(
      this.widgetCatalogList.map(widget => {
        const added =
          widget.maxInstances !== undefined &&
          widget.maxInstances > 0 &&
          (counts.get(widget.id) ?? 0) >= widget.maxInstances;
        return [
          widget.id,
          {
            disabled: widget.maxInstances === 0 || added,
            added,
            badge: added ? this.labelAdded : widget.badge
          }
        ];
      })
    );
  });
 
  /**
   * Holds the search term from the catalog to be visible when going back
   * by pressing the previous button from the widget edit view.
   */
  protected searchTerm = '';
  protected readonly searchText = signal('');
  protected readonly searchField = form(this.searchText, path => debounce(path, 400));
  /**
   * Array used to hold the search result on the widget catalog.
   * @defaultValue [] */
  protected filteredWidgetCatalog: Widget[] = [];
  // Prune disabled widgets before the next selection read, without waiting for an effect.
  protected readonly selectedWidgets = linkedSignal({
    source: this.widgetStates,
    computation: (states, previous): Widget[] =>
      previous?.value.filter(widget => !states.get(widget.id)?.disabled) ?? []
  });
  protected readonly hasSelection = computed(() => this.selectedWidgets().length > 0);
  /**
   * @deprecated Use `selectedWidgets` and `hasSelection` instead.
   * This property only holds the first selected widget and is not updated when multiple selection is allowed.
   * It will be removed in one of the next major releases.
   */
  protected readonly selected = signal<Widget | undefined>(undefined);
  private readonly singleSelectedWidget = computed(() => {
    const selectedWidgets = this.selectedWidgets();
    return selectedWidgets.length === 1 ? selectedWidgets[0] : undefined;
  });
  private widgetConfig?: Omit<WidgetConfig, 'id'>;
  private readonly singleSelectedWidgetHasEditor = computed(
    () => !!this.singleSelectedWidget()?.componentFactory.editorComponentName
  );
 
  private readonly translateService = injectSiTranslateService();
  private readonly changeDetectorRef = inject(ChangeDetectorRef);
  /** Default indicator for widgets without an `iconClass`, as specified in the design. */
  protected readonly icons = addIcons({ elementSpecialObject });
  /**
   * TODO: Remove this property in v52. Use the signal `widgetList` instead.
   */
  private get widgetCatalogList(): Widget[] {
    return this.widgetList().length ? this.widgetList() : this.widgetCatalog;
  }
 
  protected labelCancel = t(() => $localize`:@@DASHBOARD.WIDGET_LIBRARY.CANCEL:Cancel`);
  protected labelPrevious = t(() => $localize`:@@DASHBOARD.WIDGET_LIBRARY.PREVIOUS:Previous`);
  protected labelNext = t(() => $localize`:@@DASHBOARD.WIDGET_LIBRARY.NEXT:Next`);
  protected labelAdd = t(() => $localize`:@@DASHBOARD.WIDGET_LIBRARY.ADD:Add`);
  protected labelAdded = t(() => $localize`:@@DASHBOARD.WIDGET_LIBRARY.ADDED:Added`);
  protected labelEmpty = t(() => $localize`:@@DASHBOARD.WIDGET_LIBRARY.EMPTY:No widgets found`);
  protected labelEmptyMessage = t(
    () => $localize`:@@DASHBOARD.WIDGET_LIBRARY.EMPTY_MESSAGE:Refine search`
  );
 
  protected labelDialogHeading = t(
    () =>
      $localize`:@@DASHBOARD.WIDGET_LIBRARY.DISCARD_CONFIG_CHANGE_DIALOG.HEADING:Widget configuration changed`
  );
  protected labelDialogCancel = t(
    () => $localize`:@@DASHBOARD.WIDGET_LIBRARY.DISCARD_CONFIG_CHANGE_DIALOG.CANCEL:Cancel`
  );
  protected labelDialogMessage = t(
    () =>
      $localize`:@@DASHBOARD.WIDGET_LIBRARY.DISCARD_CONFIG_CHANGE_DIALOG.MESSAGE:The widget configuration changed. Do you want to discard the changes?`
  );
  protected labelDialogDiscard = t(
    () => $localize`:@@DASHBOARD.WIDGET_LIBRARY.DISCARD_CONFIG_CHANGE_DIALOG.DISCARD:Discard`
  );
  protected labelWidgetCatalogList = t(
    () => $localize`:@@DASHBOARD.WIDGET_LIBRARY.WIDGET_CATALOG_LIST:Widget catalog`
  );
 
  protected readonly showAddButton = computed(() =>
    this.view() === 'list' ? !this.singleSelectedWidgetHasEditor() : true
  );
 
  protected readonly showNextButton = computed(() =>
    this.view() === 'list'
      ? this.singleSelectedWidgetHasEditor()
      : this.editorWizardState() !== undefined
  );
 
  protected readonly showPreviousButton = computed(() => this.view() === 'editor');
 
  protected readonly disableAddButton = computed(
    () => !this.hasSelection() || (this.view() !== 'list' && this.invalidConfig())
  );
  protected readonly disableNextButton = computed(() => {
    const wizardState = this.editorWizardState();
    if (this.view() === 'list') {
      return !this.singleSelectedWidgetHasEditor();
    E} else if (!wizardState) {
      return true;
    } else if (!wizardState.hasNext) {
      return true;
    } else if (wizardState.disableNext !== undefined) {
      return wizardState.disableNext;
    } else {
      return false;
    }
  });
 
  private dialogService = inject(SiActionDialogService);
 
  constructor() {
    super();
    effect(() => {
      const selected = this.selected();
      if (selected) {
        this.selectWidgets([selected]);
      }
    });
    effect(() => {
      const searchText = this.searchText();
      untracked(() => {
        if (this.searchField().dirty()) {
          this.onSearch(searchText);
        }
      });
    });
  }
 
  ngOnInit(): void {
    this.filteredWidgetCatalog = this.widgetCatalogList;
    if (!this.multiSelect()) {
      const firstEnabledWidget = this.widgetCatalogList.find(widget =>
        this.isWidgetEnabled(widget)
      );
      this.selectWidgets(firstEnabledWidget ? [firstEnabledWidget] : []);
    }
  }
 
  protected onSearch(searchTerm?: string): void {
    if (!searchTerm || searchTerm.trim().length === 0) {
      this.searchTerm = '';
      this.filteredWidgetCatalog = this.widgetCatalogList;
    } else {
      this.searchTerm = searchTerm;
      const term = searchTerm.trim().toLowerCase();
      this.filteredWidgetCatalog = this.widgetCatalogList.filter(wd => {
        const name = this.translateService.translateSync(wd.name);
        return name.toLowerCase().includes(term);
      });
    }
    this.searchText.set(this.searchTerm);
    // In multi selection mode, filter is independent of the selection,
    // so we don't need to update the selection with the filtered catalog.
    Eif (!this.multiSelect()) {
      this.updateSelectionOnFilter();
    }
    this.changeDetectorRef.markForCheck();
  }
 
  protected onCancel(): void {
    if (!this.widgetConfigModified()) {
      this.closed.emit(undefined);
    } else E{
      this.dialogService
        .showActionDialog({
          type: 'edit-discard',
          disableSave: true,
          heading: this.labelDialogHeading,
          cancelBtnName: this.labelDialogCancel,
          disableSaveMessage: this.labelDialogMessage,
          disableSaveDiscardBtnName: this.labelDialogDiscard
        })
        .subscribe(result => {
          if (result === 'discard') {
            this.closed.emit(undefined);
          }
        });
    }
  }
 
  protected onNext(): void {
    if (this.view() === 'list') {
      this.setupWidgetInstanceEditor();
    } else E{
      if (this.isEditorWizard(this.widgetInstanceEditor)) {
        this.widgetInstanceEditor.next();
        this.editorWizardState.set(this.widgetInstanceEditor.state);
      }
    }
  }
 
  protected onPrevious(): void {
    Iif (this.isEditorWizard(this.widgetInstanceEditor) && this.editorWizardState()?.hasPrevious) {
      this.widgetInstanceEditor.previous();
      this.editorWizardState.set(this.widgetInstanceEditor.state);
    } else if (!this.widgetConfigModified()) {
      this.setupCatalog();
    } else E{
      this.dialogService
        .showActionDialog({
          type: 'edit-discard',
          disableSave: true,
          heading: this.labelDialogHeading,
          cancelBtnName: this.labelDialogCancel,
          message: this.labelDialogMessage,
          discardBtnName: this.labelDialogDiscard
        })
        .subscribe(result => {
          if (result === 'discard') {
            this.setupCatalog();
          }
        });
    }
  }
 
  private setupWidgetInstanceEditor(): void {
    const selected = this.singleSelectedWidget();
    Iif (!selected) {
      return;
    }
    this.tearDownEditor();
    this.view.set('editor');
    this.widgetConfig = createWidgetConfig(selected);
 
    this.loadWidgetEditor(selected.componentFactory, this.editorHost()).subscribe({
      next: componentRef => {
        this.initializeEditor(componentRef, this.widgetConfig!);
      },
      error: error => {
        console.error(error);
      }
    });
  }
 
  private setupCatalog(): void {
    this.editorHost().clear();
    this.tearDownEditor();
    this.widgetConfig = undefined;
    this.view.set('list');
  }
 
  protected onAddWidget(): void {
    if (this.view() === 'list') {
      const selectedWidgets = this.selectedWidgets();
      if (selectedWidgets.length === 0) {
        return;
      }
 
      if (!this.multiSelect() && selectedWidgets.length === 1) {
        const [selectedWidget] = selectedWidgets;
        Iif (selectedWidget.componentFactory.editorComponentName) {
          return;
        }
        this.closed.emit([createWidgetConfig(selectedWidget)]);
        return;
      }
 
      const configs = selectedWidgets.map(widget => this.createConfigForSelection(widget));
      this.closed.emit(configs);
      return;
    }
 
    const selectedWidget = this.singleSelectedWidget();
    Eif (!selectedWidget) {
      return;
    }
 
    if (!this.widgetConfig) {
      this.widgetConfig = createWidgetConfig(selectedWidget);
    } else {
      // Make sure we use the same config object as the editor
      if (isSignal(this.widgetInstanceEditor?.config)) {
        this.widgetConfig = this.widgetInstanceEditor?.config() ?? this.widgetConfig;
      } else {
        this.widgetConfig = this.widgetInstanceEditor?.config ?? this.widgetConfig;
      }
    }
 
    this.closed.emit([this.widgetConfig]);
  }
 
  protected selectWidgets(widgets: readonly Widget[]): void {
    const enabledWidgets = widgets.filter(widget => this.isWidgetEnabled(widget));
    const selection = this.multiSelect() ? enabledWidgets : enabledWidgets.slice(0, 1);
    this.selectedWidgets.set(selection);
    if (!this.multiSelect()) {
      this.selected.set(selection[0]);
    }
  }
 
  private isWidgetEnabled(widget: Widget): boolean {
    return !this.widgetStates().get(widget.id)?.disabled;
  }
 
  private updateSelectionOnFilter(): void {
    const filteredWidgets = new Set(this.filteredWidgetCatalog);
    const selectedFilteredWidgets = this.selectedWidgets().filter(widget =>
      filteredWidgets.has(widget)
    );
 
    if (selectedFilteredWidgets.length > 0) {
      this.selectWidgets(selectedFilteredWidgets);
      return;
    }
 
    const firstEnabledWidget = this.filteredWidgetCatalog.find(widget =>
      this.isWidgetEnabled(widget)
    );
    this.selectWidgets(firstEnabledWidget ? [firstEnabledWidget] : []);
  }
 
  private createConfigForSelection(widget: Widget): Omit<WidgetConfig, 'id'> {
    const config = createWidgetConfig(widget);
    if (this.multiSelect() && widget.componentFactory.editorComponentName) {
      return { ...config, setupPending: true };
    }
    return config;
  }
}