Refactor paste.js to improve readability and maintainability; introduce ELEMENTS utility for DOM manipulation, enhance modal functionality, and streamline password handling for private pastes. Update user.js to correct API endpoint for user information retrieval. Add modal.js for reusable modal components and styles. Update paste.html to include modal.js and adjust edit button visibility. Minor fixes in main.js for consistent formatting.

This commit is contained in:
whoswhip
2025-07-11 17:51:04 -04:00
parent f64b617089
commit 57d9a4e3b2
10 changed files with 1005 additions and 254 deletions
+202 -195
View File
@@ -1,190 +1,194 @@
const visibility = [{ id: 0, name: "Public" }, { id: 1, name: "Unlisted" }, { id: 2, name: "Private" }];
let paste = null;
const ELEMENTS = {
get: (id) => document.getElementById(id),
create: (tag, props = {}) => {
const element = document.createElement(tag);
Object.assign(element, props);
return element;
},
setText: (id, text) => ELEMENTS.get(id).innerText = text,
setStyle: (id, styles) => Object.assign(ELEMENTS.get(id).style, styles),
hide: (id) => ELEMENTS.get(id).style.display = "none",
show: (id, display = "inline-block") => ELEMENTS.get(id).style.display = display
};
document.addEventListener("DOMContentLoaded", async function () {
const id = window.location.pathname.split("/")[1];
const contentPromise = fetch(`/api/pastes/${id}`).then(response => response.text());
const infoPromise = fetch(`/api/pastes/${id}/info`).then(response => response.json());
const [content, info] = await Promise.all([
fetch(`/api/pastes/${id}`).then(response => response.text()),
fetch(`/api/pastes/${id}/info`).then(response => response.json())
]);
const blur = document.createElement("div");
blur.id = "blur";
const blur = ELEMENTS.create("div", { id: "blur" });
blur.dataset.decrypted = "false";
document.body.appendChild(blur);
const blur2 = document.getElementById("blur");
const [content, info] = await Promise.all([contentPromise, infoPromise]);
const paste = info.paste;
function showPasswordModal(errorMsg = "") {
return new Promise((resolve, reject) => {
const oldModal = document.getElementById("password-modal-bg");
if (oldModal) oldModal.remove();
const modalBg = document.createElement("div");
modalBg.id = "password-modal-bg";
const modal = document.createElement("div");
modal.id = "password-modal";
const title = document.createElement("div");
title.innerText = "Private Paste";
title.className = "modal-title";
const label = document.createElement("label");
label.innerText = "Enter the password to view this paste:";
label.htmlFor = "password-input";
const input = document.createElement("input");
input.type = "password";
input.id = "password-input";
input.autocomplete = "current-password";
if (errorMsg) {
showNotification(errorMsg, "error", 3000);
}
const btnRow = document.createElement("div");
btnRow.className = "modal-btn-row";
const okBtn = document.createElement("button");
okBtn.innerText = "Unlock";
const cancelBtn = document.createElement("button");
cancelBtn.innerText = "Cancel";
btnRow.appendChild(cancelBtn);
btnRow.appendChild(okBtn);
modal.appendChild(title);
modal.appendChild(label);
modal.appendChild(input);
modal.appendChild(btnRow);
modalBg.appendChild(modal);
document.body.appendChild(modalBg);
input.focus();
function cleanup() {
if (modalBg.parentNode) modalBg.parentNode.removeChild(modalBg);
}
okBtn.onclick = () => {
resolve(input.value);
};
cancelBtn.onclick = () => {
cleanup();
reject(new Error("User cancelled"));
};
input.addEventListener("keydown", e => {
if (e.key === "Enter") {
okBtn.click();
} else if (e.key === "Escape") {
cancelBtn.click();
}
});
modalBg.addEventListener("click", e => {
if (e.target === modalBg) {
cancelBtn.click();
}
});
});
}
if (paste.visibility === 2) {
let success = false;
let lastError = "";
while (!success) {
try {
const password = await showPasswordModal(lastError);
const decrypted = await decryptAES(content, password);
blur2.dataset.decrypted = "true";
addContent(decrypted, paste.syntax);
document.getElementById("password-modal-bg")?.remove();
success = true;
} catch (error) {
if (error.message === "User cancelled") {
document.getElementById("password-modal-bg")?.remove();
break;
}
lastError = "Failed to decrypt, invalid password, or invalid data.";
}
}
} else {
blur2.dataset.decrypted = "true";
addContent(content, paste.syntax);
paste = info.paste;
const finalContent = paste.visibility === 2 ? await handlePrivatePaste(content) : content;
if (finalContent) {
blur.dataset.decrypted = "true";
addContent(finalContent, paste.syntax);
}
document.title = `${paste.title} - Sharpbin`;
addInfo(paste);
});
function addInfo(paste) {
document.getElementById("paste-title").innerText = paste.title;
document.getElementById("paste-date").innerText = `${convertUnixToLocal(paste.created)}`;
document.getElementById("paste-syntax").innerText = paste.syntax;
document.getElementById("paste-size").innerText = paste.size === 0 ? "" : formatSize(paste.size);
if (paste.size !== paste.trueSize && paste.trueSize) {
const sizeElem = document.getElementById("paste-size");
sizeElem.classList.add("has-true-size-tooltip");
let tooltip = document.createElement("div");
tooltip.className = "true-size-tooltip";
tooltip.innerText = `True size: ${formatSize(paste.trueSize)}`;
sizeElem.appendChild(tooltip);
sizeElem.onmouseenter = () => { tooltip.style.opacity = 1; };
sizeElem.onmouseleave = () => { tooltip.style.opacity = 0; };
}
document.getElementById("paste-author").innerText = paste.username;
document.getElementById("author-link").href = paste.username === "Anonymous" ? "" : `/u/${paste.username}`;
if (paste.username === "Anonymous") {
document.getElementById("author-link").innerText = "Anonymous";
document.getElementById("author-link").href = "";
document.getElementById("author-link").style.pointerEvents = "none";
document.getElementById("author-link").style.cursor = "not-allowed";
document.getElementById("author-link").style.color = "var(--text-color)";
document.getElementById("author-link").style.textDecoration = "none";
}
document.getElementById("paste-views").innerText = paste.views;
document.getElementById("info-throbber").style.display = "none";
document.getElementById("copy-button").addEventListener("click", function () {
navigator.clipboard.writeText(window.location.href);
showNotification("Paste copied to clipboard!", "info", 2000);
});
document.getElementById("download-button").addEventListener("click", function () {
const content = document.getElementById("paste-content").innerText;
const blob = new Blob([content], { type: "text/plain" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${paste.title}.txt`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showNotification("Paste downloaded!", "info", 2000);
});
document.getElementById("raw-button").addEventListener("click", function () {
window.location.href = `/raw/${paste.id}`;
});
async function handlePrivatePaste(content) {
try {
const modalController = await Modal.prompt(
"Enter the password to view this paste:",
"",
"Private Paste",
"password",
{ keepOpen: true }
);
while (true) {
try {
const password = await modalController.update("Enter the password to view this paste:");
if (password === null) {
modalController.close();
return null;
}
const decrypted = await decryptAES(content, password);
modalController.close();
return decrypted;
} catch (error) {
showNotification("Incorrect password. Please try again.", "error", 3000);
}
}
} catch (error) {
console.error('Error in handlePrivatePaste:', error);
return null;
}
}
function addInfo(paste) {
const isAnonymous = paste.username === "Anonymous";
ELEMENTS.setText("paste-title", paste.title);
ELEMENTS.setText("paste-date", convertUnixToLocal(paste.created));
ELEMENTS.setText("paste-syntax", paste.syntax);
ELEMENTS.setText("paste-size", paste.size === 0 ? "" : formatSize(paste.size));
setupSizeTooltip(paste);
setupAuthorLink(paste, isAnonymous);
ELEMENTS.setText("paste-views", paste.views);
ELEMENTS.hide("info-throbber");
setupActionButtons(paste);
setupDeleteButton(paste);
}
function setupSizeTooltip(paste) {
if (paste.size !== paste.trueSize && paste.trueSize) {
const sizeElem = ELEMENTS.get("paste-size");
sizeElem.classList.add("has-true-size-tooltip");
const tooltip = ELEMENTS.create("div", {
className: "true-size-tooltip",
innerText: `True size: ${formatSize(paste.trueSize)}`
});
sizeElem.appendChild(tooltip);
sizeElem.onmouseenter = () => tooltip.style.opacity = 1;
sizeElem.onmouseleave = () => tooltip.style.opacity = 0;
}
}
function setupAuthorLink(paste, isAnonymous) {
const authorLink = ELEMENTS.get("author-link");
ELEMENTS.setText("paste-author", paste.username);
if (isAnonymous) {
Object.assign(authorLink, {
innerText: "Anonymous",
href: ""
});
Object.assign(authorLink.style, {
pointerEvents: "none",
textDecoration: "none"
});
} else {
authorLink.href = `/u/${paste.username}`;
}
}
function setupActionButtons(paste) {
const actions = [
{
id: "copy-button",
action: () => {
const content = ELEMENTS.get("paste-content").innerText;
navigator.clipboard.writeText(content);
showNotification("Paste copied to clipboard!", "info", 2000);
}
},
{
id: "download-button",
action: () => downloadPaste(paste.title)
},
{
id: "raw-button",
action: () => window.location.href = `/raw/${paste.id}`
}
];
actions.forEach(({ id, action }) => {
ELEMENTS.get(id).addEventListener("click", action);
});
}
function downloadPaste(title) {
const content = ELEMENTS.get("paste-content").innerText;
const blob = new Blob([content], { type: "text/plain" });
const url = URL.createObjectURL(blob);
const a = ELEMENTS.create("a", {
href: url,
download: `${title}.txt`
});
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showNotification("Paste downloaded!", "info", 2000);
}
function setupDeleteButton(paste) {
waitForAuthData().then(() => {
if (authData.user.uuid === paste.authorUUID || authData.user.type === 255) {
document.getElementById("delete-button").style.display = "inline-block";
document.getElementById("delete-button").addEventListener("click", function () {
if (confirm("Are you sure you want to delete this paste?")) {
fetch(`/api/pastes/${paste.id}`, {
method: "DELETE"
}).then(response => {
if (response.ok) {
showNotification("Paste deleted!", "info", 2000);
window.location.href = "/";
} else {
showNotification("Failed to delete paste.", "error", 2000);
}
});
ELEMENTS.show("delete-button");
ELEMENTS.get("delete-button").addEventListener("click", async () => {
const confirmed = await Modal.confirm(
"Are you sure you want to delete this paste? This action cannot be undone.",
"Delete Paste",
"danger"
);
if (confirmed) {
deletePaste(paste.id);
}
});
}
});
}
function deletePaste(pasteId) {
fetch(`/api/pastes/${pasteId}`, { method: "DELETE" })
.then(response => {
const message = response.ok ? "Paste deleted!" : "Failed to delete paste.";
const type = response.ok ? "info" : "error";
showNotification(message, type, 2000);
if (response.ok) window.location.href = "/";
});
}
function waitForAuthData() {
return new Promise((resolve) => {
const checkAuth = setInterval(() => {
@@ -197,41 +201,49 @@ function waitForAuthData() {
}
function addContent(content, syntax) {
var code = document.createElement("code");
code.textContent = content;
var pre = document.getElementById("paste-content");
const code = ELEMENTS.create("code", {
textContent: content,
id: "paste-content"
});
const pre = ELEMENTS.get("paste-content");
pre.innerText = "";
pre.appendChild(code);
pre.removeAttribute("id");
code.id = "paste-content";
code.classList.add("language-" + syntax === "plaintext" ? "none" : syntax);
if (syntax !== "plaintext" && syntax !== "none" && syntax !== "" && syntax !== null) {
const isPlaintext = ["plaintext", "none", "", null].includes(syntax);
code.classList.add(`language-${isPlaintext ? "none" : syntax}`);
if (!isPlaintext) {
hljs.highlightElement(code);
document.getElementById("paste-content").style.padding = "0px"
code.style.padding = "0px";
}
hljs.lineNumbersBlock(code);
document.getElementById("content-throbber").style.display = "none";
ELEMENTS.hide("content-throbber");
}
async function decryptAES(content, password) {
const enc = new TextEncoder();
const rawData = atob(content);
const rawDataArray = Uint8Array.from(rawData, c => c.charCodeAt(0));
const salt = rawDataArray.slice(0, 16);
const iv = rawDataArray.slice(16, 28);
const ciphertext = rawDataArray.slice(28);
const [salt, iv, ciphertext] = [
rawDataArray.slice(0, 16),
rawDataArray.slice(16, 28),
rawDataArray.slice(28)
];
const keyMaterial = await window.crypto.subtle.importKey(
const keyMaterial = await crypto.subtle.importKey(
"raw",
enc.encode(password),
new TextEncoder().encode(password),
{ name: "PBKDF2" },
false,
["deriveKey"]
);
const key = await window.crypto.subtle.deriveKey(
const key = await crypto.subtle.deriveKey(
{
name: "PBKDF2",
salt: salt,
salt,
iterations: 100000,
hash: "SHA-256"
},
@@ -241,24 +253,19 @@ async function decryptAES(content, password) {
["decrypt"]
);
const decrypted = await window.crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: iv
},
const decrypted = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv },
key,
ciphertext
);
return new TextDecoder().decode(decrypted);
}
function convertUnixToLocal(unix) {
return new Date(unix * 1000).toLocaleString();
}
const convertUnixToLocal = (unix) => new Date(unix * 1000).toLocaleString();
function formatSize(bytes) {
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
}
const formatSize = (bytes) => {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
};