a11yist/app/javascript/controllers/unsaved_changes_controller.js

52 lines
1.4 KiB
JavaScript
Raw Normal View History

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 {
2024-11-01 03:26:46 +01:00
static targets = ["cancel"]
initialState = null
2024-11-03 21:58:25 +01:00
isSubmitted = false
2024-10-28 23:06:04 +01:00
connect() {
2024-11-03 21:58:25 +01:00
console.log("connect unsaved-changes")
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))
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() {
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
}
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()) {
return
}
2024-11-03 21:58:25 +01:00
if (!window.confirm(LEAVE_ALERT)) {
event.preventDefault()
}
}
}