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

90.15% Statements 119/132
74.41% Branches 64/86
90.32% Functions 28/31
89.91% Lines 107/119

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                                                                                                        159x 42x 42x 42x 42x   42x         42x             42x             42x   42x 42x   42x   42x   42x 42x 42x 42x 42x   42x 42x 42x   42x   42x 42x   42x 42x   42x 42x     42x       42x   42x   42x   42x   42x   42x                           42x         2x                           42x         2x       42x 43x 43x   43x     43x         43x 3x 3x 1x     1x         43x           40x       43x 4x 4x 4x     39x 38x         38x       38x 38x 35x 35x             35x 35x 35x 35x               35x     35x   35x 35x               3x         4x 4x 4x 4x 4x       43x           43x 4x 4x 4x   4x 4x   4x 2x   2x   4x           4x   4x   39x 39x 39x     43x 39x     39x           2x 2x 2x   2x 2x 2x         4x 4x       4x       4x                 2x 2x          
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { NgTemplateOutlet } from '@angular/common';
import {
  AfterViewInit,
  Component,
  ComponentRef,
  computed,
  DestroyRef,
  EnvironmentInjector,
  inject,
  Injector,
  input,
  isSignal,
  OnChanges,
  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 { SiEmptyStateComponent } from '@siemens/element-ng/empty-state';
import { MenuItem } from '@siemens/element-ng/menu';
import { t } from '@siemens/element-translate-ng/translate';
 
import {
  WidgetComponentFactory,
  WidgetConfig,
  WidgetConfigEvent,
  WidgetInstance
} from '../../model/widgets.model';
import { setupWidgetInstance } from '../../widget-loader';
 
@Component({
  selector: 'si-widget-host',
  imports: [SiDashboardCardComponent, SiEmptyStateComponent, NgTemplateOutlet],
  templateUrl: './si-widget-host.component.html',
  styleUrl: './si-widget-host.component.scss',
  host: {
    class: 'grid-stack-item'
  }
})
export class SiWidgetHostComponent implements AfterViewInit, OnChanges {
  private readonly siModal = inject(SiActionDialogService);
  private readonly injector = inject(Injector);
  private readonly envInjector = inject(EnvironmentInjector);
  private readonly destroyRef = inject(DestroyRef);
 
  readonly widgetConfig = input.required<WidgetConfig>();
 
  /**
   * The component factory for this widget's type.
   */
  readonly componentFactory = input<WidgetComponentFactory>();
 
  /**
   * CSS icon class for the widget, displayed in the configuration placeholder.
   *
   * @defaultValue 'element-apps'
   */
  readonly iconClass = input('element-apps');
 
  /**
   * Sets the widget host into editable mode.
   *
   * @defaultValue false
   */
  readonly editable = input(false);
 
  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 labelSetup = t(() => $localize`:@@DASHBOARD.WIDGET.SETUP:Setup required`);
  protected labelSetupMessage = t(
    () => $localize`:@@DASHBOARD.WIDGET.SETUP_MESSAGE:Edit widget to display data`
  );
  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`
  );
 
  protected readonly emptyStateIcon = computed(() => `${this.iconClass()} si-display-xl`);
 
  widgetInstance?: WidgetInstance;
  widgetRef?: ComponentRef<WidgetInstance>;
  private attaching = false;
  /** @defaultValue [] */
  primaryActions: (MenuItemLegacy | ContentActionBarMainItem)[] = [];
  /** @defaultValue [] */
  secondaryActions: (MenuItemLegacy | MenuItem)[] = [];
  /** @defaultValue 'expanded' */
  actionBarViewType: ViewType = 'expanded';
  /** @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 readonly accentLine = computed(() => {
    const { accentLine } = this.widgetConfig();
    return accentLine && !this.setupPending() ? 'accent-' + accentLine : '';
  });
  protected readonly setupPending = computed(() => !!this.widgetConfig().setupPending);
 
  ngOnChanges(changes: SimpleChanges<this>): void {
    Iif (changes.componentFactory && !changes.componentFactory.firstChange) {
      this.detachWidgetInstance();
      this.syncWidgetAttachment();
    }
 
    if (changes.widgetConfig && !changes.widgetConfig.firstChange) {
      this.syncWidgetAttachment();
      if (this.widgetRef) {
        Iif (isSignal(this.widgetRef.instance.config)) {
          this.widgetRef.setInput('config', this.widgetConfig());
        } else {
          this.widgetRef.instance.config = this.widgetConfig();
        }
      }
    }
 
    Iif (changes.editable && !changes.editable.firstChange) {
      this.setupEditable(this.editable());
    }
  }
 
  ngAfterViewInit(): void {
    this.syncWidgetAttachment();
  }
 
  private syncWidgetAttachment(): void {
    if (this.widgetConfig().setupPending) {
      this.detachWidgetInstance();
      this.setupEditable(this.editable());
      return;
    }
 
    if (!this.widgetRef) {
      this.attachWidgetInstance();
    }
  }
 
  private attachWidgetInstance(): void {
    Iif (this.widgetRef || this.attaching) {
      return;
    }
 
    const componentFactory = this.componentFactory();
    if (componentFactory) {
      this.attaching = true;
      setupWidgetInstance(
        componentFactory,
        this.widgetHost(),
        this.injector,
        this.envInjector
      ).subscribe({
        next: (widgetRef: ComponentRef<WidgetInstance>) => {
          this.attaching = false;
          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(), 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.editable());
        },
        error: error => {
          this.attaching = false;
          console.error('Error: ', error);
        }
      });
    } else {
      console.error(`Cannot find widget with id ${this.widgetConfig().widgetId}`);
    }
  }
 
  private detachWidgetInstance(): void {
    this.widgetRef?.destroy();
    this.widgetRef = undefined;
    this.widgetInstance = undefined;
    this.widgetInstanceFooter = undefined;
    this.widgetHost().clear();
  }
 
  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.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();
        }
      });
  }
}