5
0
Fork 0
mirror of https://0xacab.org/sutty/sutty synced 2024-11-23 01:16:21 +00:00
panel/app/javascript/controllers/unsaved_changes_controller.js

46 lines
1,010 B
JavaScript
Raw Normal View History

import { Controller } from "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)));
}
}