a11yist/app/javascript/controllers/unsaved_changes_controller.js

42 lines
1 KiB
JavaScript
Raw Permalink 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() {
this.initialState = this.formState()
2024-11-03 21:58:25 +01:00
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)
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() {
this.initialState = this.formState()
}
hasChanged() {
return this.formState() != this.initialState
}
leavingPage(event) {
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()
}
}
}