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

91.5% Statements 183/200
72.3% Branches 94/130
87.8% Functions 36/41
91.57% Lines 174/190

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 461 462 463 464 465 466 467 468 469 470 471 472                                                                                  2x                                     197x 57x 57x 57x 57x 57x 57x 57x     57x   57x         57x             57x   57x 57x 57x   57x   57x   57x 57x 57x 57x 57x   57x   57x 57x   57x 57x   57x 57x   57x 57x   57x   57x   57x   57x   57x 57x   57x   57x           57x   57x   57x   57x   57x                           57x         2x                           57x         2x       57x 56x 56x       57x 56x 1x     1x         57x 1x         55x       4x     4x 4x 4x 4x             2x     2x 2x 2x                   13x 1x     12x 12x 13x       12x 12x 6x   6x         6x 6x 6x   1x 1x   2x 2x   1x 1x   2x 2x       6x 2x   4x 4x 4x 4x 4x       6x 6x 6x 6x 6x   6x   1x 1x 1x   1x   2x 1x   1x 1x 1x   2x   1x 1x 1x   1x   2x 1x   1x 1x 1x   2x       6x 6x 6x 6x             6x       6x       16x       16x     16x       55x 55x 52x             52x 52x 52x               52x     52x   52x 52x         3x         58x 32x   58x           58x 26x 26x 26x   26x 26x   26x 24x   2x   26x           26x   26x   32x 32x 32x     58x 58x     58x           2x 2x 2x   2x 2x 2x         26x 26x       4x       4x                 2x 2x          
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { LiveAnnouncer } from '@angular/cdk/a11y';
import { NgTemplateOutlet } from '@angular/common';
import {
  Component,
  ComponentRef,
  computed,
  DestroyRef,
  ElementRef,
  EnvironmentInjector,
  inject,
  Injector,
  input,
  isSignal,
  OnChanges,
  OnInit,
  output,
  signal,
  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 {
  injectSiTranslateService,
  SiTranslatePipe,
  t
} from '@siemens/element-translate-ng/translate';
import { GridItemHTMLElement, GridStackNode } from 'gridstack';
import { first } from 'rxjs';
 
import {
  WidgetComponentFactory,
  WidgetConfig,
  WidgetConfigEvent,
  WidgetInstance
} from '../../model/widgets.model';
import { setupWidgetInstance } from '../../widget-loader';
 
@Component({
  selector: 'si-widget-host',
  imports: [SiDashboardCardComponent, NgTemplateOutlet, SiTranslatePipe],
  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 injector = inject(Injector);
  private readonly envInjector = inject(EnvironmentInjector);
  private readonly destroyRef = inject(DestroyRef);
  private readonly translateService = injectSiTranslateService();
  private readonly liveAnnouncer = inject(LiveAnnouncer);
  private readonly elementRef = inject<ElementRef<GridItemHTMLElement>>(ElementRef).nativeElement;
 
  /** @defaultValue false */
  readonly keyboardActive = signal(false);
 
  readonly widgetConfig = input.required<WidgetConfig>();
 
  /**
   * The component factory for this widget's type.
   */
  readonly componentFactory = input<WidgetComponentFactory>();
 
  /**
   * Sets the widget host into editable mode.
   *
   * @defaultValue false
   */
  readonly editable = input(false);
 
  readonly remove = output<string>();
  readonly edit = output<WidgetConfig>();
  readonly gridEvent = output<Event>();
 
  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`
  );
  private a11yWidgetMovedMessage = t(
    () => $localize`:@@DASHBOARD.WIDGET.A11Y.MOVED:Widget moved to column {{column}}, row {{row}}.`
  );
  private a11yWidgetResizedMessage = t(
    () =>
      $localize`:@@DASHBOARD.WIDGET.A11Y.RESIZED:Widget resized to {{columns}} columns wide, {{rows}} rows tall.`
  );
  private a11yWidgetActivatedMessage = t(
    () =>
      $localize`:@@DASHBOARD.WIDGET.A11Y.ACTIVATED:Widget activated. Use arrow keys to move, Shift+arrow keys to resize, Escape to exit.`
  );
  private a11yWidgetDeactivatedMessage = t(
    () => $localize`:@@DASHBOARD.WIDGET.A11Y.DEACTIVATED:Widget deactivated.`
  );
  protected a11yWidgetDescription = t(
    () =>
      $localize`:@@DASHBOARD.WIDGET.A11Y.DESCRIPTION:Press Enter or Space to activate. Then use arrow keys to move, Shift+arrow keys to resize, Escape to exit.`
  );
 
  widgetInstance?: WidgetInstance;
  widgetRef?: ComponentRef<WidgetInstance>;
  /** @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 ? 'accent-' + accentLine : '';
  });
 
  ngOnChanges(changes: SimpleChanges<this>): void {
    if (changes.widgetConfig) {
      if (this.widgetRef) {
        Iif (isSignal(this.widgetRef.instance.config)) {
          this.widgetRef.setInput('config', this.widgetConfig());
        } else {
          this.widgetRef.instance.config = this.widgetConfig();
        }
      }
    }
 
    if (changes.editable && !changes.editable.firstChange) {
      this.setupEditable(this.editable());
    }
  }
 
  ngOnInit(): void {
    this.attachWidgetInstance();
  }
 
  protected onToggleActive(event: Event): void {
    Iif (!this.editable() || event.target !== event.currentTarget) {
      return;
    }
    event.preventDefault();
    const active = !this.keyboardActive();
    this.keyboardActive.set(active);
    this.announceTranslated(
      active ? this.a11yWidgetActivatedMessage : this.a11yWidgetDeactivatedMessage,
      {}
    );
  }
 
  protected onDeactivate(event: Event): void {
    Iif (!this.keyboardActive()) {
      return;
    }
    event.preventDefault();
    this.keyboardActive.set(false);
    this.announceTranslated(this.a11yWidgetDeactivatedMessage, {});
  }
 
  protected onFocusOut(): void {
    if (this.keyboardActive()) {
      this.keyboardActive.set(false);
    }
  }
 
  protected onArrowKey(event: Event): void {
    if (!this.keyboardActive()) {
      return;
    }
 
    const el = this.elementRef;
    const node = el?.gridstackNode;
    Iif (!node?.grid) {
      return;
    }
 
    const keyEvent = event as KeyboardEvent;
    if (keyEvent.shiftKey) {
      this.handleResize(keyEvent, node);
    } else {
      this.handleMove(keyEvent, node);
    }
  }
 
  private handleResize(event: KeyboardEvent, node: GridStackNode): void {
    const el = this.elementRef;
    let { w, h } = node;
    switch (event.key) {
      case 'ArrowRight':
        w = (w ?? 1) + 1;
        break;
      case 'ArrowLeft':
        w = Math.max(node.minW ?? 1, (w ?? 1) - 1);
        break;
      case 'ArrowDown':
        h = (h ?? 1) + 1;
        break;
      case 'ArrowUp':
        h = Math.max(node.minH ?? 1, (h ?? 1) - 1);
        break;
      default:
        return;
    }
    if (w === node.w && h === node.h) {
      return;
    }
    event.preventDefault();
    const grid = node.grid;
    grid!.update(el, { w, h });
    this.gridEvent.emit(new Event('resizestop'));
    this.announceTranslated(this.a11yWidgetResizedMessage, { columns: w, rows: h });
  }
 
  private handleMove(event: KeyboardEvent, node: GridStackNode): void {
    const el = this.elementRef;
    const { x, y } = node;
    const grid = node.grid;
    let newX = x ?? 0;
    let newY = y ?? 0;
 
    switch (event.key) {
      case 'ArrowRight':
        do {
          newX++;
          grid!.update(el, { x: newX, y });
        } while (node.x === x && newX < grid!.getColumn());
        break;
      case 'ArrowLeft':
        if (newX <= 0) {
          break;
        }
        do {
          newX--;
          grid!.update(el, { x: newX, y });
        } while (node.x === x && newX > 0);
        break;
      case 'ArrowDown':
        do {
          newY++;
          grid!.update(el, { x, y: newY });
        } while (node.y === y && newY < grid!.getRow());
        break;
      case 'ArrowUp':
        if (newY <= 0) {
          break;
        }
        do {
          newY--;
          grid!.update(el, { x, y: newY });
        } while (node.y === y && newY > 0);
        break;
      default:
        return;
    }
    event.preventDefault();
    this.gridEvent.emit(new Event('dragstop'));
    this.scrollIntoViewAfterTransition(el);
    this.announceTranslated(this.a11yWidgetMovedMessage, {
      column: (node.x ?? 0) + 1,
      row: (node.y ?? 0) + 1
    });
  }
 
  private scrollIntoViewAfterTransition(el: HTMLElement): void {
    const onEnd = (): void => {
      el.removeEventListener('transitionend', onEnd);
      el.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
    };
    el.addEventListener('transitionend', onEnd, { once: true });
  }
 
  private announce(message: string): void {
    this.liveAnnouncer.announce(message, 'assertive');
  }
 
  private announceTranslated(message: string, params: Record<string, unknown>): void {
    this.translateService
      .translateAsync(message, params)
      .pipe(first())
      .subscribe(msg => this.announce(msg));
  }
 
  private attachWidgetInstance(): void {
    const componentFactory = this.componentFactory();
    if (componentFactory) {
      setupWidgetInstance(
        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(), 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 => console.error('Error: ', error)
      });
    } else {
      console.error(`Cannot find widget with id ${this.widgetConfig().widgetId}`);
    }
  }
 
  setupEditable(editable: boolean, widgetConfig?: WidgetConfigEvent): void {
    if (!editable) {
      this.keyboardActive.set(false);
    }
    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 ?? [];
    }
 
    Eif (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();
        }
      });
  }
}