notes/static/note.js
2025-06-03 12:51:30 +00:00

50 lines
1.3 KiB
JavaScript

const textarea = document.getElementById("editor");
const status = document.getElementById("status");
const error = document.getElementById("error");
fetch("/api/" + noteName)
.then(res => {
if (!res.ok) throw new Error("Failed to load note. Status: " + res.status);
return res.text();
})
.then(text => {
textarea.value = text;
status.textContent = "Loaded";
})
.catch(err => {
error.textContent = "Error loading note: " + err.message;
status.textContent = "Load failed";
});
let timeout;
let last = "";
textarea.addEventListener("input", () => {
status.textContent = "Typing...";
clearTimeout(timeout);
timeout = setTimeout(() => {
const text = textarea.value;
if (text !== last) {
fetch("/api/" + noteName, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content: text })
})
.then(async res => {
if (res.ok) {
last = text;
status.textContent = "Saved";
} else {
const msg = await res.text();
status.textContent = "Save failed: " + msg;
}
})
.catch(err => {
status.textContent = "Save failed: " + err.message;
});
} else {
status.textContent = "No changes";
}
}, 500);
});