1
0
Fork 0
mirror of https://github.com/maybe-finance/maybe.git synced 2025-07-20 05:39:39 +02:00
Maybe/app/javascript/controllers/auto_submit_form_controller.js
Nico 1b654faf9a
Fixes issue with mapping values during the transactions import (#1327)
* Adds custom debounce timeout to autosubmit form controller

- There's a default debounce timeout based on element type
- You can parameterize debounce timeout on a data-attribute

* Adds corrections based on js_lint

* Restores sleep on test

---------

Co-authored-by: Nicolás Galdámez <nicolas.galdamez@unagisoftware.com>
2024-10-21 10:13:55 -04:00

54 lines
1.4 KiB
JavaScript

import { Controller } from "@hotwired/stimulus";
export default class extends Controller {
// By default, auto-submit is "opt-in" to avoid unexpected behavior. Each `auto` target
// will trigger a form submission when the configured event is triggered.
static targets = ["auto"];
static values = {
triggerEvent: { type: String, default: "input" },
};
connect() {
this.autoTargets.forEach((element) => {
const event =
element.dataset.autosubmitTriggerEvent || this.triggerEventValue;
element.addEventListener(event, this.handleInput);
});
}
disconnect() {
this.autoTargets.forEach((element) => {
const event =
element.dataset.autosubmitTriggerEvent || this.triggerEventValue;
element.removeEventListener(event, this.handleInput);
});
}
handleInput = (event) => {
const target = event.target
clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
this.element.requestSubmit();
}, this.#debounceTimeout(target));
};
#debounceTimeout(element) {
if(element.dataset.autosubmitDebounceTimeout) {
return Number.parseInt(element.dataset.autosubmitDebounceTimeout);
}
const type = element.type || element.tagName;
switch (type.toLowerCase()) {
case 'input':
case 'textarea':
return 500;
case 'select-one':
case 'select-multiple':
return 0;
default:
return 500;
}
}
}