Files
oficial/app/resources/views/layout/body/scripts/number_input.blade.php
2025-05-05 15:45:07 -04:00

77 lines
3.1 KiB
PHP

@push('page_scripts')
<script>
if (typeof Intl.NumberFormat.isLocale === 'undefined' || typeof Intl.NumberFormat.isLocale !== 'function') {
// Load Intl.NumberFormat custom methods
@include('layout.body.scripts.number_format')
}
class NumberInput {
input
isRational
outputLocale
currentValue
formatters
constructor({input, isRational, outputLocale}) {
this.input = input
this.isRational = isRational
this.outputLocale = outputLocale || 'es-CL'
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)
this.input.value = this.format(this.currentValue)
}
}
watch() {
this.input.addEventListener('change', event => {
this.currentValue = this.process(event.currentTarget.value)
this.input.value = this.format(this.currentValue)
})
}
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