All files / wizard si-wizard.component.ts

91.27% Statements 136/149
76% Branches 38/50
96.87% Functions 31/32
90.22% Lines 120/133

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                                                                                                              1x 31x                   31x                 31x             31x                 31x           31x                 31x                 31x           31x           31x           31x           31x           31x           31x           31x           31x           31x           31x           31x   31x   31x     31x     31x       5709x         365x         1267x       31x 35x 31x   43x   31x 61x 61x 61x   31x 61x 155x 61x 27x 34x 33x 33x   1x     31x                       1241x       1241x 119x     1122x 200x     922x 1524x 1524x       922x       5x 5x 5x 5x   5x             825x 221x   604x     604x 63x   541x       306x 100x   206x       306x 100x   206x               20x 20x     20x 20x 20x 20x 20x 20x                   4x     4x 4x         1x   1x             1x         306x     306x 306x       24x 24x     24x 24x 24x       31x 31x           66x 66x     66x 4x   4x     4x   62x 62x         132x 43x 1x 42x 4x 38x 100x   4x 4x 4x         20x 20x 20x   20x 4x 4x       34x        
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { NgClass, NgTemplateOutlet } from '@angular/common';
import {
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  contentChildren,
  ElementRef,
  input,
  linkedSignal,
  output,
  signal,
  untracked,
  viewChild
} from '@angular/core';
import { WebComponentContentChildren } from '@siemens/element-ng/common';
import {
  addIcons,
  elementCancel,
  elementChecked,
  elementCheckedFilled,
  elementLeft4,
  elementNotChecked,
  elementRadioChecked,
  elementRight4,
  elementWarningFilled,
  SiIconComponent
} from '@siemens/element-ng/icon';
import { SiResizeObserverDirective } from '@siemens/element-ng/resize-observer';
import { SiTranslatePipe, t } from '@siemens/element-translate-ng/translate';
 
import { SiWizardStepComponent } from './si-wizard-step.component';
 
interface StepItem {
  index: number;
  step: SiWizardStepComponent;
}
 
@Component({
  selector: 'si-wizard',
  imports: [NgClass, SiIconComponent, SiResizeObserverDirective, SiTranslatePipe, NgTemplateOutlet],
  templateUrl: './si-wizard.component.html',
  styleUrl: './si-wizard.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    class: 'py-6 px-8 d-flex flex-column',
    '[class.vertical]': 'verticalLayout()',
    '[style.--wizard-vertical-min-size]': 'verticalMinSize()',
    '[style.--wizard-vertical-max-size]': 'verticalMaxSize()'
  }
})
export class SiWizardComponent {
  protected readonly containerSteps = viewChild<ElementRef<HTMLDivElement>>('containerSteps');
 
  /**
   * Description of back button.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_WIZARD.BACK:Back`)
   * ```
   */
  readonly backText = input(t(() => $localize`:@@SI_WIZARD.BACK:Back`));
  /**
   * Description of next button.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_WIZARD.NEXT:Next`)
   * ```
   */
  readonly nextText = input(t(() => $localize`:@@SI_WIZARD.NEXT:Next`));
 
  /**
   * Hide the navigation buttons previous/next.
   *
   * @defaultValue false
   */
  readonly hideNavigation = input(false, { transform: booleanAttribute });
  /**
   * Description of save button.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_WIZARD.SAVE:Save`)
   * ```
   */
  readonly saveText = input(t(() => $localize`:@@SI_WIZARD.SAVE:Save`));
  /**
   * Hide the save button.
   *
   * @defaultValue false
   */
  readonly hideSave = input(false, { transform: booleanAttribute });
  /**
   * Text shown if you complete the wizard.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_WIZARD.COMPLETED:Wizard completed!`)
   * ```
   */
  readonly completionText = input(t(() => $localize`:@@SI_WIZARD.COMPLETED:Wizard completed!`));
  /**
   * Description of cancel button.
   *
   * @defaultValue
   * ```
   * t(() => $localize`:@@SI_WIZARD.CANCEL:Cancel`)
   * ```
   */
  readonly cancelText = input(t(() => $localize`:@@SI_WIZARD.CANCEL:Cancel`));
  /**
   * Show the cancel button
   *
   * @defaultValue false
   */
  readonly hasCancel = input(false, { transform: booleanAttribute });
  /**
   * Display a predefined page by the end of the wizard.
   *
   * @defaultValue false
   */
  readonly enableCompletionPage = input(false, { transform: booleanAttribute });
  /**
   * Define how many milliseconds the completion page is visible.
   *
   * @defaultValue 3000
   */
  readonly completionPageVisibleTime = input(3000);
  /**
   * Class name of icon shown for current and upcoming steps.
   *
   * @defaultValue 'elementNotChecked'
   */
  readonly stepIcon = input('elementNotChecked');
  /**
   * Class name of icon shown for the active step.
   *
   * @defaultValue 'elementRadioChecked'
   */
  readonly stepActiveIcon = input('elementRadioChecked');
  /**
   * Class name of icon shown when a step was completed.
   *
   * @defaultValue 'elementCheckedFilled'
   */
  readonly stepCompletedIcon = input('elementCheckedFilled');
  /**
   * Class name of icon shown when a step had an error.
   *
   * @defaultValue 'elementWarningFilled'
   */
  readonly stepFailedIcon = input('elementWarningFilled');
  /**
   * Set the orientation of the wizard to vertical.
   *
   * @defaultValue false
   */
  readonly verticalLayout = input(false, { transform: booleanAttribute });
  /**
   * Set false to show navigation buttons in footer instead of inline.
   *
   * @defaultValue false
   */
  readonly inlineNavigation = input(false, { transform: booleanAttribute });
  /**
   * Use number representation for steps.
   *
   * @defaultValue false
   */
  readonly showStepNumbers = input(false, { transform: booleanAttribute });
  /**
   * Set to true to display a divider between the steps and the content in the vertical
   *
   * @defaultValue false
   */
  readonly showVerticalDivider = input(false, { transform: booleanAttribute });
  /** Set the wizard step container min size in vertical layout. */
  readonly verticalMinSize = input<string>();
  /** Set the wizard step container max size in vertical layout. */
  readonly verticalMaxSize = input<string>();
 
  /** Callback function triggered after the wizard has been completed. */
  readonly completionAction = output();
 
  /** Callback function triggered if the wizard has been canceled. */
  readonly wizardCancel = output();
 
  /** Get the current step wizard step index. */
  get index(): number {
    return this._index();
  }
 
  /** Get number of wizard steps. */
  get stepCount(): number {
    return this.steps().length;
  }
 
  /** Get current visible wizard step. */
  get currentStep(): SiWizardStepComponent | undefined {
    return this._currentStep();
  }
 
  @WebComponentContentChildren(SiWizardStepComponent)
  protected readonly steps = contentChildren(SiWizardStepComponent);
  protected readonly visibleSteps = linkedSignal(() => this.calculateVisibleStepCount());
  protected readonly showCompletionPage = signal(false);
  /** The list of visible steps. */
  protected readonly activeSteps = computed(() => this.computeVisibleSteps());
 
  private readonly _index = linkedSignal(() => {
    const currentStep = this._currentStep();
    const currentStepIndex = currentStep ? this.steps().indexOf(currentStep) : 0;
    return currentStepIndex < 0 ? 0 : currentStepIndex;
  });
  private readonly _currentStep = linkedSignal(() => {
    const steps = this.steps();
    const currentActive = steps.find(step => step.isActive());
    if (currentActive) {
      return currentActive;
    } else if (steps.length) {
      untracked(() => steps[0].isActive.set(true));
      return steps[0];
    } else {
      return undefined;
    }
  });
  protected readonly icons = addIcons({
    elementCancel,
    elementChecked,
    elementCheckedFilled,
    elementLeft4,
    elementNotChecked,
    elementRight4,
    elementRadioChecked,
    elementWarningFilled
  });
 
  protected canActivate(stepIndex: number): boolean {
    Iif (stepIndex < 0) {
      return false;
    }
    // Can always activate previous steps
    if (stepIndex < this.index) {
      return true;
    }
    // We are already in the step. Nothing to activate.
    if (stepIndex === this.index) {
      return false;
    }
    // Fast-forward: check all steps if they are valid
    for (let i = this.index; i < stepIndex; i++) {
      const theStep = this.steps()[i];
      Iif (!theStep.isValid()) {
        return false;
      }
    }
    return true;
  }
 
  protected activateStep(event: Event, stepIndex: number): void {
    event.preventDefault();
    if (this.canActivate(stepIndex)) {
      if (stepIndex > this.index) {
        this.next(stepIndex - this.index);
      }
      Iif (stepIndex < this.index) {
        this.back(this.index - stepIndex);
      }
    }
  }
 
  protected getStateClass(stepIndex: number): string {
    if (stepIndex === this.index) {
      return 'active';
    }
    Iif (!this.canActivate(stepIndex)) {
      return 'disabled';
    }
    if (stepIndex < this.index) {
      return 'completed';
    }
    return '';
  }
 
  protected getAriaDisabled(stepIndex: number): string {
    if (!this.canActivate(stepIndex)) {
      return 'true';
    }
    return 'false';
  }
 
  protected getAriaCurrent(stepIndex: number): string {
    if (stepIndex === this.index) {
      return 'step';
    }
    return 'false';
  }
 
  /**
   * Go to the next wizard step.
   * @param delta - optional number of steps to move forward.
   */
  next(delta: number = 1): void {
    const steps = this.steps();
    Iif (this.index === steps.length - 1) {
      return;
    }
    const stepIndex = this.index + delta;
    const nextStep = steps[stepIndex];
    if (this.canActivate(stepIndex)) {
      this.currentStep?.next.emit();
      if (this.currentStep?.isNextNavigable()) {
        this.activate(nextStep);
      }
    }
  }
 
  /**
   * Go to the previous wizard step.
   * @param delta - optional number of steps to move backwards.
   */
  back(delta: number = 1): void {
    Iif (this.index === 0) {
      return;
    }
    this.currentStep?.back.emit();
    this.activate(this.steps()[this.index - delta]);
  }
 
  /** Triggers the save action to complete the wizard. */
  save(): void {
    this.currentStep?.save.emit();
 
    Iif (this.enableCompletionPage() && this.completionPageVisibleTime() > 0) {
      this.showCompletionPage.set(true);
      setTimeout(() => {
        this.showCompletionPage.set(false);
        this.completionAction.emit();
      }, this.completionPageVisibleTime());
    } else {
      this.completionAction.emit();
    }
  }
 
  protected getState(step: SiWizardStepComponent, stepIndex: number): string {
    Iif (step.failed() === true) {
      return this.stepFailedIcon();
    }
    const txtStyle = step.isActive() ? this.stepActiveIcon() : this.stepIcon();
    return stepIndex >= this.index ? txtStyle : this.stepCompletedIcon();
  }
 
  private activate(step: SiWizardStepComponent): void {
    if (this.currentStep) {
      this.currentStep.isActive.set(false);
    }
 
    step.isActive.set(true);
    this._currentStep.set(step);
    this._index.set(this.steps().indexOf(step));
  }
 
  protected updateVisibleSteps(): void {
    const newVisibleSteps = this.calculateVisibleStepCount();
    Iif (newVisibleSteps !== this.visibleSteps()) {
      this.visibleSteps.set(newVisibleSteps);
    }
  }
 
  private calculateVisibleStepCount(): number {
    const containerSteps = this.containerSteps();
    Iif (!containerSteps) {
      return 0;
    }
    if (this.verticalLayout()) {
      const computedStyle = getComputedStyle(containerSteps.nativeElement);
      const clientHeight =
        containerSteps.nativeElement.clientHeight -
        parseInt(computedStyle.paddingBlockStart) -
        parseInt(computedStyle.paddingBlockEnd);
      return Math.max(Math.floor(clientHeight / 48), 1);
    } else {
      const clientWidth = containerSteps.nativeElement.clientWidth;
      return Math.max(Math.floor(clientWidth / 150), 1);
    }
  }
 
  private computeVisibleSteps(): StepItem[] {
    const create = (index: number): StepItem => ({ index, step: this.steps()[index] });
    if (this.steps().length === 0) {
      return [];
    } else if (this.visibleSteps() <= 1) {
      return [create(this.index)];
    } else if (this.stepCount <= this.visibleSteps()) {
      return this.steps().map((_, i) => create(i));
    } else {
      const steps = [this.index];
      for (
        let i = 1, left = this.index - 1, right = this.index + 1;
        i < this.visibleSteps();
        right++, left--
      ) {
        // Iterate in both directions to check current step is in visible range.
        if (right < this.stepCount) {
          steps.push(right);
          i++;
        }
        if (left >= 0 && i < this.visibleSteps()) {
          steps.push(left);
          i++;
        }
      }
 
      return steps.sort((l, r) => l - r).map(i => create(i));
    }
  }
}