Files
oficial/app/resources/views/layout/body/scripts/number_input.blade.php
2025-04-30 23:36:32 -04:00

72 lines
2.8 KiB
PHP

@push('page_scripts')
<script>
class NumberInput {
input
isRational
outputLocale
currentValue
formatters
constructor({input, isRational, outputLocale}) {
this.input = input
this.isRational = isRational
this.outputLocale = outputLocale
this.formatters = {}
const locales = ['es-CL', 'en-US']
locales.forEach(locale => {
this.formatters[locale] = {
rational: new Intl.NumberFormat(locale, {minimumFractionDigits: 2, maximumFractionDigits: 2}),
integer: new Intl.NumberFormat(locale)
}
})
if (this.input.value !== '') {
this.currentValue = this.process(this.input.value)
}
}
watch() {
this.input.addEventListener('change', event => {
const value = this.process(event.target.value)
this.currentValue = value
this.input.value = this.format(value)
})
}
process(stringValue) {
if (stringValue === '') {
return ''
}
if (typeof stringValue !== 'string') {
return stringValue
}
return this.formatters[this.detectLocale(stringValue)][this.isRational ? 'rational' : 'integer'].parse(stringValue)
}
detectLocale(stringValue) {
if (stringValue === '') {
return ''
}
if (typeof stringValue !== 'string') {
return stringValue
}
const outputFormat = this.formatters[this.outputLocale][this.isRational ? 'rational' : 'integer'].isLocale(stringValue)
const otherFormats = Object.entries(this.formatters).filter(formatter => formatter[0] !== this.outputLocale).map(formatter => {
return {
locale: formatter[0],
value: formatter[1][this.isRational ? 'rational' : 'integer'].isLocale(stringValue)
}
}).filter(formatter => formatter.value)
if (outputFormat) {
return this.outputLocale
}
if (otherFormats.length > 0) {
return otherFormats[0].locale
}
return 'en-US'
}
format(value) {
return this.formatters[this.outputLocale][this.isRational ? 'rational' : 'integer'].format(value)
}
}
</script>
@endpush