5
0
Fork 0
mirror of https://0xacab.org/sutty/sutty synced 2024-11-22 16:26:21 +00:00
panel/app/javascript/controllers/unsaved_changes_controller.js
2024-07-20 15:21:03 -03:00

45 lines
1,020 B
JavaScript

import { Controller } from "@hotwired/stimulus";
export default class extends Controller {
connect() {
this.originalFormData = new FormData(this.element);
this.originalFormDataSerialized = this.serializeFormData(this.originalFormData);
this.submitting = false;
}
submit(event) {
this.submitting = true;
}
unsaved(event) {
if (this.submitting) return;
if (!this.hasChanged()) return;
this.submitting = false;
event.preventDefault();
event.returnValue = true;
}
unsavedTurbolinks(event) {
if (this.submitting) return;
if (!this.hasChanged()) return;
this.submitting = false;
if (window.confirm(this.element.dataset.unsavedChangesConfirmValue)) return;
event.preventDefault();
}
serializeFormData(formData) {
formData.delete("authenticity_token");
return (new URLSearchParams(formData)).toString();;
}
hasChanged() {
return (this.originalFormDataSerialized !== this.serializeFormData(new FormData(this.element)));
}
}