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

97.19% Statements 104/107
79.03% Branches 49/62
90% Functions 27/30
96.9% Lines 94/97

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                                                                                                  123x           27x             27x         27x             27x             27x       27x         27x   27x   27x 27x       27x 27x           27x 13x   27x   27x 27x 27x   27x     44x 44x   44x 44x 27x 27x   29x   17x     44x 44x     44x 20x   20x 4x 4x           27x         27x           27x 27x   27x   27x       31x 12x 22x           2x 2x 2x                   23x 23x 19x   4x 4x                   44x   44x 17x 17x 11x 11x 11x 11x             22x 22x   22x 22x     22x                                 22x 22x 22x 22x                     2x   2x 2x     2x 2x 2x 2x 2x 2x 2x                 17x 17x 7x 7x   7x 7x 7x 1x     7x 4x   7x 2x           27x     27x 27x                  
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import {
  Component,
  ComponentRef,
  computed,
  ElementRef,
  inject,
  input,
  inputBinding,
  IterableDiffer,
  IterableDiffers,
  NgZone,
  OnChanges,
  OnInit,
  output,
  outputBinding,
  signal,
  SimpleChanges,
  viewChild,
  ViewContainerRef,
  WritableSignal
} from '@angular/core';
import { SiTranslatePipe, t } from '@siemens/element-translate-ng/translate';
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: [SiTranslatePipe],
  templateUrl: './si-gridstack-wrapper.component.html',
  styleUrl: './si-gridstack-wrapper.component.scss'
})
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>();
 
  readonly gridstackContainer = viewChild('gridstackContainer', { read: ViewContainerRef });
 
  protected readonly a11yWidgetsListLabel = t(
    () => $localize`:@@DASHBOARD.A11Y.WIDGETS_LIST:Dashboard widgets`
  );
 
  private grid!: GridStack;
  private markedForRender: WidgetConfig[] = [];
  private readonly gridItems = signal<
    {
      id: string;
      component: ComponentRef<SiWidgetHostComponent>;
    }[]
  >([]);
  private readonly gridItemsMap = computed(
    () => new Map(this.gridItems().map(item => [item.id, item]))
  );
  private readonly itemIdAttr = 'item-id';
 
  private ngZone = inject(NgZone);
  private elementRef = inject(ElementRef);
  private iterableDiffers = inject(IterableDiffers);
  private widgetConfigsDiffer?: IterableDiffer<WidgetConfig>;
  private readonly widgetConfigSignals = new Map<string, WritableSignal<WidgetConfig>>();
 
  ngOnChanges(changes: SimpleChanges<this>): void {
    Eif (changes.widgetConfigs) {
      const { currentValue, firstChange } = changes.widgetConfigs;
 
      this.grid?.batchUpdate(true);
      if (firstChange) {
        this.markedForRender = currentValue;
        this.widgetConfigsDiffer = this.iterableDiffers
          .find(currentValue)
          .create((_, item: WidgetConfig) => item.id);
      } else {
        this.diffWidgetConfigs(currentValue);
      }
 
      this.updateLayout(currentValue);
      this.grid?.batchUpdate(false);
    }
 
    if (changes.editable) {
      const { currentValue, firstChange } = changes.editable;
 
      if (!firstChange) {
        this.grid.enableMove(currentValue);
        this.grid.enableResize(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.hookEvents(this.grid);
 
    this.mount(this.markedForRender);
    // Run initial diff to prime the differ with the current state
    this.widgetConfigsDiffer?.diff(this.markedForRender);
  }
 
  mount(items: WidgetConfig[]): void {
    if (items.length > 0) {
      items.forEach(item => {
        this.addToView(item);
      });
    }
  }
 
  unmount(items: WidgetConfig[]): void {
    Eif (items.length > 0) {
      items.forEach(item => {
        this.removeFromView(item.id);
      });
    }
  }
 
  /**
   *
   * Returns the position of a specific widget in the grid.
   */
  getWidgetLayout(widgetId: string): WidgetPositionConfig | undefined {
    const gridItem = this.gridItemsMap().get(widgetId);
    if (!gridItem) {
      return undefined;
    }
    const element = gridItem.component.location.nativeElement as HTMLElement;
    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 updateLayout(widgets: WidgetConfig[]): void {
    const widgetConfigMap = new Map(widgets.map(w => [w.id, { ...w, w: w.width, h: w.height }]));
 
    if (this.grid) {
      const gridItems = this.grid.getGridItems();
      gridItems.forEach(gridItem => {
        const itemId = gridItem.getAttribute('item-id');
        const config = widgetConfigMap.get(itemId!);
        Eif (config) {
          this.grid.update(gridItem, config);
        }
      });
    }
  }
 
  private addToView(item: WidgetConfig): void {
    const configSignal = signal(item);
    this.widgetConfigSignals.set(item.id, configSignal);
 
    const componentFactory = computed(
      () => this.widgetCatalogMap().get(item.widgetId)?.componentFactory
    );
 
    const componentRef = this.gridstackContainer()!.createComponent(SiWidgetHostComponent, {
      bindings: [
        inputBinding('widgetConfig', configSignal),
        inputBinding('editable', this.editable),
        inputBinding('componentFactory', componentFactory),
        outputBinding<string>('remove', widgetId => {
          this.widgetInstanceRemove.emit(widgetId);
        }),
        outputBinding<WidgetConfig>('edit', widgetConfig => {
          this.widgetInstanceEdit.emit(widgetConfig);
        }),
        outputBinding<Event>('gridEvent', event => {
          this.gridEvent.emit({ event, grid: this.grid });
        })
      ]
    });
 
    const element = componentRef.location.nativeElement as HTMLElement;
    element.setAttribute(this.itemIdAttr, item.id!);
    this.gridItems.update(items => [...items, { id: item.id!, component: componentRef }]);
    this.grid.makeWidget(element, {
      w: item.width,
      h: item.height,
      x: item.x,
      y: item.y,
      minW: item.minWidth,
      minH: item.minHeight
    });
  }
 
  private removeFromView(widgetId: string): void {
    const gridItemElements = this.grid.getGridItems();
 
    const toRemove = gridItemElements.find(
      (el: HTMLElement) => el.getAttribute(this.itemIdAttr) === widgetId
    );
 
    Eif (toRemove) {
      this.grid.removeWidget(toRemove);
      const gridItemToRemove = this.gridItemsMap().get(widgetId);
      gridItemToRemove?.component.destroy();
      this.widgetConfigSignals.delete(widgetId);
      this.gridItemsMap().delete(widgetId);
      this.gridItems.set(Array.from(this.gridItemsMap().values()));
    }
  }
 
  /**
   * Uses IterableDiffer to detect added, removed, and identity-changed items.
   * Only widgets whose object reference changed get their signal updated.
   */
  private diffWidgetConfigs(configs: WidgetConfig[]): void {
    const changes = this.widgetConfigsDiffer?.diff(configs);
    if (changes) {
      const toMount: WidgetConfig[] = [];
      const toUnmount: WidgetConfig[] = [];
 
      changes.forEachAddedItem(record => toMount.push(record.item));
      changes.forEachRemovedItem(record => toUnmount.push(record.item));
      changes.forEachIdentityChange(record =>
        this.widgetConfigSignals.get(record.item.id)?.set(record.item)
      );
 
      if (toMount.length) {
        this.mount(toMount);
      }
      if (toUnmount.length) {
        this.unmount(toUnmount);
      }
    }
  }
 
  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
          });
        });
      }
    );
  }
}