2024-10-28 22:39:32 +01:00
|
|
|
import { Controller } from "@hotwired/stimulus"
|
|
|
|
|
|
2024-10-29 01:20:21 +01:00
|
|
|
const LEAVE_ALERT = "Es gibt ungespeicherte Änderungen! Wirklich verlassen?"
|
|
|
|
|
|
2024-10-28 22:39:32 +01:00
|
|
|
// Connects to data-controller="unsaved-changes"
|
|
|
|
|
export default class extends Controller {
|
2024-11-01 03:26:46 +01:00
|
|
|
static targets = ["cancel"]
|
|
|
|
|
|
2024-10-29 01:20:21 +01:00
|
|
|
initialState = null
|
2024-11-03 21:58:25 +01:00
|
|
|
isSubmitted = false
|
2024-10-28 23:06:04 +01:00
|
|
|
|
2024-10-28 22:39:32 +01:00
|
|
|
connect() {
|
2024-11-03 21:58:25 +01:00
|
|
|
console.log("connect unsaved-changes")
|
2024-10-29 01:20:21 +01:00
|
|
|
this.initialState = this.formState()
|
2024-11-03 21:58:25 +01:00
|
|
|
|
|
|
|
|
console.log("usaved-changes connect ", this.cancelTargets)
|
2024-10-28 23:06:04 +01:00
|
|
|
|
|
|
|
|
window.addEventListener("beforeunload", (event) => this.leavingPage(event))
|
2024-10-29 01:20:21 +01:00
|
|
|
document.addEventListener('turbo:before-visit', (e) => this.leavingPage(e))
|
2024-11-03 21:58:25 +01:00
|
|
|
this.element.addEventListener("submit", (_) => this.isSubmitted = true)
|
|
|
|
|
// this.cancelTargets.forEach(element => {
|
|
|
|
|
// console.log(element)
|
|
|
|
|
// element.addEventListener("onclick", (_) => this.reset())
|
|
|
|
|
// });
|
2024-11-01 00:50:15 +01:00
|
|
|
}
|
2024-10-28 23:06:04 +01:00
|
|
|
|
|
|
|
|
formState() {
|
2024-10-28 23:19:23 +01:00
|
|
|
return JSON.stringify(Array.from(new FormData(this.element).entries())
|
2024-11-01 00:50:15 +01:00
|
|
|
.filter(x => x[1] != "")
|
|
|
|
|
.sort(x => x[0]))
|
2024-10-28 23:06:04 +01:00
|
|
|
}
|
2024-11-01 00:50:15 +01:00
|
|
|
|
2024-11-03 21:58:25 +01:00
|
|
|
reset() {
|
|
|
|
|
console.log("reset")
|
|
|
|
|
this.initialState = this.formState()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
hasChanged() {
|
|
|
|
|
console.log("hasChanged result", this.initialState != this.formState())
|
|
|
|
|
return this.formState() != this.initialState
|
|
|
|
|
}
|
|
|
|
|
|
2024-10-28 22:39:32 +01:00
|
|
|
leavingPage(event) {
|
2024-11-01 00:50:15 +01:00
|
|
|
console.log(event.type)
|
2024-11-03 21:58:25 +01:00
|
|
|
if (this.isSubmitted || !this.hasChanged()) {
|
2024-10-28 22:39:32 +01:00
|
|
|
return
|
|
|
|
|
}
|
2024-11-03 21:58:25 +01:00
|
|
|
if (!window.confirm(LEAVE_ALERT)) {
|
|
|
|
|
event.preventDefault()
|
2024-10-28 22:39:32 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|