UNPKG

chayns-components

Version:

A set of beautiful React components for developing chayns® applications.

95 lines (93 loc) 2.95 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); exports.__esModule = true; exports.default = void 0; var _DecimalFormatter = _interopRequireDefault(require("./DecimalFormatter")); var _endsWith = _interopRequireDefault(require("../../utils/endsWith")); var _startsWith = _interopRequireDefault(require("../../utils/startsWith")); class PriceFormatter extends _DecimalFormatter.default { constructor(currencySign, _temp) { if (currencySign === void 0) { currencySign = ''; } let { decimalSeparator = ',', thousandSeparator = '.', currencyBefore = null } = _temp === void 0 ? {} : _temp; super({ decimalSeparator, thousandSeparator, decimals: 2 }); this.currency = { sign: '' }; this.currency.sign = currencySign; this.currency.before = currencyBefore === null ? currencySign !== '€' : !!currencyBefore; } format(value) { if (value === null || value === '') { return ''; } if (!this.currency.sign) { return super.format(value); } if (this.currency.before) { return `${this.currency.sign} ${super.format(value)}`; } return `${super.format(value)} ${this.currency.sign}`; } removeCurrencySign(value, selection) { if (selection === void 0) { selection = null; } let newValue = value; const newSelection = { ...selection }; if (this.currency.sign) { if (this.currency.before) { if ((0, _startsWith.default)(newValue, this.currency.sign)) { newValue = newValue.slice(1); newSelection.start = Math.max(0, newSelection.start - 1); newSelection.end = Math.max(0, newSelection.end - 1); } if ((0, _startsWith.default)(newValue, ' ')) { newValue = newValue.slice(1); newSelection.start = Math.max(0, newSelection.start - 1); newSelection.end = Math.max(0, newSelection.end - 1); } } else { if ((0, _endsWith.default)(newValue, this.currency.sign)) { newValue = newValue.slice(0, -this.currency.sign.length); } if ((0, _endsWith.default)(newValue, ' ')) { newValue = newValue.slice(0, -1); } newSelection.start = Math.min(newSelection.start, newValue.length); newSelection.end = Math.min(newSelection.end, newValue.length); } } return { value: newValue, selection: newSelection }; } parse(value) { if (value === '') { return null; } const newValue = this.removeCurrencySign(value); return super.parse(newValue.value); } validate(value, selection) { const { value: newValue, selection: newSelection } = this.removeCurrencySign(value, selection); return super.validate(newValue, newSelection); } } exports.default = PriceFormatter; //# sourceMappingURL=PriceFormatter.js.map