All files / src/components/widget-instance-editor-dialog si-widget-instance-editor-dialog.component.ts

61% Statements 61/100
40.27% Branches 29/72
65.51% Functions 19/29
57.3% Lines 51/89

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                                                                                              20x         5x           5x           5x         5x   5x     5x   5x 4x     5x                           5x   5x         5x 5x 5x 5x 5x   5x   5x   5x   5x 5x   5x 5x   5x 5x               5x   5x       5x 5x 5x 5x     4x           4x 4x     4x     4x       4x           4x             4x                     4x         5x       1x 1x                                                                                   1x               1x       5x 5x 5x 5x           4x                        
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import {
  Component,
  computed,
  EnvironmentInjector,
  inject,
  Injector,
  input,
  isSignal,
  model,
  OnDestroy,
  OnInit,
  output,
  OutputRefSubscription,
  signal,
  viewChild,
  ViewContainerRef
} from '@angular/core';
import { SiActionDialogService } from '@siemens/element-ng/action-modal';
import { SiTranslatePipe, t } from '@siemens/element-translate-ng/translate';
import { Subscription } from 'rxjs';
 
import {
  Widget,
  WidgetConfig,
  WidgetConfigStatus,
  WidgetInstanceEditor,
  WidgetInstanceEditorWizard,
  WidgetInstanceEditorWizardState
} from '../../model/widgets.model';
import { setupWidgetEditor } from '../../widget-loader';
 
/**
 * The Dialog component is utilized when editing a widget instance within a dashboard.
 * It dynamically loads and creates the associated widget editor and incorporates it
 * into its content. The dialog component is accountable for interacting with the dashboard
 * and offers options for saving changes or terminating the editing process.
 */
@Component({
  selector: 'si-widget-instance-editor-dialog',
  imports: [SiTranslatePipe],
  templateUrl: './si-widget-instance-editor-dialog.component.html',
  styleUrl: './si-widget-instance-editor-dialog.component.scss'
})
export class SiWidgetInstanceEditorDialogComponent implements OnInit, OnDestroy {
  /**
   * Input for the widget instance configuration. It is used to populate the
   * widget editor.
   */
  readonly widgetConfig = model.required<WidgetConfig>();
 
  /**
   * Input for the widget definition. It is required to retrieve the component
   * factory to instantiate the widget editor.
   */
  readonly widget = input.required<Widget>();
 
  /**
   * Emits the edited widget instance configuration if the user confirms by
   * saving, or `undefined` if the user cancels the dialog.
   */
  readonly closed = output<WidgetConfig | undefined>();
 
  /**
   * Emits when the editor instantiation is completed.
   */
  readonly editorSetupCompleted = output<void>();
 
  protected readonly editorHost = viewChild.required('editorHost', { read: ViewContainerRef });
 
  /** Indicates if the current config is valid or not. If invalid, the save button will be disabled. */
  protected readonly invalidConfig = signal(false);
 
  protected readonly showNextButton = computed(() =>
    this.editorWizardState() !== undefined ? true : false
  );
 
  protected readonly disableNextButton = computed(() => {
    const wizardState = this.editorWizardState();
 
    if (!wizardState) {
      return true;
    } else if (!wizardState.hasNext) {
      return true;
    } else if (wizardState.disableNext !== undefined) {
      return wizardState.disableNext;
    } else {
      return false;
    }
  });
 
  protected readonly showPreviousButton = computed(() => !!this.editorWizardState());
 
  protected readonly disablePreviousButton = computed(() => {
    const wizardState = this.editorWizardState();
    return wizardState ? !wizardState.hasPrevious : true;
  });
 
  protected labelSave = t(() => $localize`:@@DASHBOARD.WIDGET_EDITOR_DIALOG.SAVE:Save`);
  protected labelCancel = t(() => $localize`:@@DASHBOARD.WIDGET_EDITOR_DIALOG.CANCEL:Cancel`);
  protected labelPrevious = t(() => $localize`:@@DASHBOARD.WIDGET_EDITOR_DIALOG.PREVIOUS:Previous`);
  protected labelNext = t(() => $localize`:@@DASHBOARD.WIDGET_EDITOR_DIALOG.NEXT:Next`);
  protected labelDialogMessage = t(
    () =>
      $localize`:@@DASHBOARD.WIDGET_EDITOR_DIALOG.DISCARD_CONFIG_CHANGE_DIALOG.MESSAGE:The widget configuration changed. Do you want to discard the changes?`
  );
  protected labelDialogHeading = t(
    () =>
      $localize`:@@DASHBOARD.WIDGET_EDITOR_DIALOG.DISCARD_CONFIG_CHANGE_DIALOG.HEADING:Widget configuration changed`
  );
  protected labelDialogSave = t(
    () => $localize`:@@DASHBOARD.WIDGET_EDITOR_DIALOG.DISCARD_CONFIG_CHANGE_DIALOG.SAVE:Save`
  );
  protected labelDialogDiscard = t(
    () => $localize`:@@DASHBOARD.WIDGET_EDITOR_DIALOG.DISCARD_CONFIG_CHANGE_DIALOG.DISCARD:Discard`
  );
  protected labelDialogCancel = t(
    () => $localize`:@@DASHBOARD.WIDGET_EDITOR_DIALOG.DISCARD_CONFIG_CHANGE_DIALOG.CANCEL:Cancel`
  );
 
  /**
   * Marks the widget configuration as modified. Is set when widget editor instance
   * emits configChange events. Triggers edit discard confirmation dialog when widget config
   * is modified but not dialog is canceled.
   * */
  private readonly widgetConfigModified = signal(false);
  private widgetInstanceEditor?: WidgetInstanceEditor;
  private readonly editorWizardState = signal<WidgetInstanceEditorWizardState | undefined>(
    undefined
  );
 
  private subscriptions: Subscription[] | OutputRefSubscription[] = [];
  private injector = inject(Injector);
  private envInjector = inject(EnvironmentInjector);
  private dialogService = inject(SiActionDialogService);
 
  ngOnInit(): void {
    setupWidgetEditor(
      this.widget().componentFactory,
      this.editorHost(),
      this.injector,
      this.envInjector
    ).subscribe(componentRef => {
      this.widgetInstanceEditor = componentRef.instance;
      Iif (isSignal(this.widgetInstanceEditor.config)) {
        componentRef.setInput('config', this.widgetConfig()!);
      } else {
        this.widgetInstanceEditor.config = this.widgetConfig()!;
      }
      // To be used by webcomponent wrapper
      Iif ('statusChangesHandler' in this.widgetInstanceEditor) {
        this.widgetInstanceEditor.statusChangesHandler = this.handleStatusChanges.bind(this);
      }
 
      Iif (this.widgetInstanceEditor.statusChanges) {
        this.subscriptions.push(
          this.widgetInstanceEditor.statusChanges.subscribe(statusChanges =>
            this.handleStatusChanges(statusChanges)
          ) as Subscription
        );
      I} else if (this.widgetInstanceEditor.configChange) {
        this.subscriptions.push(
          this.widgetInstanceEditor.configChange.subscribe(() =>
            this.widgetConfigModified.set(true)
          ) as Subscription
        );
      }
      Iif (this.isEditorWizard(this.widgetInstanceEditor)) {
        this.editorWizardState.set(this.widgetInstanceEditor.state);
 
        if (this.widgetInstanceEditor.stateChange) {
          this.subscriptions.push(
            this.widgetInstanceEditor.stateChange.subscribe(state => {
              this.editorWizardState.set(state);
            }) as Subscription
          );
        }
      }
      this.editorSetupCompleted.emit();
    });
  }
 
  ngOnDestroy(): void {
    this.tearDownEditor();
  }
 
  protected onCancel(): void {
    if (!this.widgetConfigModified()) {
      this.closed.emit(undefined);
    } else E{
      this.dialogService
        .showActionDialog({
          type: 'edit-discard',
          disableSave: this.invalidConfig(),
          message: this.labelDialogMessage,
          heading: this.labelDialogHeading,
          saveBtnName: this.labelDialogSave,
          discardBtnName: this.labelDialogDiscard,
          cancelBtnName: this.labelDialogCancel,
          disableSaveMessage: this.labelDialogMessage,
          disableSaveDiscardBtnName: this.labelDialogDiscard
        })
        .subscribe(result => {
          if (result === 'discard') {
            this.closed.emit(undefined);
          } else if (result === 'save') {
            this.closed.emit(this.widgetConfig());
          }
        });
    }
  }
 
  protected onNext(): void {
    if (this.isEditorWizard(this.widgetInstanceEditor)) {
      this.widgetInstanceEditor.next();
      this.editorWizardState.set(this.widgetInstanceEditor.state);
    }
  }
 
  protected onPrevious(): void {
    if (this.isEditorWizard(this.widgetInstanceEditor) && this.editorWizardState()?.hasPrevious) {
      this.widgetInstanceEditor.previous();
      this.editorWizardState.set(this.widgetInstanceEditor.state);
    }
  }
 
  protected onSave(): void {
    // In case the widget instance editor did not only change values of the config
    // object, but set a new config object reference, we need to grab it and replace
    // our local config object.
    Iif (this.widgetInstanceEditor?.config) {
      if (isSignal(this.widgetInstanceEditor.config)) {
        this.widgetConfig.set(this.widgetInstanceEditor?.config() as WidgetConfig);
      } else {
        this.widgetConfig.set(this.widgetInstanceEditor?.config as WidgetConfig);
      }
    }
 
    this.closed.emit(this.widgetConfig());
  }
 
  private tearDownEditor(): void {
    this.editorWizardState.set(undefined);
    this.widgetInstanceEditor = undefined;
    this.subscriptions.forEach(s => s.unsubscribe());
    this.subscriptions = [];
  }
 
  private isEditorWizard(
    editor?: WidgetInstanceEditor | WidgetInstanceEditorWizard
  ): editor is WidgetInstanceEditorWizard {
    return !!editor && 'state' in editor;
  }
 
  private handleStatusChanges(statusChanges: Partial<WidgetConfigStatus>): void {
    if (statusChanges.invalid !== undefined) {
      this.invalidConfig.set(statusChanges.invalid);
    }
    if (statusChanges.modified !== undefined) {
      this.widgetConfigModified.set(statusChanges.modified);
    }
  }
}