@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
77 lines (76 loc) • 2.71 kB
JavaScript
;
"use client";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _react = require("react");
var _Context = _interopRequireDefault(require("../../shared/Context.js"));
var _componentHelper = require("../../shared/component-helper.js");
var _index = require("./utils/index.js");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function useNumberFormatWithParts(value, formatter = _index.formatNumber, options = {}) {
const context = (0, _react.useContext)(_Context.default);
const params = (0, _componentHelper.extendPropsWithContext)({
returnAria: true,
...options
}, {
locale: context.locale
}, context.NumberFormat);
const result = formatter(value, params);
if (typeof result === 'string') {
return result;
}
return {
...result,
parts: parseParts(result.number)
};
}
const SIGN_RE = /^[\u200e\u200f\u061c\s]*([+\-\u2212])?\s*/;
const NUMBER_RE = /[0-9](?:[0-9.,]|[\s\u00A0\u202F](?=[0-9]))*/;
const PERCENT_RE = /^([\u00A0\u202F\s]*)([%٪])\s*$/;
function parseParts(input) {
var _signMatch$;
const source = String(input !== null && input !== void 0 ? input : '');
const signMatch = source.match(SIGN_RE);
const sign = (_signMatch$ = signMatch[1]) !== null && _signMatch$ !== void 0 ? _signMatch$ : null;
const afterSign = source.slice(signMatch[0].length);
const numberMatch = afterSign.match(NUMBER_RE);
if (!numberMatch) {
return {
sign,
signedNumber: source.trim(),
number: afterSign.trim(),
currency: null,
currencyPosition: null,
spaceAfterCurrency: false,
spaceBeforeCurrency: false,
percent: null,
percentSpacing: ''
};
}
const number = numberMatch[0].trim();
const signedNumber = sign ? `${sign}${number}` : number;
const before = afterSign.slice(0, numberMatch.index).trim();
const after = afterSign.slice(numberMatch.index + numberMatch[0].length);
const percentMatch = after.match(PERCENT_RE);
const percent = percentMatch ? percentMatch[2] : null;
const percentSpacing = percentMatch ? percentMatch[1] : '';
const trailing = percentMatch ? '' : after.trim();
const hasBefore = before.length > 0;
const hasAfter = trailing.length > 0;
const currency = hasBefore ? before : hasAfter ? trailing : null;
return {
sign,
signedNumber,
number,
currency,
currencyPosition: hasBefore ? 'before' : hasAfter ? 'after' : null,
spaceAfterCurrency: hasBefore,
spaceBeforeCurrency: hasAfter,
percent,
percentSpacing
};
}
var _default = exports.default = useNumberFormatWithParts;
//# sourceMappingURL=useNumberFormatWithParts.js.map