a11yist/app/javascript/controllers/unsaved_changes_controller.js

40 lines
1.1 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 {
initialState = null
2024-10-28 23:06:04 +01:00
connect() {
this.initialState = this.formState()
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-01 00:50:15 +01:00
this.element.addEventListener("submit", (_) => this.initialState = null)
}
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
leavingPage(event) {
2024-11-01 00:50:15 +01:00
console.log(event.type)
if (this.initialState == null || this.initialState == this.formState()) {
return
}
2024-11-01 00:50:15 +01:00
if (event.type == "turbo:before-visit") {
if (!window.confirm(LEAVE_ALERT)) {
event.preventDefault()
} else {
this.initialState = null
}
} else {
this.initialState = null
event.returnValue = LEAVE_ALERT;
return event.returnValue;
}
}
}