receipt-form: Prompt before leaving unfinished form

Whenever any of the fields on the page are changed, the form will be
marked as "dirty" until it is submitted.  If the form is "dirty" and the
user tries to navigate away from the page, the browser will prompt for
confirmation before leaving the page.
This commit is contained in:
2025-03-11 21:05:52 -05:00
parent 0c088e6fc8
commit dfa5ed407b

View File

@@ -30,6 +30,23 @@ const imgPreview = document.getElementById(
) as HTMLImageElement;
const xactselect = document.getElementById("transactions") as SlSelect;
let dirty = false;
window.addEventListener("beforeunload", function(evt) {
if (dirty) {
evt.preventDefault();
}
});
form.querySelectorAll("sl-input, sl-textarea, input").forEach((inp) => {
let eventName = inp.tagName == "input" ? "cange" : "sl-change";
inp.addEventListener(eventName, (evt) => {
if ((evt.target as HTMLInputElement).value) {
dirty = true;
}
});
});
form.addEventListener("submit", async (evt) => {
evt.preventDefault();
btnSubmit.loading = true;
@@ -55,6 +72,7 @@ form.addEventListener("submit", async (evt) => {
}
if (r.ok) {
notify("Successfully uploaded receipt", undefined, undefined, null);
dirty = false;
window.location.href = "/receipts";
} else {
const err = await getResponseError(r);
@@ -62,6 +80,10 @@ form.addEventListener("submit", async (evt) => {
}
});
form.addEventListener("reset", () => {
dirty = false;
});
cameraInput.addEventListener("ready", ((evt: CustomEvent) => {
btnSubmit.disabled = !evt.detail.hasPhoto;
btnUpload.disabled = !!evt.detail.hasPhoto;