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

56 lines
1.3 KiB
JavaScript
Raw Permalink Normal View History

2024-07-20 18:21:03 +00:00
import { Controller } from "@hotwired/stimulus";
export default class extends Controller {
connect() {
this.originalFormDataSerialized = this.serializeFormData(this.element);
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();
}
formData(form) {
const formData = new FormData(form);
formData.delete("authenticity_token");
return formData;
}
/*
* Elimina saltos de línea y espacios al serializar, para evitar
* detectar cambios cuando cambió el espaciado, por ejemplo cuando el
* editor con formato aplica espacios o elimina saltos de línea.
*/
serializeFormData(form) {
return (new URLSearchParams(this.formData(form))).toString().replaceAll("+", "").replaceAll("%0A", "");
}
hasChanged() {
return (this.originalFormDataSerialized !== this.serializeFormData(this.element));
}
}