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

92.07% Statements 93/101
75.92% Branches 41/54
88.46% Functions 23/26
92.3% Lines 84/91

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                                                                                            143x 38x 38x 38x 38x 38x   38x   38x 38x   38x   38x   38x 38x 38x 38x 38x   38x   38x 38x   38x 38x   38x 38x           38x   38x   38x 38x     38x   38x                           38x         2x                           38x         2x         105x 105x       37x 37x 1x     1x             36x 36x   36x       36x 36x 33x             33x 33x 33x                   33x     33x   33x 33x         3x         73x           73x 4x 4x 4x   4x 4x   4x 2x   2x   4x           4x   4x   69x 69x 69x     73x 37x     37x           2x 2x 2x   2x 2x 2x         4x 4x             4x       4x                 2x 2x          
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { AsyncPipe, NgTemplateOutlet } from '@angular/common';
import {
  Component,
  ComponentRef,
  DestroyRef,
  EnvironmentInjector,
  inject,
  Injector,
  input,
  isSignal,
  OnChanges,
  OnInit,
  output,
  SimpleChanges,
  TemplateRef,
  viewChild,
  ViewContainerRef
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { SiActionDialogService } from '@siemens/element-ng/action-modal';
// We need one import from the main entry.
// Otherwise, module federation is confused.
// I don't know why.
import type { MenuItem as MenuItemLegacy } from '@siemens/element-ng/common';
import { ContentActionBarMainItem, ViewType } from '@siemens/element-ng/content-action-bar';
import { SiDashboardCardComponent } from '@siemens/element-ng/dashboard';
import { MenuItem } from '@siemens/element-ng/menu';
import { t } from '@siemens/element-translate-ng/translate';
 
import { WidgetConfig, WidgetConfigEvent, WidgetInstance } from '../../model/widgets.model';
import { SiGridService } from '../../services/si-grid.service';
import { setupWidgetInstance } from '../../widget-loader';
 
@Component({
  selector: 'si-widget-host',
  imports: [SiDashboardCardComponent, AsyncPipe, NgTemplateOutlet],
  templateUrl: './si-widget-host.component.html',
  styleUrl: './si-widget-host.component.scss',
  host: {
    class: 'grid-stack-item'
  }
})
export class SiWidgetHostComponent implements OnInit, OnChanges {
  private readonly siModal = inject(SiActionDialogService);
  private readonly gridService = inject(SiGridService);
  private readonly injector = inject(Injector);
  private readonly envInjector = inject(EnvironmentInjector);
  private readonly destroyRef = inject(DestroyRef);
 
  readonly widgetConfig = input.required<WidgetConfig>();
 
  readonly remove = output<string>();
  readonly edit = output<WidgetConfig>();
 
  readonly card = viewChild.required<SiDashboardCardComponent>('card');
 
  readonly widgetHost = viewChild.required('widgetHost', { read: ViewContainerRef });
 
  protected labelEdit = t(() => $localize`:@@DASHBOARD.WIDGET.EDIT:Edit`);
  protected labelRemove = t(() => $localize`:@@DASHBOARD.WIDGET.REMOVE:Remove`);
  protected labelExpand = t(() => $localize`:@@DASHBOARD.WIDGET.EXPAND:Expand`);
  protected labelRestore = t(() => $localize`:@@DASHBOARD.WIDGET.RESTORE:Restore`);
  protected labelDialogMessage = t(
    () =>
      $localize`:@@DASHBOARD.REMOVE_WIDGET_CONFIRMATION_DIALOG.MESSAGE:Do you really want to remove the widget?`
  );
  protected labelDialogHeading = t(
    () => $localize`:@@DASHBOARD.REMOVE_WIDGET_CONFIRMATION_DIALOG.HEADING:Remove widget`
  );
  protected labelDialogRemove = t(
    () => $localize`:@@DASHBOARD.REMOVE_WIDGET_CONFIRMATION_DIALOG.REMOVE:Remove`
  );
  protected labelDialogCancel = t(
    () => $localize`:@@DASHBOARD.REMOVE_WIDGET_CONFIRMATION_DIALOG.CANCEL:Cancel`
  );
 
  widgetInstance?: WidgetInstance;
  widgetRef?: ComponentRef<WidgetInstance>;
  /** @defaultValue [] */
  primaryActions: (MenuItemLegacy | ContentActionBarMainItem)[] = [];
  /** @defaultValue [] */
  secondaryActions: (MenuItemLegacy | MenuItem)[] = [];
  /** @defaultValue 'expanded' */
  actionBarViewType: ViewType = 'expanded';
  editable$ = this.gridService.editable$;
 
  /** @defaultValue [] */
  editablePrimaryActions: (MenuItemLegacy | ContentActionBarMainItem)[] = [];
  /** @defaultValue [] */
  editableSecondaryActions: (MenuItemLegacy | MenuItem)[] = [];
 
  /**
   * @defaultValue
   * ```
   * {
   *   type: 'action',
   *   label: this.labelEdit,
   *   icon: 'element-edit',
   *   iconOnly: true,
   *   action: () => this.onEdit()
   * }
   * ```
   */
  editAction: ContentActionBarMainItem = {
    type: 'action',
    label: this.labelEdit,
    icon: 'element-edit',
    iconOnly: true,
    action: () => this.onEdit()
  };
  /**
   * @defaultValue
   * ```
   * {
   *   type: 'action',
   *   label: this.labelRemove,
   *   icon: 'element-delete',
   *   iconOnly: true,
   *   action: () => this.onRemove()
   * }
   * ```
   */
  removeAction: ContentActionBarMainItem = {
    type: 'action',
    label: this.labelRemove,
    icon: 'element-delete',
    iconOnly: true,
    action: () => this.onRemove()
  };
  protected widgetInstanceFooter?: TemplateRef<unknown>;
 
  protected get accentLine(): string {
    const widgetConfig = this.widgetConfig();
    return widgetConfig.accentLine ? 'accent-' + widgetConfig.accentLine : '';
  }
 
  ngOnChanges(changes: SimpleChanges<this>): void {
    Eif (changes.widgetConfig) {
      if (this.widgetRef) {
        Iif (isSignal(this.widgetRef.instance.config)) {
          this.widgetRef.setInput('config', this.widgetConfig());
        } else {
          this.widgetRef.instance.config = this.widgetConfig();
        }
      }
    }
  }
 
  ngOnInit(): void {
    this.attachWidgetInstance();
    this.editable$
      .pipe<boolean>(takeUntilDestroyed(this.destroyRef))
      .subscribe(editable => this.setupEditable(editable));
  }
 
  private attachWidgetInstance(): void {
    const widget = this.gridService.getWidget(this.widgetConfig().widgetId);
    if (widget) {
      setupWidgetInstance(
        widget.componentFactory,
        this.widgetHost(),
        this.injector,
        this.envInjector
      ).subscribe({
        next: (widgetRef: ComponentRef<WidgetInstance>) => {
          this.widgetInstance = widgetRef.instance;
          this.widgetRef = widgetRef;
          Iif (this.widgetInstance.configChange) {
            // Note: setTimeout is needed to prevent ExpressionChangedAfterItHasBeenCheckedError
            // on web component, who pushes their configuration through an event after being attached
            // to the DOM.
            this.widgetInstance.configChange
              .pipe(takeUntilDestroyed(this.destroyRef))
              .subscribe(event =>
                setTimeout(() => this.setupEditable(this.editable$.value, event))
              );
          }
          Iif (isSignal(this.widgetInstance.config)) {
            this.widgetRef.setInput('config', this.widgetConfig());
          } else {
            this.widgetInstance.config = this.widgetConfig();
          }
          this.widgetInstanceFooter = this.widgetInstance.footer;
          this.setupEditable(this.gridService.editable$.value);
        },
        error: error => console.error('Error: ', error)
      });
    } else {
      console.error(`Cannot find widget with id ${this.widgetConfig().widgetId}`);
    }
  }
 
  setupEditable(editable: boolean, widgetConfig?: WidgetConfigEvent): void {
    widgetConfig ??= {
      primaryActions: this.widgetInstance?.primaryActions,
      secondaryActions: this.widgetInstance?.secondaryActions,
      primaryEditActions: this.widgetInstance?.primaryEditActions,
      secondaryEditActions: this.widgetInstance?.secondaryEditActions
    };
    if (editable) {
      this.editablePrimaryActions = [];
      Eif (this.isEditable()) {
        this.editablePrimaryActions.push(this.editAction);
      }
      Eif (!this.widgetConfig().isNotRemovable) {
        this.editablePrimaryActions.push(this.removeAction);
      }
      if (widgetConfig.primaryEditActions) {
        this.primaryActions = [...widgetConfig.primaryEditActions, ...this.editablePrimaryActions];
      } else {
        this.primaryActions = this.editablePrimaryActions;
      }
      Iif (widgetConfig.secondaryEditActions) {
        this.secondaryActions = [
          ...widgetConfig.secondaryEditActions,
          ...this.editableSecondaryActions
        ];
      } else {
        this.secondaryActions = this.editableSecondaryActions;
      }
      this.actionBarViewType = 'expanded';
    } else {
      this.actionBarViewType = this.widgetConfig().actionBarViewType ?? 'expanded';
      this.primaryActions = widgetConfig.primaryActions ?? [];
      this.secondaryActions = widgetConfig.secondaryActions ?? [];
    }
 
    if (this.widgetInstance?.editable !== undefined) {
      Iif (isSignal(this.widgetInstance.editable)) {
        this.widgetRef?.setInput('editable', editable);
      } else {
        this.widgetInstance.editable = editable;
      }
    }
  }
 
  private doRemove(): void {
    const card = this.card();
    Eif (card.isExpanded()) {
      card.restore();
    }
    const widgetConfig = this.widgetConfig();
    Eif (widgetConfig.id) {
      this.remove.emit(widgetConfig.id);
    }
  }
 
  private isEditable(): boolean {
    const widgetConfig = this.widgetConfig();
    return (
      !widgetConfig.immutable &&
      !!this.gridService.getWidget(widgetConfig.widgetId)?.componentFactory?.editorComponentName
    );
  }
 
  onEdit(): void {
    this.edit.emit(this.widgetConfig());
  }
 
  onRemove(): void {
    this.siModal
      .showActionDialog({
        type: 'delete-confirm',
        message: this.labelDialogMessage,
        heading: this.labelDialogHeading,
        deleteBtnName: this.labelDialogRemove,
        cancelBtnName: this.labelDialogCancel
      })
      .subscribe(result => {
        Eif (result === 'delete') {
          this.doRemove();
        }
      });
  }
}