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)); } }