UNPKG

headless-currency-input

Version:

Headless Currency Input is a component to format currency input in an elegant way.

2 lines 1.99 kB
import {mergeRefs}from'@react-aria/utils';import {resolveCurrencyFormat}from'@sumup/intl';import {forwardRef,useRef}from'react';import {NumberFormatBase}from'react-number-format';import {jsx}from'react/jsx-runtime';function y(o,f=0){return o.value=o.value,o!==null?o.selectionStart||o.selectionStart===0?(o.focus(),o.setSelectionRange(f,f),!0):(o.focus(),!1):!1}function S({locale:o="en",currency:f="USD",withCurrencySymbol:g=!0,...t},I){let i=useRef(null),n=resolveCurrencyFormat(o,f),l=(n==null?void 0:n.currencyPosition)==="prefix"?`${n.currencySymbol} `:"",r=(n==null?void 0:n.minimumFractionDigits)??0,d=(n==null?void 0:n.maximumFractionDigits)??0,s=10**r;function b(e){var m,c;let u=0;Number(e)?u=Number(e):(u=0,typeof document<"u"&&document.activeElement===i.current&&((m=i.current)==null||m.setSelectionRange(e.length+(r??0),e.length+(r??0)),e.length&&e.length<=3&&((c=i.current)==null||c.setSelectionRange(e.length+(r??0),e.length+(r??0)))));let a=new Intl.NumberFormat(n==null?void 0:n.locale,{style:"currency",currency:n==null?void 0:n.currency,currencyDisplay:"code",minimumFractionDigits:r,maximumFractionDigits:d}).format(r?u/s:u).replace(/[a-z]{3}/i,"").trim();return g?`${l}${a}`:`${a}`}function T(e,u){var c;let a=r?(Number.parseFloat(e.value)/s).toFixed(r):e.value,m=e.floatValue&&r?e.floatValue/s:e.floatValue;(c=t==null?void 0:t.onValueChange)==null||c.call(t,{value:a,floatValue:m,formattedValue:e.formattedValue},u);}function R(e){var u;if(i.current){let a=i.current.value.length-l.length;y(i.current,a+(r??0));}(u=t==null?void 0:t.onFocus)==null||u.call(t,e);}function h(e){var u;if(i.current){let a=i.current.value.length-l.length;y(i.current,a+(r??0));}(u=t==null?void 0:t.onInput)==null||u.call(t,e);}return jsx(NumberFormatBase,{...t,format:b,onFocus:R,onInput:h,onValueChange:T,getInputRef:mergeRefs(i,I),prefix:void 0,valueIsNumericString:!1})}var H=forwardRef(S);export{H as CurrencyInput};//# sourceMappingURL=index.mjs.map //# sourceMappingURL=index.mjs.map