Files
fizzy/app/javascript/controllers/css_variable_counter_controller.js
T

34 lines
749 B
JavaScript

import { Controller } from "@hotwired/stimulus"
import { debounce } from "helpers/timing_helpers"
export default class extends Controller {
static targets = [ "item", "counter" ]
static values = {
propertyName: String,
maxValue: { type: Number, default: 20 }
}
initialize() {
this.#updateCounter = debounce(this.#updateCounter.bind(this), 50)
}
connect() {
this.#updateCounter()
}
itemTargetConnected() {
this.#updateCounter()
}
itemTargetDisconnected() {
this.#updateCounter()
}
#updateCounter = () => {
if (!this.hasCounterTarget) return
const count = Math.min(this.itemTargets.length, this.maxValueValue)
this.counterTarget.style.setProperty(this.propertyNameValue, count)
}
}