Grupo-AFAL/frontend-helpers

View on GitHub
javascript/src/controllers/step-number-input-controller.js

Summary

Maintainability
B
5 hrs
Test Coverage
import { Controller } from '@hotwired/stimulus'
 
export class StepNumberInputController extends Controller {
static targets = ['input', 'add', 'subtract']
 
connect () {
this.value = parseInt(this.inputTarget.value) || 0
this.minValue = parseInt(this.inputTarget.min) || 0
this.maxValue = parseInt(this.inputTarget.max) || 10
this.setValue()
 
this.inputTarget.addEventListener('change', e => {
const newValue = parseInt(e.target.value) || 0
 
if (newValue === this.value) return
 
this.value = newValue
this.setValue()
})
}
 
Similar blocks of code found in 2 locations. Consider refactoring.
add (e) {
e.preventDefault()
this.value += 1
this.setValue()
this.triggerChangeEvent()
}
 
Similar blocks of code found in 2 locations. Consider refactoring.
subtract (e) {
e.preventDefault()
this.value -= 1
this.setValue()
this.triggerChangeEvent()
}
 
Function `setValue` has a Cognitive Complexity of 8 (exceeds 5 allowed). Consider refactoring.
setValue () {
this.value = Math.max(Math.min(this.value, this.maxValue), this.minValue)
this.inputTarget.value = this.value
 
Similar blocks of code found in 2 locations. Consider refactoring.
if (this.hasAddTarget) {
if (this.value === this.maxValue) {
this.addTarget.classList.add('is-static')
} else {
this.addTarget.classList.remove('is-static')
}
}
 
Similar blocks of code found in 2 locations. Consider refactoring.
if (this.hasSubtractTarget) {
if (this.value === this.minValue) {
this.subtractTarget.classList.add('is-static')
} else {
this.subtractTarget.classList.remove('is-static')
}
}
}
 
triggerChangeEvent () {
const event = document.createEvent('HTMLEvents')
event.initEvent('change', false, true)
this.inputTarget.dispatchEvent(event)
}
}