All files / src/components/flexible-dashboard si-flexible-dashboard.component.ts

81.25% Statements 91/112
63.21% Branches 55/87
70.83% Functions 17/24
82.35% Lines 84/102

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                                                    1x 1x                                                               1x           13x         13x           13x             13x           13x           13x             13x             13x             13x             13x               13x                   13x 13x             13x           13x         13x       13x       13x                 13x   13x 13x 13x   13x     1x           13x             13x         15x             13x 15x 15x       1x   14x       13x 13x 13x 13x 13x 13x           23x 5x 5x 2x   5x 1x 1x 1x   5x 5x     23x 3x 2x   1x     23x 1x         13x       13x               3x 3x 1x   3x 3x   3x 3x 3x       1x 1x 1x 1x         3x                 18x 18x       18x         18x   19x   18x           18x 16x   16x               19x     19x 19x                                                                  
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { AsyncPipe } from '@angular/common';
import {
  Component,
  computed,
  inject,
  input,
  inputBinding,
  model,
  OnChanges,
  OnDestroy,
  OnInit,
  output,
  outputBinding,
  signal,
  SimpleChanges,
  Type,
  viewChild,
  ViewContainerRef
} from '@angular/core';
import { MenuItem } from '@siemens/element-ng/common';
import { SiDashboardComponent } from '@siemens/element-ng/dashboard';
import { t } from '@siemens/element-translate-ng/translate';
import { BehaviorSubject, combineLatest, of, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
 
import {
  Config,
  SI_DASHBOARD_CONFIGURATION,
  SI_DASHBOARD_TOOLBAR_ITEMS
} from '../../model/configuration';
import { DashboardToolbarItem } from '../../model/si-dashboard-toolbar.model';
import { SI_WIDGET_STORE } from '../../model/si-widget-storage';
import { Widget, WidgetConfig } from '../../model/widgets.model';
import { SiDashboardToolbarComponent } from '../dashboard-toolbar/si-dashboard-toolbar.component';
import { SiGridComponent } from '../grid/si-grid.component';
import { SiWidgetCatalogComponent } from '../widget-catalog/si-widget-catalog.component';
import { SiWidgetInstanceEditorDialogComponent } from '../widget-instance-editor-dialog/si-widget-instance-editor-dialog.component';
 
/**
 * Dashboard has three state: displaying the *dashboard* (default),
 * showing the *catalog* to add a new widget, or showing an *editor*
 * to edit an existing widget.
 */
type ViewState = 'dashboard' | 'catalog' | 'editor';
 
/**
 * The component implements a dashboard with adding, removing and resizing widgets.
 * It consists and connects a toolbar, a grid with widgets, and a widget catalog.
 */
@Component({
  selector: 'si-flexible-dashboard',
  imports: [SiDashboardComponent, SiDashboardToolbarComponent, SiGridComponent, AsyncPipe],
  templateUrl: './si-flexible-dashboard.component.html',
  styleUrl: './si-flexible-dashboard.component.scss'
})
export class SiFlexibleDashboardComponent implements OnInit, OnChanges, OnDestroy {
  /**
   * Input to change the dashboard editable state.
   *
   * @defaultValue false
   */
  readonly editable = model(false);
 
  /**
   * Heading for the dashboard.
   */
  readonly heading = input<string>();
 
  /**
   * Optionally, provide a custom subclass of the SiWidgetCatalogComponent
   * to use your own catalog component.
   */
  readonly widgetCatalogComponent = input<Type<SiWidgetCatalogComponent>>();
 
  /**
   * Optionally, provide a custom subclass of the {@link SiWidgetInstanceEditorDialogComponent}
   * to use your own implementation.
   */
  readonly widgetInstanceEditorDialogComponent =
    input<Type<SiWidgetInstanceEditorDialogComponent>>();
 
  /**
   * Optionally, but it is recommended to include an id for a dashboard.
   * The id is utilized in the persistence calls on the {@link SiWidgetStorage}.
   */
  readonly dashboardId = input<string>();
 
  /**
   * Sets the available widgets for the widget catalog to the dashboard.
   *
   * @defaultValue [] */
  readonly widgetCatalog = input<Widget[]>([]);
 
  /**
   * Option to remove the add widget instance button from the primary toolbar.
   *
   * @defaultValue false
   */
  readonly hideAddWidgetInstanceButton = input(false);
 
  /**
   * Option to hide the dashboard edit button.
   *
   * @defaultValue false
   */
  readonly hideEditButton = input(false);
 
  /**
   *  Option to display the edit button as a text button instead, only if the window is larger than xs {@link SiResponsiveContainerDirective}.
   *
   * @defaultValue false
   */
  readonly showEditButtonLabel = input(false);
 
  /**
   * Option to turn off the loading spinner on save and load operations.
   *
   * @defaultValue false
   */
  readonly hideProgressIndicator = input(false);
 
  /**
   * Option to configure a dashboard instance. Default is the optional value from
   * the {@link SI_DASHBOARD_CONFIGURATION}.
   *
   * @defaultValue inject(SI_DASHBOARD_CONFIGURATION)
   */
  readonly config = input<Config | undefined>(inject(SI_DASHBOARD_CONFIGURATION));
 
  /**
   * 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`)
  );
 
  /**
   * Primary action menu items shown in the edit mode of the dashboard.
   * @defaultValue []
   */
  readonly primaryEditActions = input<DashboardToolbarItem[]>([]);
 
  /**
   * Secondary action menu items shown in the edit mode of the dashboard.
   * @defaultValue []
   */
  readonly secondaryEditActions = input<DashboardToolbarItem[]>([]);
 
  /**
   * The grid component is the actual container for the widgets.
   */
  readonly grid = viewChild.required<SiGridComponent>('grid');
 
  /** Property to access the dashboard component instance.
   */
  readonly dashboard = viewChild.required<SiDashboardComponent>('dashboard');
 
  /** The view child holds the container that hosts the widget catalog.
   */
  protected readonly catalogHost = viewChild.required('catalogHost', { read: ViewContainerRef });
 
  /**
   * 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>();
 
  protected labelAddWidget = t(() => $localize`:@@DASHBOARD.ADD_WIDGET:Add widget`);
  protected labelEditor = t(() => $localize`:@@DASHBOARD.WIDGET_EDITOR_DIALOG.TITLE:Edit`);
  protected labelCatalog = t(() => $localize`:@@DASHBOARD.WIDGET_LIBRARY.TITLE:Add widget`);
 
  protected addWidgetInstanceAction: DashboardToolbarItem = {
    type: 'action',
    label: this.labelAddWidget,
    action: () => this.showWidgetCatalog()
  };
 
  /**
   * The primary action menu items shown in the edit mode of the dashboard.
   */
  readonly primaryEditActions$ = new BehaviorSubject<(MenuItem | DashboardToolbarItem)[]>([
    this.addWidgetInstanceAction
  ]);
  /**
   * The secondary action menu items shown in the edit mode of the dashboard. When all menu items are more than
   * three, they will be places in the secondary menu of the content action bar.
   */
  readonly secondaryEditActions$ = new BehaviorSubject<(MenuItem | DashboardToolbarItem)[]>([]);
 
  /**
   * @returns True, if the dashboard shows its widgets and not a catalog or and editor.
   */
  readonly isDashboardVisible = computed(() => this.viewState() === 'dashboard');
 
  /**
   * The page title of the dashboard, which is either {@link SiFlexibleDashboardComponent.heading} for the
   * default widget view or `DASHBOARD.WIDGET_EDITOR_DIALOG.TITLE` or 'DASHBOARD.WIDGET_LIBRARY.TITLE' when
   * adding new or editing widgets.
   */
  readonly pageTitle = computed(() => {
    const viewState = this.viewState();
    switch (viewState) {
      case 'editor':
        return this.labelEditor;
      case 'catalog':
        return this.labelCatalog;
      default:
        return this.heading();
    }
  });
 
  private readonly viewState = signal<ViewState>('dashboard');
  private widgetStorage = inject(SI_WIDGET_STORE);
  private hideAddWidgetInstanceButton$ = new BehaviorSubject(this.hideAddWidgetInstanceButton());
  private dashboardId$ = new Subject<string | undefined>();
  private readonly toolbar = viewChild.required<SiDashboardToolbarComponent>('toolbar');
  private readonly globalEditActions = inject(SI_DASHBOARD_TOOLBAR_ITEMS, { optional: true }) ?? {
    primary: [],
    secondary: []
  };
 
  ngOnChanges(changes: SimpleChanges<this>): void {
    if (changes.dashboardId) {
      const dashboard = this.dashboard();
      if (dashboard.isExpanded) {
        dashboard.restore();
      }
      if (this.editable()) {
        this.grid().cancel();
        this.viewState.set('dashboard');
        this.catalogHost().clear();
      }
      this.dashboardId$.next(changes.dashboardId.currentValue);
      this.setupMenuItems();
    }
 
    if (changes.editable) {
      if (changes.editable.currentValue) {
        this.grid().edit();
      } else {
        this.grid().cancel();
      }
    }
    if (changes.hideAddWidgetInstanceButton) {
      this.hideAddWidgetInstanceButton$.next(changes.hideAddWidgetInstanceButton.currentValue);
    }
  }
 
  ngOnInit(): void {
    this.setupMenuItems();
  }
 
  ngOnDestroy(): void {
    this.dashboardId$.next(undefined);
  }
 
  /**
   * Shows the widget catalog of the dashboard. If a widget instance is expanded
   * it restores the widget instances before.
   */
  showWidgetCatalog(): void {
    const dashboard = this.dashboard();
    if (dashboard.isExpanded) {
      dashboard.restore();
    }
    Eif (!this.editable()) {
      this.grid().edit();
    }
    this.viewState.set('catalog');
    const componentType = this.widgetCatalogComponent() ?? SiWidgetCatalogComponent;
    const catalogRef = this.catalogHost().createComponent<SiWidgetCatalogComponent>(componentType, {
      bindings: [
        inputBinding('searchPlaceholder', this.searchPlaceholder),
        outputBinding<Omit<WidgetConfig, 'id'> | undefined>('closed', widgetConfig => {
          this.viewState.set('dashboard');
          this.catalogHost().clear();
          Eif (widgetConfig) {
            this.grid().addWidgetInstance(widgetConfig);
          }
        })
      ]
    });
    catalogRef.instance.widgetCatalog = this.widgetCatalog();
  }
 
  protected onModified(event: boolean): void {
    this.isModified.emit(event);
    this.toolbar().disableSaveButton.set(!event);
  }
 
  private setupMenuItems(): void {
    const primaryEditActions = [...this.primaryEditActions(), ...this.globalEditActions.primary];
    const secondaryEditActions = [
      ...this.secondaryEditActions(),
      ...this.globalEditActions.secondary
    ];
    const primaryMenuItems = primaryEditActions.length
      ? of(primaryEditActions)
      : this.widgetStorage.getToolbarMenuItems
        ? this.widgetStorage.getToolbarMenuItems(this.dashboardId()).primary
        : of([]);
    combineLatest([primaryMenuItems, this.hideAddWidgetInstanceButton$])
      .pipe(takeUntil(this.dashboardId$))
      .subscribe(([items, hideAddButton]) => this.setupPrimaryMenuItems(items, hideAddButton));
 
    const secondaryMenuItems = secondaryEditActions.length
      ? of(secondaryEditActions)
      : this.widgetStorage.getToolbarMenuItems
        ? this.widgetStorage.getToolbarMenuItems(this.dashboardId()).secondary
        : undefined;
 
    if (secondaryMenuItems) {
      secondaryMenuItems
        .pipe(takeUntil(this.dashboardId$))
        .subscribe(items => this.secondaryEditActions$.next(items));
    }
  }
 
  private setupPrimaryMenuItems(
    items: (MenuItem | DashboardToolbarItem)[],
    hideAddWidgetInstanceButton: boolean
  ): void {
    const next: (MenuItem | DashboardToolbarItem)[] = hideAddWidgetInstanceButton
      ? []
      : [this.addWidgetInstanceAction];
    next.push(...items);
    this.primaryEditActions$.next(next);
  }
 
  protected editWidgetInstance(widgetConfig: WidgetConfig): void {
    const dashboard = this.dashboard();
    if (dashboard.isExpanded) {
      dashboard.restore();
    }
    const widget = this.getWidget(widgetConfig.widgetId);
    const widgetInstanceEditorDialogComponent = this.widgetInstanceEditorDialogComponent();
    const componentType =
      widgetInstanceEditorDialogComponent ?? SiWidgetInstanceEditorDialogComponent;
 
    this.viewState.set('editor');
    this.catalogHost().createComponent<SiWidgetInstanceEditorDialogComponent>(componentType, {
      bindings: [
        inputBinding('widgetConfig', () => widgetConfig),
        inputBinding('widget', () => widget),
        outputBinding<WidgetConfig | undefined>('closed', editedWidgetConfig => {
          this.viewState.set('dashboard');
          this.catalogHost().clear();
          if (editedWidgetConfig) {
            this.grid().updateWidgetInstance(editedWidgetConfig);
          }
        })
      ]
    });
  }
 
  private getWidget(id: string): Widget | undefined {
    return this.widgetCatalog().find(widget => widget.id === id);
  }
}