notes/static/note.js

82 lines
2.1 KiB
JavaScript
Raw Normal View History

2025-06-03 14:00:58 +02:00
const textarea = document.getElementById("editor");
const status = document.getElementById("status");
const error = document.getElementById("error");
2025-06-06 16:20:05 +02:00
const currentUser = document.getElementById("username").innerHTML;
const path = window.location.pathname;
2025-06-03 14:00:58 +02:00
2025-06-06 16:20:05 +02:00
// === ROUTE PARSING ===
let mode = "private";
let fetchUrl = "";
let editable = true;
let last = "";
if (path.startsWith("/public/")) {
const username = path.split("/")[2];
fetchUrl = "/publicapi/" + username;
editable = (currentUser === username);
mode = "public";
} else if (path === "/board") {
fetchUrl = "/boardapi";
mode = "shared";
editable = true;
} else if (path.startsWith("/n/") || path.startsWith("/notes/")) {
const note = path.split("/").pop();
fetchUrl = "/api/" + note;
editable = true;
} else {
error.textContent = "Unsupported path: " + path;
textarea.disabled = true;
throw new Error("Unknown path: " + path);
}
if (!editable) textarea.disabled = true;
// === FETCH INITIAL CONTENT ===
fetch(fetchUrl)
.then(res => {
2025-06-06 16:20:05 +02:00
if (!res.ok) throw new Error("Failed to load. Status: " + res.status);
return res.text();
})
2025-06-03 14:00:58 +02:00
.then(text => {
textarea.value = text;
2025-06-06 16:20:05 +02:00
last = text;
2025-06-03 14:00:58 +02:00
status.textContent = "Loaded";
})
.catch(err => {
2025-06-06 16:20:05 +02:00
error.textContent = "Error loading content: " + err.message;
status.textContent = "Load failed";
2025-06-03 14:00:58 +02:00
});
2025-06-06 16:20:05 +02:00
// === AUTOSAVE LOGIC ===
2025-06-03 14:00:58 +02:00
let timeout;
textarea.addEventListener("input", () => {
2025-06-06 16:20:05 +02:00
if (!editable) return;
2025-06-03 14:00:58 +02:00
status.textContent = "Typing...";
clearTimeout(timeout);
timeout = setTimeout(() => {
const text = textarea.value;
if (text !== last) {
2025-06-06 16:20:05 +02:00
fetch(fetchUrl, {
2025-06-03 14:00:58 +02:00
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content: text })
})
.then(async res => {
2025-06-03 14:00:58 +02:00
if (res.ok) {
last = text;
status.textContent = "Saved";
} else {
const msg = await res.text();
status.textContent = "Save failed: " + msg;
2025-06-03 14:00:58 +02:00
}
})
.catch(err => {
status.textContent = "Save failed: " + err.message;
2025-06-03 14:00:58 +02:00
});
} else {
status.textContent = "No changes";
}
}, 500);
});