a11yist/app/javascript/controllers/unsaved_changes_controller.js

32 lines
928 B
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))
this.element.addEventListener("submit", (_) => this.initialState = this.formState())
}
2024-10-28 23:06:04 +01:00
formState() {
return JSON.stringify(Array.from(new FormData(this.element).entries())
.filter(x => x[1] != "")
.sort(x => x[0]))
2024-10-28 23:06:04 +01:00
}
leavingPage(event) {
if(this.initialState == this.formState()) {
return
}
if (!window.confirm(LEAVE_ALERT)) {
event.preventDefault()
}
}
}