a11yist/app/javascript/controllers/unsaved_changes_controller.js
david d1294c2fc4
Some checks failed
/ Run tests (push) Successful in 1m22s
/ Run system tests (push) Failing after 1m33s
/ Build, push and deploy image (push) Successful in 3m22s
Refactorings and gui improvements
2024-11-03 21:58:25 +01:00

52 lines
No EOL
1.4 KiB
JavaScript

import { Controller } from "@hotwired/stimulus"
const LEAVE_ALERT = "Es gibt ungespeicherte Änderungen! Wirklich verlassen?"
// Connects to data-controller="unsaved-changes"
export default class extends Controller {
static targets = ["cancel"]
initialState = null
isSubmitted = false
connect() {
console.log("connect unsaved-changes")
this.initialState = this.formState()
console.log("usaved-changes connect ", this.cancelTargets)
window.addEventListener("beforeunload", (event) => this.leavingPage(event))
document.addEventListener('turbo:before-visit', (e) => this.leavingPage(e))
this.element.addEventListener("submit", (_) => this.isSubmitted = true)
// this.cancelTargets.forEach(element => {
// console.log(element)
// element.addEventListener("onclick", (_) => this.reset())
// });
}
formState() {
return JSON.stringify(Array.from(new FormData(this.element).entries())
.filter(x => x[1] != "")
.sort(x => x[0]))
}
reset() {
console.log("reset")
this.initialState = this.formState()
}
hasChanged() {
console.log("hasChanged result", this.initialState != this.formState())
return this.formState() != this.initialState
}
leavingPage(event) {
console.log(event.type)
if (this.isSubmitted || !this.hasChanged()) {
return
}
if (!window.confirm(LEAVE_ALERT)) {
event.preventDefault()
}
}
}