// paste-bin UI β app logic.
// Contract surface is ONLY window.PasteBinAPI (generated client.js from openapi.json).
// No hand-rolled fetch, no hardcoded endpoints: every call below is a generated op.
"use strict";
(() => {
const API = window.PasteBinAPI;
if (!API) {
document.body.insertAdjacentHTML(
"afterbegin",
'
client.js failed to load β regenerate: archllm openapi paste-bin --client --out ui
'
);
return;
}
const $ = (s) => document.querySelector(s);
// pinned contract literals (mirror of x-error-literals, used for early client-side feedback)
const ERR_EMPTY_CONTENT = "Content cannot be empty";
const ERR_NO_FILE = "No file selected";
const ERR_MISMATCH = "File content does not match image type.";
const ERR_TOO_LARGE = "File too large. Maximum size is 20 MB.";
const ERR_NOT_FOUND = "Paste not found";
const MAX_BYTES = 20 * 1024 * 1024;
const IMG_ACCEPT = "image/png,image/jpeg,image/gif,image/bmp,image/webp,image/svg+xml,image/tiff";
const TYPE_ICON = { text: "π", image: "πΌ", file: "π" };
const state = { type: "text", file: null, lastView: null, lastId: null };
const recent = loadRecent();
/* ---------------- toasts ---------------- */
function toast(kind, title, detail = "", ttl = 5200) {
const el = document.createElement("div");
el.className = `toast toast-${kind}`;
const t = document.createElement("div");
t.className = "toast-title";
t.textContent = title;
el.appendChild(t);
if (detail) {
const d = document.createElement("div");
d.className = "toast-detail";
d.textContent = detail;
el.appendChild(d);
}
const x = document.createElement("button");
x.className = "toast-x";
x.setAttribute("aria-label", "Dismiss");
x.textContent = "Γ";
x.onclick = () => el.remove();
el.appendChild(x);
$("#toasts").appendChild(el);
requestAnimationFrame(() => el.classList.add("in"));
setTimeout(() => {
el.classList.remove("in");
setTimeout(() => el.remove(), 300);
}, ttl);
}
function errToast(e) {
const kind = e && e.status === 429 ? "warn" : "err";
const hint =
e && e.status === 429
? "upload budget (10/min) resets within 60 s"
: e && e.apiError
? `pinned contract message Β· ${API.ERROR_MESSAGES ? "see openapi.json x-error-literals" : ""}`
: "network error β is the API proxy up?";
toast(kind, e && e.message ? e.message : String(e), hint);
}
/* ---------------- health + contract badges ---------------- */
async function pingHealth() {
const pill = $("#healthPill");
try {
await API.getHealth();
pill.className = "pill pill-ok";
pill.innerHTML = 'api ok';
} catch {
pill.className = "pill pill-err";
pill.innerHTML = 'api down';
}
}
async function loadBadges() {
try {
const [idx, doc] = await Promise.all([API.getIndex(), API.fetchContract()]);
$("#brandTag").textContent = `service ${idx.service} Β· spec β openapi β client β ui`;
const ops = Object.values(doc.paths).reduce(
(n, p) => n + Object.keys(p).filter((m) => /^(get|post|put|delete|patch)$/.test(m)).length,
0
);
const b = $("#contractBadge");
b.textContent = `v${doc.info.version} Β· ${ops} ops`;
b.title = `OpenAPI ${doc.openapi} β ${doc.info.title} (openapi.json)`;
} catch {
$("#contractBadge").textContent = "v?";
}
}
/* ---------------- create: type tabs ---------------- */
function setType(t) {
state.type = t;
for (const b of $("#typeSeg").children) {
const on = b.dataset.t === t;
b.classList.toggle("on", on);
b.setAttribute("aria-selected", on ? "true" : "false");
}
$("#paneText").hidden = t !== "text";
$("#paneFile").hidden = t === "text";
$("#fileInput").accept = t === "image" ? IMG_ACCEPT : "";
$("#dzSub").textContent =
t === "image"
? "png Β· jpeg Β· gif Β· bmp Β· webp Β· svg Β· tiff β max 20 MB"
: "any file β max 20 MB";
if (state.file) validateFileForType();
}
$("#typeSeg").addEventListener("click", (e) => {
const b = e.target.closest("button[data-t]");
if (b) setType(b.dataset.t);
});
/* ---------------- create: file handling ---------------- */
const fileInput = $("#fileInput");
const dz = $("#dropzone");
function fmtSize(bytes) {
if (bytes < 1024) return bytes + " B";
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " KB";
return (bytes / (1024 * 1024)).toFixed(2) + " MB";
}
function validateFileForType() {
if (!state.file) return true;
if (state.type === "image" && !state.file.type.startsWith("image/")) {
toast("err", ERR_MISMATCH, state.file.name + " β switch to File tab for non-images");
return false;
}
return true;
}
function setFile(f) {
if (!f) return;
state.file = f;
if (f.size > MAX_BYTES) toast("warn", ERR_TOO_LARGE, f.name + " is " + fmtSize(f.size));
if (!validateFileForType()) {
clearFile();
return;
}
const isImg = state.type === "image" && f.type.startsWith("image/");
$("#dzIdle").hidden = true;
$("#dzPreview").hidden = false;
const thumb = $("#dzThumb");
const ico = $("#dzFileIco");
if (isImg) {
thumb.src = URL.createObjectURL(f);
thumb.hidden = false;
ico.hidden = true;
} else {
thumb.hidden = true;
thumb.removeAttribute("src");
ico.hidden = false;
ico.textContent = state.type === "file" ? "π" : "β";
}
$("#dzName").textContent = f.name;
$("#dzMeta").textContent = `${fmtSize(f.size)} Β· ${f.type || "unknown type"}`;
}
function clearFile() {
state.file = null;
fileInput.value = "";
const thumb = $("#dzThumb");
thumb.hidden = true;
thumb.removeAttribute("src");
$("#dzIdle").hidden = false;
$("#dzPreview").hidden = true;
}
dz.addEventListener("click", (e) => {
if (e.target.closest("#dzRemove")) return;
fileInput.click();
});
dz.addEventListener("keydown", (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
fileInput.click();
}
});
fileInput.addEventListener("change", () => setFile(fileInput.files[0] || null));
$("#dzRemove").addEventListener("click", (e) => {
e.stopPropagation();
clearFile();
});
["dragenter", "dragover"].forEach((ev) =>
dz.addEventListener(ev, (e) => {
e.preventDefault();
dz.classList.add("dragover");
})
);
["dragleave", "drop"].forEach((ev) =>
dz.addEventListener(ev, (e) => {
e.preventDefault();
dz.classList.remove("dragover");
})
);
dz.addEventListener("drop", (e) => {
const f = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0];
if (f) setFile(f);
});
/* ---------------- create: submit ---------------- */
$("#content").addEventListener("input", () => {
$("#charCount").textContent = String($("#content").value.length);
});
async function createPaste() {
const btn = $("#createBtn");
const title = $("#title").value.trim();
const expiry = $("#expiry").value;
const content = $("#content").value;
if (state.type === "text" && !content.trim()) {
toast("err", ERR_EMPTY_CONTENT);
$("#content").focus();
return;
}
if (state.type !== "text" && !state.file) {
toast("err", ERR_NO_FILE);
return;
}
if (state.file && state.file.size > MAX_BYTES) {
toast("warn", ERR_TOO_LARGE, state.file.name + " is " + fmtSize(state.file.size));
return;
}
btn.disabled = true;
btn.textContent = "Creatingβ¦";
$("#createHint").textContent = `POST /pastes Β· ${state.type} Β· ${expiry}`;
try {
const out = await API.postPastes({
paste_type: state.type,
title,
expiry,
content: state.type === "text" ? content : "",
file: state.type === "text" ? null : state.file,
});
toast("ok", `Created ${out.id}`, out.title ? `"${out.title}"` : state.type + " paste");
remember(out);
// reset the form, keep the type
$("#title").value = "";
$("#content").value = "";
$("#charCount").textContent = "0";
clearFile();
openPaste(out.id);
} catch (e) {
errToast(e);
} finally {
btn.disabled = false;
btn.textContent = "Create paste";
$("#createHint").textContent = "";
}
}
$("#createBtn").addEventListener("click", createPaste);
/* ---------------- view ---------------- */
function fmtTime(iso) {
if (!iso) return "";
const d = new Date(iso);
return isNaN(d) ? iso : d.toLocaleString();
}
function showOpenErr(msg) {
const el = $("#openErr");
el.textContent = msg;
el.hidden = !msg;
}
async function openPaste(id) {
id = (id || "").trim();
if (!API.PASTE_ID_RE.test(id)) {
showOpenErr("id must be 16 hex chars (contract: paste_id pattern)");
return;
}
showOpenErr("");
$("#openId").value = id;
$("#stage").innerHTML =
'loading ' + id + "β¦
";
$("#viewMeta").hidden = true;
$("#viewActions").hidden = true;
try {
const v = await API.getPastesPaste_id(id);
state.lastView = v;
state.lastId = id;
renderView(v);
} catch (e) {
state.lastView = null;
state.lastId = null;
renderViewError(e);
}
}
function renderView(v) {
const stage = $("#stage");
stage.innerHTML = "";
if (v.type === "text") {
const pre = document.createElement("pre");
pre.className = "view-text";
pre.textContent = v.content == null ? "" : v.content;
stage.appendChild(pre);
} else if (v.type === "image") {
const wrap = document.createElement("div");
wrap.className = "stage-img";
const img = document.createElement("img");
img.alt = v.title || "paste image";
img.src = API.getPastesPaste_idRawUrl(v.id);
img.onerror = () => {
img.onerror = null;
renderViewError(new API.ApiError(0, "image failed to load"));
};
wrap.appendChild(img);
stage.appendChild(wrap);
} else {
const wrap = document.createElement("div");
wrap.className = "view-file";
wrap.innerHTML =
'π
' +
'' +
'';
wrap.querySelector(".view-file-name").textContent = v.filename || "unnamed file";
wrap.querySelector(".view-file-sub").textContent = v.mimetype || "unknown type";
stage.appendChild(wrap);
}
const bits = [];
bits.push("type " + v.type);
if (v.title) bits.push("title " + escapeHtml(v.title));
if (v.filename) bits.push("file " + escapeHtml(v.filename));
if (v.mimetype) bits.push("mime " + v.mimetype);
bits.push("created " + fmtTime(v.created_at));
bits.push(v.expires_at ? "expires " + fmtTime(v.expires_at) : "expires never");
const meta = $("#viewMeta");
meta.innerHTML = bits.join(" Β· ");
meta.hidden = false;
$("#actRaw").href = API.getPastesPaste_idRawUrl(v.id);
$("#actDownload").href = API.getPastesPaste_idDownloadUrl(v.id);
$("#viewActions").hidden = false;
}
function renderViewError(e) {
const notFound = e && e.status === 404;
$("#stage").innerHTML = "";
const wrap = document.createElement("div");
wrap.className = "view-error";
wrap.innerHTML =
'' + (notFound ? "π" : "β οΈ") + "
" +
'' +
'';
wrap.querySelector(".view-error-title").textContent = notFound
? ERR_NOT_FOUND
: (e && e.message) || "could not load";
wrap.querySelector(".view-error-sub").textContent = notFound
? "it expired, or the id is wrong"
: "check the health pill β is the API up?";
$("#stage").appendChild(wrap);
$("#viewMeta").hidden = true;
$("#viewActions").hidden = true;
}
function escapeHtml(s) {
return s.replace(/[&<>"']/g, (c) => ({
"&": "&", "<": "<", ">": ">", '"': """, "'": "'",
}[c]));
}
$("#openBtn").addEventListener("click", () => openPaste($("#openId").value));
$("#openId").addEventListener("keydown", (e) => {
if (e.key === "Enter") openPaste($("#openId").value);
});
/* ---------------- view: actions ---------------- */
async function copyText(text, label) {
try {
await navigator.clipboard.writeText(text);
toast("ok", "Copied " + label);
} catch {
// fallback for non-secure contexts
const ta = document.createElement("textarea");
ta.value = text;
ta.style.position = "fixed";
ta.style.opacity = "0";
document.body.appendChild(ta);
ta.select();
try {
document.execCommand("copy");
toast("ok", "Copied " + label);
} catch {
toast("err", "Clipboard blocked", "select & copy manually");
}
ta.remove();
}
}
$("#actCopyJson").addEventListener("click", () => {
if (state.lastView) copyText(JSON.stringify(state.lastView, null, 2), "JSON");
});
$("#actCopyId").addEventListener("click", () => {
if (state.lastId) copyText(state.lastId, "id");
});
/* ---------------- recent chips (localStorage β the API has no list endpoint) ---------------- */
function loadRecent() {
try {
const raw = localStorage.getItem("pb.recent");
const arr = raw ? JSON.parse(raw) : [];
return Array.isArray(arr) ? arr : [];
} catch {
return [];
}
}
function saveRecent(list) {
try {
localStorage.setItem("pb.recent", JSON.stringify(list));
} catch {
/* private mode β chips just won't persist */
}
}
function remember(out) {
const list = loadRecent().filter((r) => r.id !== out.id);
list.unshift({ id: out.id, title: out.title, type: out.type, created_at: out.created_at });
saveRecent(list.slice(0, 12));
renderChips();
}
function renderChips() {
const list = loadRecent();
const box = $("#chips");
box.innerHTML = "";
$("#recentClear").hidden = list.length === 0;
if (!list.length) {
const s = document.createElement("span");
s.className = "chips-empty";
s.textContent = "nothing yet β pastes you create land here";
box.appendChild(s);
return;
}
for (const r of list) {
const chip = document.createElement("div");
chip.className = "chip";
chip.title = r.id + (r.title ? " β " + r.title : "") + (r.created_at ? " Β· " + fmtTime(r.created_at) : "");
const ico = document.createElement("span");
ico.className = "chip-ico";
ico.textContent = TYPE_ICON[r.type] || "π";
const id = document.createElement("span");
id.className = "chip-id";
id.textContent = r.id;
chip.appendChild(ico);
chip.appendChild(id);
if (r.title) {
const t = document.createElement("span");
t.className = "chip-title";
t.textContent = r.title;
chip.appendChild(t);
}
const x = document.createElement("button");
x.className = "chip-x";
x.setAttribute("aria-label", "Remove from recent");
x.textContent = "Γ";
x.onclick = (e) => {
e.stopPropagation();
saveRecent(loadRecent().filter((q) => q.id !== r.id));
renderChips();
};
chip.appendChild(x);
chip.addEventListener("click", () => openPaste(r.id));
box.appendChild(chip);
}
}
$("#recentClear").addEventListener("click", () => {
saveRecent([]);
renderChips();
});
/* ---------------- boot ---------------- */
setType("text");
renderChips();
pingHealth();
setInterval(pingHealth, 30000);
loadBadges();
})();