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

73.37% Statements 113/154
50.94% Branches 54/106
80.95% Functions 34/42
72.14% Lines 101/140

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                                                                                                                      95x                 19x 19x             19x               19x   19x               19x           19x       19x 19x   19x 21x     19x 19x 19x 19x 19x   19x   19x   19x 19x   19x   19x   19x 19x   19x 19x     19x 26x     19x 26x     24x   19x 19x 10x 10x 10x                         19x             19x   19x         19x 19x 19x 19x 19x     16x 16x 14x         19x       6x 2x 2x   4x 4x 12x     6x 4x   2x         1x 1x                                       4x 4x                   2x     2x 2x                                       4x 4x     4x 4x 4x   4x             2x 2x 2x     2x     2x       2x 2x                 2x                   2x                         2x           25x 25x 25x 25x 25x 25x       2x 2x 2x 2x       1x 1x       1x 1x                 1x       20x 20x   18x 18x               4x                        
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { CdkListbox, CdkOption } from '@angular/cdk/listbox';
import {
  Component,
  ComponentRef,
  computed,
  EnvironmentInjector,
  inject,
  Injector,
  input,
  isSignal,
  OnDestroy,
  OnInit,
  output,
  OutputRefSubscription,
  signal,
  viewChild,
  ViewContainerRef
} 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 { SiTranslatePipe, t } from '@siemens/element-translate-ng/translate';
import { Subscription } from 'rxjs';
 
import {
  createWidgetConfig,
  Widget,
  WidgetConfig,
  WidgetConfigStatus,
  WidgetInstanceEditor,
  WidgetInstanceEditorWizard,
  WidgetInstanceEditorWizardState
} from '../../model/widgets.model';
import { setupWidgetEditor } from '../../widget-loader';
 
/**
 * 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 implements OnInit, OnDestroy {
  /**
   * 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');
 
  protected readonly editorHost = viewChild.required('editorHost', { read: ViewContainerRef });
 
  /**
   * 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
  );
 
  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;
    }
  });
 
  /** Indicates if the current config is valid or not. If invalid, the add button is disabled. */
  private readonly invalidConfig = signal(false);
 
  /**
   * Marks the widget configuration as modified. Is set when widget editor instance
   * emits configChange events. Triggers edit discard confirmation dialog when widget config
   * is modified but not added to the dashboard.
   * */
  private widgetConfigModified = false;
  private widgetInstanceEditor?: WidgetInstanceEditor;
  private readonly editorWizardState = signal<WidgetInstanceEditorWizardState | undefined>(
    undefined
  );
  private widgetInstanceEditorRef?: ComponentRef<WidgetInstanceEditor>;
 
  private subscriptions: Subscription[] | OutputRefSubscription[] = [];
  private dialogService = inject(SiActionDialogService);
  private injector = inject(Injector);
  private envInjector = inject(EnvironmentInjector);
  private readonly widgetCdkListbox = viewChild(CdkListbox<Widget>);
 
  ngOnInit(): void {
    this.filteredWidgetCatalog = this.widgetCatalog;
    if (this.widgetCatalog.length > 0) {
      this.selectWidget(this.widgetCatalog[0]);
    }
  }
 
  ngOnDestroy(): void {
    this.tearDownEditor();
  }
 
  protected onSearch(searchTerm?: string): void {
    if (!searchTerm || searchTerm.trim().length === 0) {
      this.searchTerm = '';
      this.filteredWidgetCatalog = this.widgetCatalog;
    } else {
      this.searchTerm = searchTerm;
      this.filteredWidgetCatalog = this.widgetCatalog.filter(wd =>
        wd.name.toLowerCase().includes(searchTerm.trim().toLowerCase())
      );
    }
    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);
 
    setupWidgetEditor(
      selected.componentFactory,
      this.editorHost(),
      this.injector,
      this.envInjector
    ).subscribe({
      next: componentRef => {
        this.widgetInstanceEditorRef = componentRef;
        this.widgetInstanceEditor = componentRef.instance;
        Iif (isSignal(this.widgetInstanceEditor.config)) {
          this.widgetInstanceEditorRef.setInput('config', this.widgetConfig);
        } else {
          this.widgetInstanceEditor.config = this.widgetConfig!;
        }
        // To be used by webcomponent wrapper
        Iif ('statusChangesHandler' in this.widgetInstanceEditor) {
          this.widgetInstanceEditor.statusChangesHandler = this.handleStatusChanges.bind(this);
        }
 
        let hasStatusChangesEmitter = false;
        Iif (this.widgetInstanceEditor.statusChanges) {
          hasStatusChangesEmitter = true;
          this.subscriptions.push(
            this.widgetInstanceEditor.statusChanges.subscribe(statusChanges => {
              this.handleStatusChanges(statusChanges);
            }) as Subscription
          );
        }
 
        Iif (this.widgetInstanceEditor.configChange) {
          this.subscriptions.push(
            this.widgetInstanceEditor.configChange.subscribe(config => {
              if (!hasStatusChangesEmitter) {
                this.widgetConfigModified = true;
              }
            }) as Subscription
          );
        }
 
        Iif (this.isEditorWizard(this.widgetInstanceEditor)) {
          this.editorWizardState.set(this.widgetInstanceEditor.state);
 
          if (this.widgetInstanceEditor.stateChange) {
            this.subscriptions.push(
              this.widgetInstanceEditor.stateChange.subscribe(state => {
                this.editorWizardState.set(state);
              }) as Subscription
            );
          }
        }
      },
      error: error => {
        console.error(error);
      }
    });
  }
 
  private tearDownEditor(): void {
    this.invalidConfig.set(false);
    this.widgetConfigModified = false;
    this.editorWizardState.set(undefined);
    this.widgetInstanceEditor = undefined;
    this.subscriptions.forEach(s => s.unsubscribe());
    this.subscriptions = [];
  }
 
  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);
      });
    }
  }
 
  private isEditorWizard(
    editor?: WidgetInstanceEditor | WidgetInstanceEditorWizard
  ): editor is WidgetInstanceEditorWizard {
    return !!editor && 'state' in editor;
  }
 
  private handleStatusChanges(statusChanges: Partial<WidgetConfigStatus>): void {
    if (statusChanges.invalid !== undefined) {
      this.invalidConfig.set(statusChanges.invalid);
    }
    if (statusChanges.modified !== undefined) {
      this.widgetConfigModified = statusChanges.modified;
    }
  }
}