feature: the beginnings of chat working
This commit is contained in:
parent
85024c6e62
commit
649ff432bb
24 changed files with 1555 additions and 918 deletions
65
public/js/smartforms.js
Normal file
65
public/js/smartforms.js
Normal file
|
@ -0,0 +1,65 @@
|
|||
document.addEventListener("DOMContentLoaded", () => {
|
||||
/* make all forms semi-smart */
|
||||
const forms = document.querySelectorAll("form");
|
||||
for (const form of forms) {
|
||||
const script = form.querySelector("script");
|
||||
|
||||
form.onsubmit = async (event) => {
|
||||
event.preventDefault();
|
||||
|
||||
const form_data = new FormData(form);
|
||||
const body = {};
|
||||
for (const [key, value] of form_data.entries()) {
|
||||
const elements = key.split(".");
|
||||
let current = body;
|
||||
for (const element of elements.slice(0, elements.length - 1)) {
|
||||
current[element] = current[element] ?? {};
|
||||
current = current[element];
|
||||
}
|
||||
|
||||
current[elements.slice(elements.length - 1).shift()] = value;
|
||||
}
|
||||
|
||||
const url = form.action;
|
||||
|
||||
try {
|
||||
// TODO: send session header
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error_body = await response.json();
|
||||
const error = error_body?.error;
|
||||
|
||||
if (form.on_error) {
|
||||
return form.on_error(error);
|
||||
}
|
||||
|
||||
alert(error.message ?? "Unknown error!");
|
||||
return;
|
||||
}
|
||||
|
||||
const response_body = await response.json();
|
||||
if (form.on_response) {
|
||||
return form.on_response(response_body);
|
||||
}
|
||||
} catch (error) {
|
||||
console.dir({
|
||||
error,
|
||||
});
|
||||
|
||||
if (form.onerror) {
|
||||
return form.onerror(error);
|
||||
}
|
||||
|
||||
alert(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
Loading…
Add table
Add a link
Reference in a new issue