doodle-decoder / static /client.js
cetusian's picture
Deploy doodle-decoder
8e2476f verified
Raw History Blame Contribute Delete
2.68 kB
/* Rune Labs: the two helpers both static Spaces use. Plain globals, loaded before the page's own script. */
/* POST JSON to the Space and return the reply, or throw with the server's message. */
async function post(path, body) {
const r = await fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body || {}) });
const data = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(data.detail || "Something went wrong. Try again in a moment.");
return data;
}
/* One probability row: label, bar, percentage. Built with textContent, never HTML. */
function bar(label, p, top) {
const row = document.createElement("div");
row.className = top ? "bar top" : "bar";
const name = document.createElement("span");
name.textContent = label;
const track = document.createElement("div");
track.className = "track";
const fill = document.createElement("div");
fill.className = "fill";
fill.style.width = `${(p * 100).toFixed(1)}%`;
track.append(fill);
const pct = document.createElement("span");
pct.className = "pct";
pct.textContent = `${Math.round(p * 100)}%`;
row.append(name, track, pct);
return row;
}
/* Where a share should send people. On surogate.ai the page passes ?share=<its own address>, so a share made
inside the embed leads back there. Only that site or a local preview is trusted: a crafted link cannot
make the button share somewhere else. On its own, the Space shares itself. */
const SHARE_HOSTS = ["surogate.ai", "www.surogate.ai", "localhost", "127.0.0.1"];
function shareUrl(params) {
let url = null;
try { url = new URL(new URLSearchParams(location.search).get("share")); } catch { /* none or not a URL */ }
if (!url || !/^https?:$/.test(url.protocol) || !SHARE_HOSTS.includes(url.hostname)) {
url = new URL(location.href);
for (const k of ["share", "embed", "__theme"]) url.searchParams.delete(k);
}
for (const [k, v] of Object.entries(params || {})) url.searchParams.set(k, v);
return String(url);
}
/* Share text plus the link: the share sheet where there is one, the clipboard otherwise. */
async function share(button, text, params) {
const full = `${text} ${shareUrl(params)}`;
const copy = async () => { await navigator.clipboard.writeText(full); button.textContent = "Copied!"; };
try {
if (navigator.share) await navigator.share({ text: full }); else await copy();
} catch (err) {
// AbortError: the visitor closed the share sheet. Anything else (a frame without web-share): copy instead.
if (err.name !== "AbortError") await copy().catch(() => { button.textContent = "Copy the address bar to share"; });
}
}