@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
252 lines (251 loc) • 10.1 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.correctNumberValue = exports.correctCaretPosition = void 0;
exports.fromJSON = fromJSON;
exports.getSoftKeyboardAttributes = getSoftKeyboardAttributes;
exports.handleCurrencyMask = void 0;
exports.handleDecimalSeparator = handleDecimalSeparator;
exports.handlePercentMask = exports.handleNumberMask = void 0;
exports.handleThousandsSeparator = handleThousandsSeparator;
exports.isRequestingNumberMask = exports.isRequestingLocaleSupport = exports.invisibleSpace = void 0;
var _parse = _interopRequireDefault(require("core-js-pure/stable/json/parse.js"));
var _NumberUtils = require("../number-format/NumberUtils.js");
var _componentHelper = require("../../shared/component-helper.js");
var _helpers = require("../../shared/helpers.js");
var _createTextMaskInputElement = require("./text-mask/createTextMaskInputElement.js");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const enableLocaleSupportWhen = ['as_number', 'as_percent', 'as_currency'];
const enableNumberMaskWhen = ['as_number', 'as_percent', 'as_currency', 'number_mask', 'currency_mask'];
const invisibleSpace = exports.invisibleSpace = '\u200B';
const NUMBER_MINUS = '-|−|‐|‒|–|—|―';
const isRequestingLocaleSupport = props => {
return Object.entries(props).some(([k, v]) => v && enableLocaleSupportWhen.includes(k));
};
exports.isRequestingLocaleSupport = isRequestingLocaleSupport;
const isRequestingNumberMask = props => {
return Object.entries(props).some(([k, v]) => v && enableNumberMaskWhen.includes(k));
};
exports.isRequestingNumberMask = isRequestingNumberMask;
const correctNumberValue = ({
localValue = null,
props,
locale,
maskParams
}) => {
let value = props.value === null ? null : props.value === undefined ? undefined : String(props.value);
if (isNaN(parseFloat(value))) {
return value;
}
const decimalPos = value.indexOf('.');
if (maskParams.integerLimit && typeof maskParams.integerLimit === 'number') {
const limit = maskParams.integerLimit;
const integers = value.split('.')[0];
const isNegative = parseFloat(integers) < 0;
if (integers.length - (isNegative ? 1 : 0) > limit) {
const decimals = decimalPos > 0 ? value.slice(decimalPos) : '';
value = integers.slice(0, limit + (isNegative ? 1 : 0)) + decimals;
}
}
const shouldHaveDecimals = maskParams.allowDecimal || maskParams.decimalLimit > 0 && maskParams.allowDecimal !== false;
if (!shouldHaveDecimals) {
if (decimalPos > -1) {
value = value.slice(0, decimalPos);
}
}
if (props.number_format) {
const options = {
locale,
decimals: 0,
...props.number_format
};
if (shouldHaveDecimals) {
options.decimals = maskParams.decimalLimit;
}
value = String((0, _NumberUtils.format)(value, options));
}
const decimalSymbol = maskParams.decimalSymbol;
value = value.replace('.', decimalSymbol);
if (localValue !== null) {
const invalidCharactersRegex = new RegExp(`[^${NUMBER_MINUS}\\d${decimalSymbol}]`, 'g');
const localNumberValue = localValue.replace(invalidCharactersRegex, '');
const numberValue = value.replace(invalidCharactersRegex, '');
const valueHasDecimal = numberValue.includes(decimalSymbol);
if (!valueHasDecimal) {
const endsWithDecimal = localNumberValue.endsWith(decimalSymbol);
const endsWithZeroAndDecimal = localNumberValue.endsWith(`${decimalSymbol}0`);
if (endsWithDecimal) {
value = `${value}${decimalSymbol}`;
} else if (endsWithZeroAndDecimal && !numberValue.endsWith(`${decimalSymbol}0`)) {
value = `${value}${decimalSymbol}0`;
}
}
if (localNumberValue !== '0' && new RegExp(`^(0|(${NUMBER_MINUS})0)`).test(localNumberValue) && parseFloat(numberValue.replace(decimalSymbol, '.')) === parseFloat(localNumberValue.replace(decimalSymbol, '.'))) {
value = localValue;
}
if (new RegExp(`^((${NUMBER_MINUS})|(${NUMBER_MINUS})0)$`).test(localValue.replace(new RegExp(`[^\\d(${NUMBER_MINUS})0]`, 'g'), ''))) {
value = localValue;
} else if (localNumberValue === '' && numberValue === '0') {
value = '';
}
}
return value;
};
exports.correctNumberValue = correctNumberValue;
const correctCaretPosition = (element, maskParamsRef, props) => {
const correction = () => {
try {
const maskParams = maskParamsRef === null || maskParamsRef === void 0 ? void 0 : maskParamsRef.current;
const suffix = maskParams === null || maskParams === void 0 ? void 0 : maskParams.suffix;
const prefix = maskParams === null || maskParams === void 0 ? void 0 : maskParams.prefix;
const start = element.selectionStart;
const end = element.selectionEnd;
if (start !== end) {
return;
}
if (suffix || prefix) {
const suffixStart = element.value.indexOf(suffix);
const suffixEnd = suffixStart + (suffix === null || suffix === void 0 ? void 0 : suffix.length);
let pos = undefined;
if (start >= suffixStart && start <= suffixEnd) {
pos = suffixStart;
if (maskParams.placeholderChar !== invisibleSpace && element.value.length - 1 === String(suffix + prefix).length) {
pos = pos - 1;
}
} else {
const prefixStart = element.value.indexOf(prefix);
const prefixEnd = prefixStart + (prefix === null || prefix === void 0 ? void 0 : prefix.length) || 0;
if (start >= prefixStart && start <= prefixEnd) {
pos = prefixEnd;
}
}
const char = element.value.slice(pos - 1, pos);
if (char === invisibleSpace) {
pos = suffixStart - 1;
}
if (!isNaN(parseFloat(String(pos)))) {
(0, _createTextMaskInputElement.safeSetSelection)(element, pos);
}
} else if (props !== null && props !== void 0 && props.mask && element.value.length === end) {
const chars = element.value.split('');
for (let l = chars.length, i = l - 1; i >= 0; i--) {
const char = chars[i];
const mask = props.mask[i];
if (char && char !== invisibleSpace && mask instanceof RegExp && mask.test(char)) {
for (let n = i + 1; n < l; n++) {
var _mask$test;
const mask = props.mask[n];
if (mask !== null && mask !== void 0 && (_mask$test = mask.test) !== null && _mask$test !== void 0 && _mask$test.call(mask, char)) {
(0, _createTextMaskInputElement.safeSetSelection)(element, n);
break;
}
}
break;
}
}
}
} catch (e) {
(0, _componentHelper.warn)(e);
}
};
if (typeof window !== 'undefined') {
window.requestAnimationFrame(correction);
}
};
exports.correctCaretPosition = correctCaretPosition;
const handlePercentMask = ({
props,
locale,
maskParams
}) => {
const value = (0, _NumberUtils.format)(props.value, {
locale,
percent: true
});
const m = String(value).match(/((\s|)%)$/g);
maskParams.suffix = (m === null || m === void 0 ? void 0 : m[0]) || ' %';
return maskParams;
};
exports.handlePercentMask = handlePercentMask;
const handleCurrencyMask = ({
mask_options,
currency_mask
}) => {
const givenParams = typeof currency_mask === 'string' ? {
...mask_options,
...{
0: String(currency_mask)
}
} : {
...mask_options,
...currency_mask
};
const paramsWithDefaults = {
showMask: true,
placeholderChar: null,
allowDecimal: true,
decimalLimit: 2,
decimalSymbol: ',',
...givenParams
};
const currencyLabel = typeof currency_mask === 'string' ? currency_mask : typeof givenParams.currency === 'string' ? givenParams.currency : 'kr';
const hasCurrencyLabel = typeof currencyLabel === 'string' && currencyLabel;
const shouldShowCurrencyLabel = hasCurrencyLabel && givenParams.currencyDisplay !== false;
const shouldShowCurrencyBeforeAmount = givenParams.currencyDisplay === 'code' && shouldShowCurrencyLabel;
if (shouldShowCurrencyBeforeAmount) {
paramsWithDefaults.prefix = `${currencyLabel} `;
paramsWithDefaults.suffix = '';
} else if (shouldShowCurrencyLabel) {
paramsWithDefaults.suffix = ` ${currencyLabel}`;
} else {
paramsWithDefaults.prefix = '';
paramsWithDefaults.suffix = '';
}
if (typeof (givenParams === null || givenParams === void 0 ? void 0 : givenParams.allowDecimal) === 'undefined' && typeof (givenParams === null || givenParams === void 0 ? void 0 : givenParams.decimalLimit) === 'number') {
paramsWithDefaults.allowDecimal = givenParams.decimalLimit > 0;
}
return paramsWithDefaults;
};
exports.handleCurrencyMask = handleCurrencyMask;
const handleNumberMask = ({
mask_options,
number_mask
}) => {
const maskParams = {
decimalSymbol: ',',
...mask_options,
...number_mask
};
if (typeof maskParams.allowDecimal === 'undefined') {
maskParams.allowDecimal = maskParams.decimalLimit > 0;
}
return maskParams;
};
exports.handleNumberMask = handleNumberMask;
function getSoftKeyboardAttributes(mask) {
if ((mask === null || mask === void 0 ? void 0 : mask.instanceOf) !== 'createNumberMask') {
return undefined;
}
const maskParams = mask === null || mask === void 0 ? void 0 : mask.maskParams;
if (_helpers.IS_IOS && (maskParams === null || maskParams === void 0 ? void 0 : maskParams.allowNegative) !== false) {
return undefined;
}
return {
inputMode: maskParams.allowDecimal && maskParams.decimalLimit !== 0 ? 'decimal' : 'numeric'
};
}
function handleThousandsSeparator(locale) {
return (0, _NumberUtils.getThousandsSeparator)(locale).replace(' ', ' ');
}
function handleDecimalSeparator(locale) {
const decimalSymbol = (0, _NumberUtils.getDecimalSeparator)(locale);
return decimalSymbol;
}
function fromJSON(str, fallback = null) {
if (typeof str === 'string' && str[0] === '{') {
return (0, _parse.default)(str);
}
return str || fallback;
}
//# sourceMappingURL=InputMaskedUtils.js.map