File size: 2,676 Bytes
6b6430f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e2476f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* 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"; });
  }
}