UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

231 lines 9.01 kB
import _JSON$parse from "core-js-pure/stable/json/parse.js"; import { format, getDecimalSeparator, getThousandsSeparator } from "../number-format/NumberUtils.js"; import { warn } from "../../shared/component-helper.js"; import { IS_IOS } from "../../shared/helpers.js"; import { safeSetSelection } from "./text-mask/createTextMaskInputElement.js"; const enableLocaleSupportWhen = ['as_number', 'as_percent', 'as_currency']; const enableNumberMaskWhen = ['as_number', 'as_percent', 'as_currency', 'number_mask', 'currency_mask']; export const invisibleSpace = '\u200B'; const NUMBER_MINUS = '-|−|‐|‒|–|—|―'; export const isRequestingLocaleSupport = props => { return Object.entries(props).some(([k, v]) => v && enableLocaleSupportWhen.includes(k)); }; export const isRequestingNumberMask = props => { return Object.entries(props).some(([k, v]) => v && enableNumberMaskWhen.includes(k)); }; export 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(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; }; export 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)))) { 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)) { safeSetSelection(element, n); break; } } break; } } } } catch (e) { warn(e); } }; if (typeof window !== 'undefined') { window.requestAnimationFrame(correction); } }; export const handlePercentMask = ({ props, locale, maskParams }) => { const value = 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; }; export 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; }; export 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; }; export 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 (IS_IOS && (maskParams === null || maskParams === void 0 ? void 0 : maskParams.allowNegative) !== false) { return undefined; } return { inputMode: maskParams.allowDecimal && maskParams.decimalLimit !== 0 ? 'decimal' : 'numeric' }; } export function handleThousandsSeparator(locale) { return getThousandsSeparator(locale).replace(' ', ' '); } export function handleDecimalSeparator(locale) { const decimalSymbol = getDecimalSeparator(locale); return decimalSymbol; } export function fromJSON(str, fallback = null) { if (typeof str === 'string' && str[0] === '{') { return _JSON$parse(str); } return str || fallback; } //# sourceMappingURL=InputMaskedUtils.js.map