93 lines
2.4 KiB
JavaScript
93 lines
2.4 KiB
JavaScript
const textarea = document.getElementById("editor");
|
|
const status = document.getElementById("status");
|
|
const error = document.getElementById("error");
|
|
const currentUser = document.getElementById("username").innerHTML;
|
|
const path = window.location.pathname;
|
|
|
|
// === 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 => {
|
|
if (!res.ok) throw new Error("Failed to load. Status: " + res.status);
|
|
return res.text();
|
|
})
|
|
.then(text => {
|
|
textarea.value = text;
|
|
last = text;
|
|
status.textContent = "Loaded";
|
|
})
|
|
.catch(err => {
|
|
error.textContent = "Error loading content: " + err.message;
|
|
status.textContent = "Load failed";
|
|
});
|
|
|
|
// === AUTOSAVE LOGIC ===
|
|
let timeout;
|
|
|
|
textarea.addEventListener("input", () => {
|
|
if (!editable) return;
|
|
status.textContent = "Typing...";
|
|
clearTimeout(timeout);
|
|
timeout = setTimeout(() => {
|
|
const text = textarea.value;
|
|
if (text !== last) {
|
|
fetch(fetchUrl, {
|
|
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);
|
|
});
|
|
|
|
|
|
const socket = io();
|
|
|
|
// Listen for updates
|
|
socket.on('board_update', data => {
|
|
if (true && data.content !== last) {
|
|
textarea.value = data.content;
|
|
last = data.content;
|
|
status.textContent = "Updated from server";
|
|
}
|
|
}); |