generated from boboko/starter
40 lines
980 B
JavaScript
40 lines
980 B
JavaScript
import { Controller } from '@hotwired/stimulus'
|
|
|
|
export default class extends Controller {
|
|
static targets = ['input', 'decrement']
|
|
static values = { min: { type: Number, default: 1 } }
|
|
|
|
connect() {
|
|
this.#updateDecrement()
|
|
}
|
|
|
|
increment() {
|
|
this.#setValue(this.#current + 1)
|
|
}
|
|
|
|
decrement() {
|
|
this.#setValue(this.#current - 1)
|
|
}
|
|
|
|
clamp() {
|
|
this.#setValue(this.#current)
|
|
}
|
|
|
|
get #current() {
|
|
return parseInt(this.inputTarget.value, 10) || this.minValue
|
|
}
|
|
|
|
#setValue(val) {
|
|
const clamped = Math.max(this.minValue, val)
|
|
this.inputTarget.value = clamped
|
|
this.#updateDecrement()
|
|
this.inputTarget.dispatchEvent(new Event('quantity:change', { bubbles: true }))
|
|
}
|
|
|
|
#updateDecrement() {
|
|
const atMin = this.#current <= this.minValue
|
|
this.decrementTarget.disabled = atMin
|
|
this.decrementTarget.setAttribute('aria-disabled', atMin)
|
|
}
|
|
}
|