2024-04-14 12:41:22 +00:00
|
|
|
import { Behavior, fireEvents, registerBehavior } from "./index";
|
2024-04-01 13:19:38 +00:00
|
|
|
|
2024-04-14 12:41:22 +00:00
|
|
|
class FormBehavior extends Behavior {
|
2024-04-01 13:19:38 +00:00
|
|
|
constructor(element) {
|
2024-04-14 12:41:22 +00:00
|
|
|
super(element);
|
|
|
|
|
2024-04-11 17:07:20 +00:00
|
|
|
element.addEventListener("submit", this.onSubmit.bind(this));
|
2024-04-01 13:19:38 +00:00
|
|
|
}
|
|
|
|
|
2024-04-11 17:07:20 +00:00
|
|
|
async onSubmit(event) {
|
2024-04-01 13:19:38 +00:00
|
|
|
event.preventDefault();
|
|
|
|
|
|
|
|
const url = this.element.action;
|
|
|
|
const formData = new FormData(this.element);
|
|
|
|
if (event.submitter) {
|
|
|
|
formData.append(event.submitter.name, event.submitter.value);
|
|
|
|
}
|
|
|
|
|
|
|
|
await fetch(url, {
|
|
|
|
method: "POST",
|
|
|
|
body: formData,
|
|
|
|
redirect: "manual", // ignore redirect
|
|
|
|
});
|
|
|
|
|
2024-04-11 17:07:20 +00:00
|
|
|
const events = this.element.getAttribute("ld-fire");
|
|
|
|
if (fireEvents) {
|
|
|
|
fireEvents(events);
|
2024-04-01 13:19:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-14 12:41:22 +00:00
|
|
|
class AutoSubmitBehavior extends Behavior {
|
2024-04-01 13:19:38 +00:00
|
|
|
constructor(element) {
|
2024-04-14 12:41:22 +00:00
|
|
|
super(element);
|
|
|
|
|
2024-04-11 17:07:20 +00:00
|
|
|
element.addEventListener("change", () => {
|
|
|
|
const form = element.closest("form");
|
2024-04-01 13:19:38 +00:00
|
|
|
form.dispatchEvent(new Event("submit", { cancelable: true }));
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
registerBehavior("ld-form", FormBehavior);
|
2024-04-11 17:07:20 +00:00
|
|
|
registerBehavior("ld-auto-submit", AutoSubmitBehavior);
|