All files / src/components/grid si-grid.component.ts

91.33% Statements 137/150
69.76% Branches 60/86
86.48% Functions 32/37
94.07% Lines 127/135

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 460                                        2x 2x                                                 2x   13x 13x 13x 13x               13x               13x               13x           13x               13x                       13x             13x             13x                 13x           13x           13x             13x                 13x                 13x                 13x     26x         13x   13x     51x           9x 1x     9x 4x 3x   1x       9x 2x         13x 13x       13x 13x             6x 6x 6x 6x 6x 6x 6x                 4x 3x     1x   1x   1x 1x 1x 1x         1x 1x 1x 1x 1x                         2x 1x     1x       1x 1x 1x   1x                   8x 8x 8x       8x 8x                   1x 1x   1x 1x     1x 2x   1x 1x                         2x 2x 1x   1x 1x                 1x   1x 1x 1x 1x 1x 1x 1x                         1x 1x   1x 1x 1x 1x 1x 1x         4x       4x     1x   1x   4x   1x 1x 1x         14x   14x               14x 14x 14x   15x 15x 15x 14x 14x                     14x 14x 15x 15x             1x               14x     14x       9x 2x 2x        
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { AsyncPipe } from '@angular/common';
import {
  Component,
  inject,
  input,
  model,
  OnChanges,
  OnDestroy,
  OnInit,
  output,
  SimpleChanges,
  Type,
  viewChild
} from '@angular/core';
import { SiLoadingSpinnerDirective } from '@siemens/element-ng/loading-spinner';
import { ModalOptions, SiModalService } from '@siemens/element-ng/modal';
import { BehaviorSubject, Subscription } from 'rxjs';
import { take } from 'rxjs/operators';
 
import { SI_DASHBOARD_CONFIGURATION } from '../../model/configuration';
import { GridConfig } from '../../model/gridstack.model';
import { SI_WIDGET_ID_PROVIDER } from '../../model/si-widget-id-provider';
import { SI_WIDGET_STORE } from '../../model/si-widget-storage';
import { Widget, WidgetConfig } from '../../model/widgets.model';
import { SiGridService } from '../../services/si-grid.service';
import {
  GridWrapperEvent,
  SiGridstackWrapperComponent
} from '../gridstack-wrapper/si-gridstack-wrapper.component';
import { SiWidgetInstanceEditorDialogComponent } from '../widget-instance-editor-dialog/si-widget-instance-editor-dialog.component';
 
/**
 * The grid component is the actual component on which the widget instances are placed and visualized. You can think of
 * a headless dashboard, without a title, toolbar or edit buttons.
 */
@Component({
  selector: 'si-grid',
  imports: [SiGridstackWrapperComponent, SiLoadingSpinnerDirective, AsyncPipe],
  templateUrl: './si-grid.component.html',
  styleUrl: './si-grid.component.scss',
  providers: [SiGridService]
})
export class SiGridComponent implements OnInit, OnChanges, OnDestroy {
  private storeSubscription?: Subscription;
  private gridService = inject(SiGridService);
  private modalService = inject(SiModalService);
  private widgetStorage = inject(SI_WIDGET_STORE);
  private widgetIdProvider = inject(SI_WIDGET_ID_PROVIDER);
 
  /**
   * Configuration options for a grid instance. Default is the optional
   * value from the {@link SI_DASHBOARD_CONFIGURATION}.
   *
   * @defaultValue inject(SI_DASHBOARD_CONFIGURATION)?.grid
   */
  readonly gridConfig = input<GridConfig | undefined>(inject(SI_DASHBOARD_CONFIGURATION)?.grid);
 
  /**
   * Sets the grid into editable mode, in which the widget instances can be moved,
   * resized, removed or new ones added.
   *
   * @defaultValue false
   */
  readonly editable = model(false);
  /**
   * This is the internal owner of the current editable state and is used to track if
   * editable or not. Not editable can be changed by either calling the `edit()` api
   * method or by setting the `editable` input. When setting the input, the `ngOnChanges(...)`
   * hook is used to call the `edit()` method. Similar, to get from editable to not editable,
   * `cancel()` or `save()` is used and can be triggered from `ngOnChanges(...)`.
   */
  private editableInternal = false;
 
  /**
   * An optional, but recommended dashboard id that is used in persistence and passed
   * to the widget store for saving and loading data.
   */
  readonly dashboardId = input<string>();
 
  /**
   * Provides the available widgets to the grid. When loading the widget configurations from
   * the storage, we need to have the widget definition available to be able to create the widget
   * instances on the grid.
   *
   * @defaultValue [] */
  readonly widgetCatalog = input<Widget[]>([]);
 
  /**
   * When the user clicks edit on a widget instance, an editor need to appear and the
   * widget editor component need to be loaded. When the grid is used standalone, it
   * takes care and opens a modal dialog and loads the configured widget editor component.
   * When the grid is used in a container like the flexible dashboard, the container manages
   * where the widget instance editor is displayed. In this case this options prevents the grid
   * from showing the editor in the dialog, and emits on `widgetInstanceEdit` on clicking the
   * widget `edit` action.
   *
   * @defaultValue false */
  readonly emitWidgetInstanceEditEvents = input(false);
 
  /**
   * Option to turn off the loading spinner on save and load operations.
   *
   * @defaultValue false
   */
  readonly hideProgressIndicator = input(false);
 
  /**
   * Option to configure a custom widget instance editor dialog component. The component provides the
   * editor hosting and the buttons to save and cancel.
   */
  readonly widgetInstanceEditorDialogComponent =
    input<Type<SiWidgetInstanceEditorDialogComponent>>();
 
  /**
   * Emits the modification state of the grid. It is `unmodified` when the visible state
   * is equal to the loaded state from the widget storage. When the user modifies the dashboard by
   * e.g. while moving the widgets, the dashboard is marked as `modified` and emits `true` and when the user
   * persists the change by saving, or reverts the state by canceling, the state is `unmodified`
   * again and emits `false`.
   */
  readonly isModified = output<boolean>();
 
  /**
   * Modified state that is emitted in the `isModified` output. Should only be
   changed using the {@link setModified} method.
   */
  private modified = false;
 
  /**
   * Emits to notify about edit events of widget instances. Only emits
   * if `emitWidgetInstanceEditEvents` is set to `true`.
   */
  readonly widgetInstanceEdit = output<WidgetConfig>();
 
  /**
   * All widget configuration objects of the visible widget instances.
   *
   * @internal
   */
  readonly visibleWidgetInstances$ = new BehaviorSubject<WidgetConfig[]>([]);
 
  /**
   * All widget instance configs that are on the grid by loading from the widget
   * storage. Thus, these widget are persisted.
   *
   * @defaultValue []
   * @internal
   */
  persistedWidgetInstances: WidgetConfig[] = [];
 
  /**
   * Widget instance configs that are added to the grid in edit mode, but not
   * persisted yet, as the user did not confirm the modification by save.
   *
   * @defaultValue []
   * @internal
   */
  transientWidgetInstances: WidgetConfig[] = [];
 
  /**
   * All widget instance configurations that are removed from the grid in edit mode.
   * These instances are persistently removed on save or re-added again on cancel.
   *
   * @defaultValue []
   * @internal
   */
  markedForRemoval: WidgetConfig[] = [];
 
  /** @defaultValue viewChild.required(SiGridstackWrapperComponent) */
  readonly gridStackWrapper = viewChild.required(SiGridstackWrapperComponent);
 
  /**
   * Indication for load and save operations.
   */
  readonly isLoading: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
 
  protected initialLoad = true;
 
  protected get showEmptyState(): boolean {
    return !this.initialLoad && this.visibleWidgetInstances$.value.length === 0;
  }
 
  ngOnChanges(changes: SimpleChanges<this>): void {
    // Reload widgets if the dashboardId changes. Do not load on inital
    // dashboardId property binding as first load will be done in ngOnInit()
    if (changes.dashboardId && !changes.dashboardId.firstChange) {
      queueMicrotask(() => this.loadAndSubscribeWidgets());
    }
 
    if (changes.editable) {
      if (changes.editable.currentValue) {
        this.edit();
      } else {
        this.cancel();
      }
    }
 
    if (changes.widgetCatalog) {
      this.gridService.widgetCatalog.set(this.widgetCatalog());
    }
  }
 
  ngOnInit(): void {
    queueMicrotask(() => this.loadAndSubscribeWidgets());
    this.gridService.widgetCatalog.set(this.widgetCatalog());
  }
 
  ngOnDestroy(): void {
    this.storeSubscription?.unsubscribe();
    this.isLoading.complete();
  }
 
  /**
   * Set dashboard grid in editable mode to modify widget instances.
   */
  edit(): void {
    Eif (!this.editableInternal) {
      this.transientWidgetInstances = [];
      this.markedForRemoval = [];
      this.setModified(false);
      this.editableInternal = true;
      this.editable.set(true);
      this.gridService.editable$.next(this.editableInternal);
    }
  }
 
  /**
   * Persists the current widget instances to the widget storage and
   * changes the editable and isModified modes.
   */
  save(): void {
    if (!this.editableInternal) {
      return;
    }
 
    this.isLoading.next(true);
    // Update position information
    const widgets = this.updateWidgetPositions(this.visibleWidgetInstances$.value);
 
    const transientWidgetIds = new Set(this.transientWidgetInstances.map(w => w.id));
    const modifiedWidgets = widgets.filter(widget => !transientWidgetIds.has(widget.id));
    const addedWidgets = widgets.filter(widget => transientWidgetIds.has(widget.id));
    this.widgetStorage
      .save(modifiedWidgets, addedWidgets, this.markedForRemoval, this.dashboardId())
      .pipe(take(1))
      .subscribe({
        next: (value: WidgetConfig[]) => {
          this.setModified(false);
          this.editableInternal = false;
          this.editable.set(false);
          this.gridService.editable$.next(this.editableInternal);
          this.isLoading.next(false);
        },
        error: (err: any) => {
          console.error('Saving dashboard configuration failed.', err);
          this.isLoading.next(false);
        }
      });
  }
 
  /**
   * Cancel current changes and restore last saved state.
   */
  cancel(): void {
    if (!this.editableInternal) {
      return;
    }
 
    Iif (this.modified) {
      this.visibleWidgetInstances$.next([...this.persistedWidgetInstances]);
      this.setModified(false);
    }
    this.editableInternal = false;
    Eif (this.editable()) {
      this.editable.set(false);
    }
    this.gridService.editable$.next(this.editableInternal);
  }
 
  /**
   * Adds a new widget instance configuration to the dashboard grid. It is not
   * persisted yet and is added to the transient widget instances.
   *
   * @param widgetInstanceConfig - The new widget configuration.
   */
  addWidgetInstance(widgetInstanceConfig: Omit<WidgetConfig, 'id'>): void {
    const id = this.widgetIdProvider.generateWidgetId(widgetInstanceConfig, this.dashboardId());
    const newWidget: WidgetConfig = { ...widgetInstanceConfig, id };
    const nextWidgets = this.updateWidgetPositions([
      ...this.visibleWidgetInstances$.value,
      newWidget
    ]);
    this.transientWidgetInstances.push(newWidget);
    this.visibleWidgetInstances$.next(nextWidgets);
  }
 
  /**
   * Removes a widget instance from the visible widgets and puts it in the
   * {@link markedForRemoval} array.
   *
   * @param widgetInstanceId - The id of the widget instance to be removed.
   */
  removeWidgetInstance(widgetInstanceId: string): void {
    const widgetToRemove = this.visibleWidgetInstances$.value.find(
      widget => widget.id === widgetInstanceId
    );
    Eif (widgetToRemove) {
      Iif (!this.transientWidgetInstances.some(widget => widget.id === widgetToRemove.id)) {
        this.markedForRemoval.push(widgetToRemove);
      }
      let nextWidgets = this.visibleWidgetInstances$.value.filter(
        widget => widget.id !== widgetInstanceId
      );
      nextWidgets = this.updateWidgetPositions(nextWidgets);
      this.visibleWidgetInstances$.next(nextWidgets);
    }
  }
 
  /**
   * Opens the provided widget configuration in the related editor or
   * emits on {@link widgetInstanceEdit}, if {@link emitWidgetInstanceEditEvents}
   * is true.
   *
   * @param widgetInstanceConfig - The config of the widget instance to edit.
   */
  editWidgetInstance(widgetInstanceConfig: WidgetConfig): void {
    // Need to edit a clone to avoid runtime editing
    const widgetConfigClone = structuredClone(widgetInstanceConfig);
    if (this.emitWidgetInstanceEditEvents()) {
      this.widgetInstanceEdit.emit(widgetConfigClone);
    } else {
      const widget = this.gridService.getWidget(widgetConfigClone.widgetId);
      const config: ModalOptions<SiWidgetInstanceEditorDialogComponent> = {
        animated: true,
        keyboard: true,
        inputValues: {
          widgetConfig: widgetConfigClone,
          widget
        },
        class: widget?.componentFactory.editorModalClass ?? 'modal-xl'
      };
      const widgetInstanceEditorDialogComponent = this.widgetInstanceEditorDialogComponent();
      const componentType =
        widgetInstanceEditorDialogComponent ?? SiWidgetInstanceEditorDialogComponent;
      const modalRef = this.modalService.show(componentType, config);
      const subscription = modalRef.content.closed.subscribe(editedWidgetConfig => {
        subscription.unsubscribe();
        modalRef.hide();
        Eif (editedWidgetConfig) {
          this.updateWidgetInstance(editedWidgetConfig);
        }
      });
    }
  }
 
  /**
   * Updates the visible widgets with an updated configuration. Will update the
   * user interface and emit on {@link isModified}.
   *
   * @param editedWidgetConfig - The config of the widget instance that was updated.
   */
  updateWidgetInstance(editedWidgetConfig: WidgetConfig): void {
    const index = this.visibleWidgetInstances$.value.findIndex(
      wc => wc.id === editedWidgetConfig.id
    );
    Eif (index >= 0) {
      let nextWidgets = this.updateWidgetPositions([...this.visibleWidgetInstances$.value]);
      nextWidgets[index] = editedWidgetConfig;
      nextWidgets = this.updateWidgetPositions(nextWidgets);
      this.visibleWidgetInstances$.next(nextWidgets);
      setTimeout(() => this.setModified(true), 0);
    }
  }
 
  protected handleGridEvent(event: GridWrapperEvent): void {
    const relevantEventTypes = ['added', 'removed', 'dragstop', 'resizestop'];
    // When widgets without explicit x/y are first added, GridStack auto-positions them.
    // Capture these resolved positions so cancel() can restore the exact layout
    // instead of re-triggering auto-positioning which may produce a different result.
    if (
      event.event.type === 'added' &&
      !this.editableInternal &&
      this.persistedWidgetInstances.some(w => w.x === undefined || w.y === undefined)
    ) {
      this.persistedWidgetInstances = this.updateWidgetPositions(this.persistedWidgetInstances);
    }
    if (this.editable() && relevantEventTypes.includes(event.event.type)) {
      // Make sure the widget config always holds the latest position information
      const widgets = this.updateWidgetPositions(this.visibleWidgetInstances$.value);
      this.visibleWidgetInstances$.next(widgets);
      setTimeout(() => this.setModified(true), 0);
    }
  }
 
  private loadAndSubscribeWidgets(): void {
    this.storeSubscription?.unsubscribe();
    // remove existing widgets
    this.visibleWidgetInstances$.next([]);
 
    // Only when we change the dashboard id, this method is invoked
    // directly. In this case we start the progress here and we stop
    // it in the `next` subscription. The subscription stays hot and
    // also get called when save() is invoked. In this case, we do not
    // want to decrease the progress counter as we do it in the save
    // subscription. To handle this, we use the boolean marker `initialLoad`.
    this.initialLoad = true;
    this.isLoading.next(true);
    this.storeSubscription = this.widgetStorage.load(this.dashboardId()).subscribe({
      next: widgets => {
        this.visibleWidgetInstances$.next(widgets);
        this.persistedWidgetInstances = widgets;
        if (this.initialLoad) {
          this.initialLoad = false;
          this.isLoading.next(false);
        }
      },
      error: err => {
        console.error('Loading dashboard configuration failed', err);
        this.isLoading.next(false);
      }
    });
  }
 
  private updateWidgetPositions(widgetConfigs: WidgetConfig[]): WidgetConfig[] {
    const layout = this.gridStackWrapper().getLayout();
    const widgets = widgetConfigs.map(widget => {
      const position = layout.find(p => p.id === widget.id);
      if (
        position &&
        (widget.x !== position.x ||
          widget.y !== position.y ||
          widget.width !== position.width ||
          widget.height !== position.height)
      ) {
        return {
          ...widget,
          x: position.x,
          y: position.y,
          width: position.width,
          height: position.height
        };
      } else {
        return widget;
      }
    });
    return widgets || [];
  }
 
  private setModified(modified: boolean): void {
    if (this.modified !== modified) {
      this.modified = modified;
      this.isModified.emit(this.modified);
    }
  }
}