85 lines
2.2 KiB
JavaScript
85 lines
2.2 KiB
JavaScript
const topicInput = document.getElementById("topic");
|
|
const generateBtn = document.getElementById("generate-btn");
|
|
const exportBtn = document.getElementById("export-btn");
|
|
const statusEl = document.getElementById("status");
|
|
const outputEl = document.getElementById("output");
|
|
|
|
let current = { topic: "", markdown: "" };
|
|
|
|
function setStatus(text, isError = false) {
|
|
statusEl.textContent = text;
|
|
statusEl.classList.toggle("error", isError);
|
|
}
|
|
|
|
async function generate() {
|
|
const topic = topicInput.value.trim();
|
|
if (!topic) {
|
|
setStatus("请先输入主题", true);
|
|
return;
|
|
}
|
|
|
|
generateBtn.disabled = true;
|
|
exportBtn.disabled = true;
|
|
setStatus("生成中,请稍候…");
|
|
outputEl.textContent = "正在生成…";
|
|
|
|
try {
|
|
const resp = await fetch("/api/generate", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ topic }),
|
|
});
|
|
const data = await resp.json();
|
|
|
|
if (!resp.ok) {
|
|
throw new Error(data.error || "生成失败");
|
|
}
|
|
|
|
current = { topic: data.topic, markdown: data.markdown };
|
|
outputEl.textContent = data.markdown;
|
|
exportBtn.disabled = false;
|
|
setStatus("生成完成");
|
|
} catch (err) {
|
|
outputEl.textContent = "生成失败";
|
|
setStatus(err.message, true);
|
|
} finally {
|
|
generateBtn.disabled = false;
|
|
}
|
|
}
|
|
|
|
async function exportMarkdown() {
|
|
if (!current.markdown) return;
|
|
|
|
try {
|
|
const resp = await fetch("/api/export", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(current),
|
|
});
|
|
|
|
if (!resp.ok) {
|
|
const data = await resp.json().catch(() => ({}));
|
|
throw new Error(data.error || "导出失败");
|
|
}
|
|
|
|
const blob = await resp.blob();
|
|
const url = URL.createObjectURL(blob);
|
|
const a = document.createElement("a");
|
|
a.href = url;
|
|
a.download = `${current.topic}-登记手册.md`;
|
|
document.body.appendChild(a);
|
|
a.click();
|
|
a.remove();
|
|
URL.revokeObjectURL(url);
|
|
setStatus("已开始下载");
|
|
} catch (err) {
|
|
setStatus(err.message, true);
|
|
}
|
|
}
|
|
|
|
generateBtn.addEventListener("click", generate);
|
|
exportBtn.addEventListener("click", exportMarkdown);
|
|
topicInput.addEventListener("keydown", (e) => {
|
|
if (e.key === "Enter") generate();
|
|
});
|