mirror of
https://0xacab.org/sutty/sutty
synced 2024-11-22 14:36:21 +00:00
55 lines
1.3 KiB
JavaScript
55 lines
1.3 KiB
JavaScript
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));
|
|
}
|
|
}
|