Files
calminer/static/js/scenario-form.js

70 lines
1.7 KiB
JavaScript

document.addEventListener("DOMContentLoaded", () => {
const form = document.getElementById("scenario-form");
if (!form) {
return;
}
const nameInput = /** @type {HTMLInputElement | null} */ (
document.getElementById("name")
);
const descriptionInput = /** @type {HTMLInputElement | null} */ (
document.getElementById("description")
);
const table = document.getElementById("scenario-table");
const tableBody = document.getElementById("scenario-table-body");
const emptyState = document.getElementById("empty-state");
form.addEventListener("submit", async (event) => {
event.preventDefault();
if (!nameInput || !descriptionInput) {
return;
}
const payload = {
name: nameInput.value.trim(),
description: descriptionInput.value.trim() || null,
};
if (!payload.name) {
return;
}
const response = await fetch("/api/scenarios/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!response.ok) {
const errorText = await response.text();
console.error("Scenario creation failed", errorText);
return;
}
const data = await response.json();
const row = document.createElement("tr");
row.dataset.scenarioId = String(data.id);
row.innerHTML = `
<td>${data.name}</td>
<td>${data.description ?? "—"}</td>
`;
if (emptyState) {
emptyState.remove();
}
if (table) {
table.classList.remove("hidden");
table.removeAttribute("aria-hidden");
}
if (tableBody) {
tableBody.appendChild(row);
}
form.reset();
nameInput.focus();
});
});