All files / formly si-formly-translate.extension.ts

100% Statements 24/24
92.85% Branches 13/14
100% Functions 2/2
100% Lines 24/24

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                41x   57x 57x 2x     55x   55x 55x 29x     55x   1x 1x 4x 4x 4x         55x 1x     55x 5x     55x 1x 1x 1x     1x               55x      
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { FormlyFieldConfig } from '@ngx-formly/core';
import { injectSiTranslateService } from '@siemens/element-translate-ng/translate';
 
export class SiFormlyTranslateExtension {
  private translate = injectSiTranslateService();
  prePopulate(field: FormlyFieldConfig): void {
    const to = field.props ?? {};
    if (to.translate === false || to._translated) {
      return;
    }
 
    field.expressions ??= {};
 
    to._translated = true;
    if (to.label) {
      field.expressions['props.label'] = this.translate.translateAsync(to.label);
    }
 
    if (to.options) {
      // e.g. a select
      let i = -1;
      to.options.forEach((val: any) => {
        i++;
        if (field.expressions) {
          field.expressions[`props.options.${i}.label`] = this.translate.translateAsync(val.label);
        }
      });
    }
 
    if (to.placeholder) {
      field.expressions['props.placeholder'] = this.translate.translateAsync(to.placeholder);
    }
 
    if (to.description) {
      field.expressions['props.description'] = this.translate.translateAsync(to.description);
    }
 
    if (field.validation?.messages) {
      const msgs = field.validation.messages;
      for (const msg in msgs) {
        if (typeof msgs[msg] === 'string') {
          // This unfortunately blocks any opportunity to create context specific messages
          // Specific messages could be done via the "map" function when the schema itself is parsed
          field.expressions[`validation.messages.${msg}`] = this.translate.translateAsync(
            msgs[msg] + ''
          );
        }
      }
    }
 
    // Trigger a change
    field.expressions = { ...(field.expressions ?? {}) };
  }
}