All files / lib/text-input-field text-input-field.formatters.ts

97.18% Statements 138/142
87.5% Branches 28/32
100% Functions 8/8
97.18% Lines 138/142

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 1431x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 53x 53x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 90x 90x 90x 90x 90x 90x 90x 90x 1x 1x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 18x 18x 12x 12x 12x 12x 22x 4x 12x 12x 22x 22x 22x 22x 22x 22x 1x 1x 129x 129x 118x 118x 118x 22x         129x 129x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 2x 2x 2x 8x 8x 8x 8x 13x 13x 8x 8x 13x 30x 13x 13x 8x  
/*******************************************************************************
 * Copyright bei
 * Entwicklungs- und Pflegeverbund für das gemeinsame Fachverfahren gefa
 *
 *******************************************************************************/
import { Converter } from '../utils/util.types';
 
/**
 * Representation of a parsing error.
 */
export interface ParseError {
  /**
   * Error message describing the error, must be presentable to the user.
   */
  message: string;
}
 
export function isParseError(value: string | ParseError): value is ParseError {
  return typeof value === 'object';
}
 
/**
 * A formatter which is capable of converting between internal values and the user facing representation.
 */
export interface TextInputFormatter {
  /**
   * Parse user input and convert it to the internal representation of the value.
   * @param input the user input to convert
   * @returns the parsed value, i.e. the internal representation to use, or a ParseError if
   *          the input cannot be converted (e.g. if it's in an invalid format).
   */
  parse: Converter<string, string | ParseError>;
 
  /**
   * Format a value for presentation to the user.
   * @param value the internal representation of the value.
   * @returns the formatted value
   */
  format: Converter<string, string>;
}
 
/**
 * Formatter for the text input which displays numeric values with a fixed number of decimals.
 *
 * Internal format is the representation of a `number` as string (i.e. result of `Number.toString()`), user
 * representation is a number formatted according to a German locale.
 */
export class TextInputNumberFormatter implements TextInputFormatter {
  private readonly numberFormat: Intl.NumberFormat;
  private readonly parseFractionRegex: RegExp;
  private readonly parseIntegerRegex: RegExp = /^-?\d+(\.\d{3})*$/;
 
  /**
   * Create a new number formatter.
   * @param decimals the number of decimals to show
   */
  constructor(private readonly decimals = 0) {
    this.numberFormat = new Intl.NumberFormat('de-DE', {
      style: 'decimal',
      useGrouping: true,
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    });
    this.parseFractionRegex = new RegExp(`^\\d{0,${decimals.toFixed(0)}}$`);
  }
 
  public parse(input: string): string | ParseError {
    if (!input) {
      return input;
    }
 
    const [integerPart, fractionPart] = input.split(',', 2) as [
      string,
      string | undefined,
    ];
    if (!this.parseIntegerRegex.test(integerPart)) {
      return { message: 'Eingabe ist keine gültige Zahl' };
    }
    const integer = integerPart
      .replaceAll('.', '') // replace thousands-separators
      .replace(/^0+/g, ''); // strip leading zeros
 
    if (!this.parseFractionRegex.test(fractionPart ?? '')) {
      return {
        message: `Maximal ${this.decimals.toFixed(0)} Nachkommastellen erlaubt.`,
      };
    }
    const fraction = fractionPart?.replace(/(?=(0+))\1$/g, ''); // strip trailing zeros
 
    return (
      (integer.length > 0 ? integer : '0') + (fraction ? '.' + fraction : '')
    );
  }
 
  public format(value: string): string {
    if (!value) {
      return value;
    }
 
    const numeric = parseFloat(value);
    if (!isNaN(numeric)) {
      return this.numberFormat.format(numeric);
    } else {
      console.error(`provided value '${value}' is not a number`);
      return '';
    }
  }
}
 
/**
 * Formatter for the text input which displays an IBAN in a friendly format.
 */
export class TextInputIBANFormatter implements TextInputFormatter {
  private readonly parseRegexp: RegExp = /^[A-Z]{2}\d{2}[A-Za-z0-9]{1,30}$/;
 
  public parse(input: string): string | ParseError {
    if (!input) {
      return '';
    }
 
    const withoutWhitespace = input.replace(/\s/g, '');
    // allow input with country code in lower case -> automatically convert to upper case
    const normalized =
      withoutWhitespace.substring(0, 2).toUpperCase() +
      withoutWhitespace.substring(2);
    if (!this.parseRegexp.test(normalized)) {
      return { message: 'Keine gültige IBAN' };
    } else {
      return normalized;
    }
  }
 
  public format(value: string): string {
    return [...this.stringChunks(value, 4)].join(' ');
  }
 
  private *stringChunks(value: string, size: number) {
    for (let start = 0; start < value.length; start += size) {
      yield value.slice(start, start + size);
    }
  }
}