feature/cierres (#25)
Varios cambios Co-authored-by: Juan Pablo Vial <jpvialb@incoviba.cl> Reviewed-on: #25
This commit is contained in:
@ -0,0 +1,76 @@
|
||||
@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
|
Reference in New Issue
Block a user