UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

71 lines (70 loc) 2.44 kB
"use client"; import { useContext } from 'react'; import Context from "../../shared/Context.js"; import { extendPropsWithContext } from "../../shared/component-helper.js"; import { formatNumber } from "./utils/index.js"; function useNumberFormatWithParts(value, formatter = formatNumber, options = {}) { const context = useContext(Context); const params = 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 }; } export default useNumberFormatWithParts; //# sourceMappingURL=useNumberFormatWithParts.js.map