All files / src/components/gridstack-wrapper si-gridstack-wrapper.component.ts

98.27% Statements 57/58
97.05% Branches 33/34
93.33% Functions 14/15
100% Lines 47/47

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                                                                                              118x           25x             25x         25x             25x             25x       25x         25x   25x 25x 20x         25x 25x 25x 25x 25x 25x     42x 17x 17x 17x   17x   17x 4x     17x 17x 9x 2x           42x 4x 4x         25x         25x           25x 25x 25x 25x       29x   29x               20x 20x 19x   1x 1x                   25x     16x 16x                  
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { isPlatformBrowser } from '@angular/common';
import {
  ChangeDetectionStrategy,
  afterNextRender,
  Component,
  computed,
  DestroyRef,
  ElementRef,
  inject,
  Injector,
  input,
  NgZone,
  OnChanges,
  OnInit,
  output,
  PLATFORM_ID,
  SimpleChanges,
  viewChildren
} from '@angular/core';
import { GridItemHTMLElement, GridStack, GridStackNode, GridStackOptions } from 'gridstack';
 
import { DEFAULT_GRIDSTACK_OPTIONS, GridConfig } from '../../model/gridstack.model';
import {
  WidgetComponentFactory,
  WidgetConfig,
  WidgetPositionConfig
} from '../../model/widgets.model';
import { SiWidgetHostComponent } from '../widget-host/si-widget-host.component';
 
export interface GridWrapperEvent {
  event: Event;
  items?: GridStackNode[];
  grid: GridStack;
  el?: GridItemHTMLElement;
}
 
@Component({
  selector: 'si-gridstack-wrapper',
  imports: [SiWidgetHostComponent],
  templateUrl: './si-gridstack-wrapper.component.html',
  styleUrl: './si-gridstack-wrapper.component.scss',
  changeDetection: ChangeDetectionStrategy.Eager
})
export class SiGridstackWrapperComponent implements OnInit, OnChanges {
  /**
   * Grid items to render inside the gridstack
   *
   * @defaultValue []
   */
  readonly widgetConfigs = input<WidgetConfig[]>([]);
 
  /**
   * Whenever gridstack allows to drag, resize or delete the grid item
   *
   * @defaultValue false
   */
  readonly editable = input(false);
 
  /**
   * Module configuration
   */
  readonly gridConfig = input<GridConfig>();
 
  /**
   * Map of widget id to widget definition, passed through to widget hosts.
   *
   * @defaultValue new Map()
   */
  readonly widgetCatalogMap = input<Map<string, { componentFactory: WidgetComponentFactory }>>(
    new Map()
  );
 
  /**
   * Emits dashboard grid events.
   */
  readonly gridEvent = output<GridWrapperEvent>();
  /**
   * Emits the id of a widget instance that shall be removed.
   */
  readonly widgetInstanceRemove = output<string>();
 
  /**
   * Emits the id of a widget instance that shall be edited.
   */
  readonly widgetInstanceEdit = output<WidgetConfig>();
 
  private readonly widgetHosts = viewChildren(SiWidgetHostComponent);
  private readonly widgetHostsMap = computed(
    () => new Map(this.widgetHosts().map(host => [host.widgetConfig().id, host]))
  );
 
  protected grid?: GridStack;
 
  private readonly ngZone = inject(NgZone);
  private readonly elementRef = inject(ElementRef);
  private readonly injector = inject(Injector);
  private readonly platformId = inject(PLATFORM_ID);
  private readonly isBrowser = isPlatformBrowser(this.platformId);
  private readonly destroyRef = inject(DestroyRef);
 
  ngOnChanges(changes: SimpleChanges<this>): void {
    if (changes.widgetConfigs && !changes.widgetConfigs.firstChange) {
      const configs = changes.widgetConfigs.currentValue;
      const newIds = new Set(configs.map(w => w.id));
      const hostMap = this.widgetHostsMap();
 
      const hasAdds = configs.some(w => !hostMap.has(w.id));
 
      if (hasAdds) {
        this.startBatch();
      }
 
      Eif (this.isBrowser) {
        for (const [id, host] of hostMap) {
          if (!newIds.has(id)) {
            this.grid?.removeWidget(host.elementRef);
          }
        }
      }
    }
 
    if (changes.editable && !changes.editable.firstChange) {
      this.grid?.enableMove(changes.editable.currentValue);
      this.grid?.enableResize(changes.editable.currentValue);
    }
  }
 
  ngOnInit(): void {
    const initialViewMode: GridStackOptions = {
      disableDrag: !this.editable(),
      disableResize: !this.editable()
    };
 
    const options: GridStackOptions = {
      ...DEFAULT_GRIDSTACK_OPTIONS,
      ...this.gridConfig()?.gridStackOptions,
      ...initialViewMode
    };
 
    this.grid = GridStack.init(options, this.elementRef.nativeElement.firstChild as HTMLElement);
    this.startBatch();
    this.hookEvents(this.grid);
    this.destroyRef.onDestroy(() => this.grid?.destroy());
  }
 
  private startBatch(): void {
    this.grid?.batchUpdate(true);
    // this ensures that si-widget-host components are rendered before turning off batch mode.
    afterNextRender(() => this.grid?.batchUpdate(false), { injector: this.injector });
  }
 
  /**
   *
   * Returns the position of a specific widget in the grid.
   */
  getWidgetLayout(widgetId: string): WidgetPositionConfig | undefined {
    const gridItem = this.widgetHostsMap().get(widgetId);
    if (!gridItem) {
      return undefined;
    }
    const element = gridItem.elementRef;
    return {
      id: widgetId,
      x: Number(element.getAttribute('gs-x')) || 0,
      y: Number(element.getAttribute('gs-y')) || 0,
      width: Number(element.getAttribute('gs-w')) || 0,
      height: Number(element.getAttribute('gs-h')) || 0
    };
  }
 
  private hookEvents(grid: GridStack): void {
    grid.on(
      'added removed dragstop resizestop disable enable dropped resize resizestart drag dragstart change',
      (event: Event) => {
        this.ngZone.run(() => {
          this.gridEvent.emit({
            event,
            grid
          });
        });
      }
    );
  }
}