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

79.48% Statements 93/117
55.95% Branches 47/84
91.17% Functions 31/34
77.88% Lines 81/104

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                                                                                                105x                 23x 23x             23x               23x               23x           23x       23x 23x   23x 23x     23x   23x 23x 23x 23x 23x   23x   23x   23x 23x   23x   23x   23x 23x   23x 23x     23x 28x     23x 28x     26x   23x 23x 10x 10x 10x                       23x 23x     18x 18x 16x         7x 2x 2x   5x 5x 5x 14x 14x     7x 5x   2x         1x 1x                                       4x 4x                   2x     2x 2x                                       4x 4x     4x 4x 4x   4x   2x     2x           2x 2x 2x 2x       1x 1x       1x 1x                 1x       23x 23x   21x 21x          
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { CdkListbox, CdkOption } from '@angular/cdk/listbox';
import {
  Component,
  computed,
  inject,
  input,
  isSignal,
  OnInit,
  output,
  signal,
  viewChild
} from '@angular/core';
import { SiActionDialogService } from '@siemens/element-ng/action-modal';
import { SiCircleStatusComponent } from '@siemens/element-ng/circle-status';
import { SiEmptyStateComponent } from '@siemens/element-ng/empty-state';
import { SiSearchBarComponent } 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,
    SiCircleStatusComponent,
    SiEmptyStateComponent,
    SiTranslatePipe,
    CdkListbox,
    CdkOption
  ],
  templateUrl: './si-widget-catalog.component.html',
  styleUrl: './si-widget-catalog.component.scss'
})
export class SiWidgetCatalogComponent extends SiWidgetEditorBase implements OnInit {
  /**
   * Placeholder text for the search input field in the widget catalog.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@DASHBOARD.WIDGET_LIBRARY.SEARCH_PLACEHOLDER:Search widget`)
   * ```
   */
  readonly searchPlaceholder = input(
    t(() => $localize`:@@DASHBOARD.WIDGET_LIBRARY.SEARCH_PLACEHOLDER:Search widget`)
  );
  /**
   * Emits when the catalog is `closed`, either by canceling or by adding or saving
   * a widget configuration. On cancel `undefined` is emitted, otherwise the related
   * widget configuration is emitted.
   */
  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.
   *
   * @defaultValue [] */
  widgetCatalog: Widget[] = [];
 
  /**
   * 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 = '';
  /**
   * Array used to hold the search result on the widget catalog.
   * @defaultValue [] */
  protected filteredWidgetCatalog: Widget[] = [];
  protected readonly selected = signal<Widget | undefined>(undefined);
  private widgetConfig?: Omit<WidgetConfig, 'id'>;
  private readonly hasEditor = computed(
    () => !!this.selected()?.componentFactory.editorComponentName
  );
 
  private readonly translateService = injectSiTranslateService();
 
  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 labelEmpty = t(() => $localize`:@@DASHBOARD.WIDGET_LIBRARY.EMPTY:Empty`);
 
  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 list`
  );
 
  protected readonly showAddButton = computed(() =>
    this.view() === 'list' ? !this.hasEditor() : true
  );
 
  protected readonly showNextButton = computed(() =>
    this.view() === 'list' ? this.hasEditor() : this.editorWizardState() !== undefined
  );
 
  protected readonly showPreviousButton = computed(() => this.view() === 'editor');
 
  protected readonly disableAddButton = computed(() => !this.selected() || this.invalidConfig());
  protected readonly disableNextButton = computed(() => {
    const wizardState = this.editorWizardState();
    if (this.view() === 'list') {
      return !this.selected();
    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);
  private readonly widgetCdkListbox = viewChild(CdkListbox<Widget>);
 
  ngOnInit(): void {
    this.filteredWidgetCatalog = this.widgetCatalog;
    if (this.widgetCatalog.length > 0) {
      this.selectWidget(this.widgetCatalog[0]);
    }
  }
 
  protected onSearch(searchTerm?: string): void {
    if (!searchTerm || searchTerm.trim().length === 0) {
      this.searchTerm = '';
      this.filteredWidgetCatalog = this.widgetCatalog;
    } else {
      this.searchTerm = searchTerm;
      const term = searchTerm.trim().toLowerCase();
      this.filteredWidgetCatalog = this.widgetCatalog.filter(wd => {
        const name = this.translateService.translateSync(wd.name);
        return name.toLowerCase().includes(term);
      });
    }
    if (this.filteredWidgetCatalog.length > 0) {
      this.selectWidget(this.filteredWidgetCatalog[0]);
    } else {
      this.selectWidget(undefined);
    }
  }
 
  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.selected();
    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 {
    const selected = this.selected();
    Iif (!selected) {
      return;
    }
 
    if (!this.widgetConfig) {
      this.widgetConfig = createWidgetConfig(selected);
    } else E{
      // 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 selectWidget(widget?: Widget): void {
    this.selected.set(widget);
    if (widget) {
      // need to keep this in setTimeout to avoid ExpressionChangedAfterItHasBeenCheckedError
      setTimeout(() => {
        this.widgetCdkListbox()?.selectValue(widget);
      });
    }
  }
}