make currency input more resilient

This commit is contained in:
Ruben Fiszel
2023-12-10 21:21:50 +01:00
parent cc805a06b5
commit f43e31b967
2 changed files with 20 additions and 14 deletions
@@ -102,7 +102,7 @@
'wm-currency-input'
),
wrapper: 'w-full windmillapp',
formattedZero: twMerge('text-black windmillapp ', css?.input?.class, 'wm-currency')
formattedZero: twMerge('windmillapp ', css?.input?.class, 'wm-currency')
}}
style={css?.input?.style}
bind:value
@@ -43,12 +43,17 @@
maximumFractionDigits?: number,
minimumFractionDigits?: number
) => {
return new Intl.NumberFormat(locale, {
currency: currency,
style: 'currency',
maximumFractionDigits: maximumFractionDigits || 0,
minimumFractionDigits: minimumFractionDigits || 0
}).format(value)
try {
return new Intl.NumberFormat(locale, {
currency: currency,
style: 'currency',
maximumFractionDigits: maximumFractionDigits || 0,
minimumFractionDigits: minimumFractionDigits || 0
}).format(value)
} catch (e) {
console.error(e)
return 'ERR'
}
}
// Checks if the key pressed is allowed
@@ -64,14 +69,15 @@
}
let inputTarget: HTMLInputElement
const currencyDecimal = new Intl.NumberFormat(locale).format(1.1).charAt(1) // '.' or ','
const isDecimalComma = currencyDecimal === ','
const currencySymbol = formatCurrency(0, 0)
.replace('0', '') // e.g. '$0' > '$'
.replace(/\u00A0/, '') // e.g '0 €' > '€'
// Updates `value` by stripping away the currency formatting
const setUnformattedValue = (event?: KeyboardEvent) => {
const currencyDecimal = new Intl.NumberFormat(locale).format(1.1).charAt(1) // '.' or ','
const isDecimalComma = currencyDecimal === ','
const currencySymbol = formatCurrency(0, 0)
.replace('0', '') // e.g. '$0' > '$'
.replace(/\u00A0/, '') // e.g '0 €' > '€'
if (event) {
// Don't format if the user is typing a `currencyDecimal` point
if (event.key === currencyDecimal) return
@@ -189,7 +195,7 @@
/>
</div>
<style lang="postcss">
<style>
input.currencyInput__formatted {
border: 1px solid #e2e2e2;
padding: 10px;
@@ -197,7 +203,7 @@
}
input.currencyInput__formatted--zero {
color: #333;
@apply text-primary;
}
input.currencyInput__formatted--positive {