Files
3dealer/resources/js/stimulus/auto-submit-controller.js
2026-10-24 00:20:57 +03:00

37 lines
1.3 KiB
JavaScript

import { Controller } from '@hotwired/stimulus'
// Submits the host <form> a short beat after a control inside it changes,
// coalescing a burst — rapid slider nudges, or holding an arrow key on a range
// input — into a single submit. Wire it on the <form>:
//
// <form data-controller="auto-submit"
// data-action="change->auto-submit#submit range-slider:change->auto-submit#submit"
// data-auto-submit-delay-value="300"> (delay optional, ms)
//
// `change` covers native inputs (checkbox, select); the range slider emits its
// own `range-slider:change` on commit. Uses requestSubmit() (not submit()) so a
// <turbo-frame> around the form still captures the navigation and validation runs.
//
// Optional data-auto-submit-media-value="(min-width: 64rem)" limits auto-submit
// to viewports matching that query — below it the form waits for its own submit
// button (e.g. the mobile filters drawer's "Apply").
export default class extends Controller {
static values = {
delay: { type: Number, default: 300 },
media: String,
}
submit() {
if (this.mediaValue && !window.matchMedia(this.mediaValue).matches) return
clearTimeout(this.#timer)
this.#timer = setTimeout(() => this.element.requestSubmit(), this.delayValue)
}
disconnect() {
clearTimeout(this.#timer)
}
#timer
}