// Shared helpers: DOM, formatting, API, markdown, modal, loading states. import { icon, FILE_ICON } from "./icons.js"; import { SITE, DESCRIPTION, canonicalPath, imagePath } from "./seo-meta.js"; export const $ = (s, el = document) => el.querySelector(s); // the page's title, description and canonical address as you move around (the server writes them for a first load) export function setMeta({ title, description, indexable } = {}) { const url = location.origin + canonicalPath(location.href); const rendered = document.querySelector('meta[name="rlx-page-url"]'); const changed = rendered?.content !== url; if (changed) { document.querySelectorAll('script[type="application/ld+json"]').forEach((s) => s.remove()); if (rendered) rendered.content = url; } if (title || changed) document.title = !title ? `${SITE}: RL environments on the Hugging Face Hub` : title.includes(SITE) ? title : `${title} · ${SITE}`; const desc = (description || (changed ? DESCRIPTION : document.querySelector('meta[name="description"]')?.content) || DESCRIPTION).slice(0, 300); const set = (selector, value) => document.querySelector(selector)?.setAttribute("content", value); set('meta[name="description"]', desc); for (const key of ["og:title", "twitter:title"]) set(`meta[${key.startsWith("og:") ? "property" : "name"}="${key}"]`, document.title); set('meta[property="og:description"]', desc); set('meta[name="twitter:description"]', desc); set('meta[property="og:url"]', url); if (changed) { const image = location.origin + imagePath(location.href); set('meta[property="og:image"]', image); set('meta[name="twitter:image"]', image); set('meta[property="og:type"]', /^\/t\//.test(location.pathname) || location.search.includes("task=") ? "article" : "website"); } if (changed || indexable !== undefined) set('meta[name="robots"]', indexable === false || /^\/(runs|run\/|compare\/)/.test(location.pathname) ? "noindex, follow" : "index, follow, max-image-preview:large, max-snippet:-1"); const canon = document.querySelector('link[rel="canonical"]'); if (canon) canon.href = url; } // go to another page of the app: a real path (/d/org/name, /t/...), so every page has its own address for search // engines and links; main.js routes on popstate export function nav(to, { replace = false } = {}) { history[replace ? "replaceState" : "pushState"](null, "", to); dispatchEvent(new PopStateEvent("popstate")); } export const $$ = (s, el = document) => [...el.querySelectorAll(s)]; export const fmt = new Intl.NumberFormat("en-US"); export const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); export const vals = (v) => (Array.isArray(v) ? v : v == null ? [] : [v]); // Rollouts graded before the runner translated it carry the General verifier's own label ("llm 3票" = 3 votes). export const checkMsg = (m) => String(m ?? "").replace(/^llm (\d+)票$/, (_, n) => `judged by the model (${n} vote${n === "1" ? "" : "s"})`); export const DOMAIN_NAME = { code: "Code", webdev: "Webdev", cyber: "Cyber", music: "Music", general: "General" }; export const storage = { get(k) { try { return localStorage.getItem(k); } catch { return null; } }, set(k, v) { try { localStorage.setItem(k, v); } catch { /* private mode */ } }, }; // `retry`: a GET that failed upstream (502/503/504: the dataset viewer or the Hub, briefly) is asked again that many // times, a moment apart, before the page shows an error export async function api(path, opts = {}) { const { retry = 0, ...o } = opts; for (let attempt = 0; ; attempt++) { try { return await apiOnce(path, o); } catch (e) { const again = [502, 503, 504].includes(e.status) && (!o.method || o.method === "GET") && !o.signal?.aborted; if (!again || attempt >= retry) throw e; await new Promise((r) => setTimeout(r, 1500 * (attempt + 1))); } } } async function apiOnce(path, opts) { const res = await fetch(path, { credentials: "same-origin", ...opts, headers: { ...(opts.body ? { "Content-Type": "application/json" } : {}), ...(opts.headers || {}) }, body: opts.body && typeof opts.body !== "string" ? JSON.stringify(opts.body) : opts.body, }); if (!res.ok) { let msg = `${res.status}`; try { const detail = (await res.json()).detail; if (Array.isArray(detail)) msg = detail.map((x) => `${(x.loc || []).filter((k) => k !== "body").join(".")}: ${x.msg || "invalid value"}`).join("; "); else if (typeof detail === "string") msg = detail; } catch { /* not json */ } const err = new Error(msg); err.status = res.status; throw err; } return res.json(); } // Data ships gzipped (Spaces serve static files uncompressed); inflate in the browser. export async function getJSONgz(url) { const res = await fetch(url, { cache: "no-cache" }); // revalidate (a cheap 304), so a redeploy never serves stale data if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`); const buf = new Uint8Array(await res.arrayBuffer()); if (buf[0] !== 0x1f || buf[1] !== 0x8b) return JSON.parse(new TextDecoder().decode(buf)); return new Response(new Blob([buf]).stream().pipeThrough(new DecompressionStream("gzip"))).json(); } export function money(x) { if (x == null || isNaN(x)) return "–"; if (x === 0) return "$0"; if (x < 0.01) return "<$0.01"; return "$" + (x < 10 ? x.toFixed(2) : x.toFixed(0)); } export function ago(ts) { if (!ts) return ""; const s = Date.now() / 1000 - ts; if (s < 60) return "just now"; if (s < 3600) return `${Math.floor(s / 60)} min ago`; if (s < 86400) return `${Math.floor(s / 3600)} h ago`; return new Date(ts * 1000).toLocaleDateString(); } export function dur(s) { if (s == null) return ""; s = Math.max(0, Math.round(s)); return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, "0")}s` : `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`; } export function bytes(n) { if (n == null) return ""; return n < 1024 ? `${n} B` : n < 1048576 ? `${(n / 1024).toFixed(0)} KB` : `${(n / 1048576).toFixed(1)} MB`; } export function tokensShort(n) { if (!n) return "0"; return n < 1000 ? String(n) : n < 1e6 ? `${(n / 1000).toFixed(n < 1e4 ? 1 : 0)}k` : `${(n / 1e6).toFixed(2)}M`; } // Escape first, then headings, lists, fences, inline code, bold, links. export function md(src) { const out = []; const lines = String(src ?? "").replace(/\r/g, "").split("\n"); let i = 0, para = [], list = null; const inline = (s) => esc(s) .replace(/`([^`]+)`/g, "$1") .replace(/\*\*([^*]+)\*\*/g, "$1") .replace(/(^|[\s(])\*([^*\s][^*]*?)\*(?=[\s.,;:!?)]|$)/g, "$1$2") .replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, '$1'); const flush = () => { if (para.length) { out.push(`

${inline(para.join(" "))}

`); para = []; } if (list) { out.push(`<${list.tag}>${list.items.map((x) => `
  • ${inline(x)}
  • `).join("")}`); list = null; } }; while (i < lines.length) { const line = lines[i]; if (/^\s*```/.test(line)) { flush(); const buf = []; i++; while (i < lines.length && !/^\s*```/.test(lines[i])) buf.push(lines[i++]); out.push(`
    ${esc(buf.join("\n"))}
    `); i++; continue; } const h = line.match(/^\s*(#{1,4})\s+(.*)$/); const ul = line.match(/^\s*[-*•]\s+(.*)$/); const ol = line.match(/^\s*\d+[.)]\s+(.*)$/); const tr = /^\s*\|.*\|\s*$/.test(line); if (h) { flush(); out.push(`

    ${inline(h[2])}

    `); } else if (tr) { flush(); const rows = []; while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) rows.push(lines[i++]); const cells = rows.filter((r) => !/^\s*\|[\s:|-]+\|\s*$/.test(r)).map((r) => r.trim().slice(1, -1).split("|").map((c) => c.trim())); out.push(`
    ${cells.map((r, n) => `${r.map((c) => (n ? `` : ``)).join("")}`).join("")}
    ${inline(c)}${inline(c)}
    `); continue; } else if (ul || ol) { if (para.length) { out.push(`

    ${inline(para.join(" "))}

    `); para = []; } const tag = ul ? "ul" : "ol"; if (!list || list.tag !== tag) { if (list) flush(); list = { tag, items: [] }; } list.items.push((ul || ol)[1]); } else if (!line.trim()) flush(); else { if (list) flush(); para.push(line.trim()); } i++; } flush(); return out.join(""); } export function toast(text, ms = 2200) { const t = $("#toast"); t.textContent = text; t.hidden = false; clearTimeout(toast._t); toast._t = setTimeout(() => (t.hidden = true), ms); } // A thin bar across the top while something loads. Nested calls are counted, so it finishes once. let busy = 0, crawl = null; export const progress = { start() { const bar = $("#progress i"); if (!bar) return; if (busy++ === 0) { clearInterval(crawl); bar.style.transition = "none"; bar.style.opacity = "1"; bar.style.width = "0"; requestAnimationFrame(() => { bar.style.transition = ""; bar.style.width = "30%"; }); crawl = setInterval(() => { const w = parseFloat(bar.style.width) || 0; if (w < 90) bar.style.width = w + (90 - w) * 0.08 + "%"; }, 250); } }, done() { const bar = $("#progress i"); if (!bar || busy === 0 || --busy > 0) return; clearInterval(crawl); bar.style.width = "100%"; setTimeout(() => { if (!busy) { bar.style.opacity = "0"; setTimeout(() => { if (!busy) bar.style.width = "0"; }, 300); } }, 180); }, async wrap(p) { this.start(); try { return await p; } finally { this.done(); } }, }; // Skeleton building blocks: widths are percentages, so they read as text rather than as boxes. export const sk = { line: (w = 100, h = 12) => ``, lines: (...ws) => ws.map((w) => sk.line(w)).join(""), box: (h, extra = "") => ``, card: (inner) => `
    ${inner}
    `, // a list's cards while a page of it loads: the same box as a real card, so the grid doesn't jump cards: (n = 6) => Array.from({ length: n }, () => `
  • ${sk.line(34, 11)}${sk.line(56, 16)}${sk.lines(96, 72)}${sk.line(28, 11)}
  • `).join(""), // a list's toolbar, its filters and six cards, as the environment pages lay them out list: (n = 6) => `
    ${sk.box(40, "flex:1;border-radius:10px")}${sk.box(40, "width:110px;border-radius:10px")}
    ${sk.box(14, "width:160px")}
      ${sk.cards(n)}
    `, // a page header: breadcrumbs, a kicker, the title and its facts head: () => `
    ${sk.box(12, "width:220px")}
    ${sk.box(22, "width:180px")}${sk.line(54, 28)}${sk.line(70, 13)}
    `, }; let modalReturn = null; export function openModal(title, html, { raw, kind } = {}) { modalReturn = document.activeElement; $("#modal-title").textContent = title; $("#modal-icon").innerHTML = kind ? icon(FILE_ICON[kind] || kind, 16, "kind") : ""; $("#modal-body").innerHTML = html; const open = $("#modal-open"); open.hidden = !raw; if (raw) { open.href = raw; open.innerHTML = `${icon("external", 14)}Open original`; } $("#modal").hidden = false; $("#scrim").hidden = false; document.body.classList.add("noscroll"); $("#modal-close").focus(); return $("#modal-body"); } export function closeModal() { if ($("#modal").hidden && !$("#dialog-root").innerHTML) return; $("#modal").hidden = true; $("#scrim").hidden = true; $("#modal-body").innerHTML = ""; $("#dialog-root").innerHTML = ""; document.body.classList.remove("noscroll"); if (modalReturn?.focus) modalReturn.focus(); modalReturn = null; } export function openDialog(html) { modalReturn = document.activeElement; const root = $("#dialog-root"); root.innerHTML = ``; $("#scrim").hidden = false; document.body.classList.add("noscroll"); return root.firstElementChild; } export const spinner = (cls = "") => ``; export function emptyState(ic, title, text = "", action = "") { return `
    ${icon(ic, 28)}

    ${esc(title)}

    ${text ? `

    ${text}

    ` : ""}${action}
    `; } const NUM = /^-?[$€£]?\(?-?[\d,]*\.?\d+\)?%?$/; export function table(rows, { header = true, max = 200 } = {}) { if (!rows || !rows.length) return `

    Empty.

    `; const [head, ...body] = header ? rows : [null, ...rows]; return `
    ${head ? `${head.map((c) => ``).join("")}` : ""} ${body.slice(0, max).map((r) => `${r.map((c) => `${esc(c)}`).join("")}`).join("")}
    ${esc(c)}
    `; } export const LIVE_STATUSES = ["queued", "starting", "setup", "running", "verifying"]; const STATUS = { queued: ["Queued", "clock"], starting: ["Starting sandbox", "box"], setup: ["Setting up", "box"], running: ["Agent running", "terminal"], verifying: ["Grading", "scale"], done: ["Done", "check"], failed: ["Failed", "alert"], cancelled: ["Stopped", "stop"], interrupted: ["Interrupted", "alert"] }; export function statusPill(status) { const live = LIVE_STATUSES.includes(status); const [label, ic] = STATUS[status] || [status, "info"]; return `${live ? '' : icon(ic, 12)}${esc(label)}`; } export const rewardClass = (r) => (r == null || r < 0 || r > 1 ? "none" : r >= 0.999 ? "full" : r > 0 ? "part" : "zero"); export const rewardText = (r) => (r == null ? "–" : Number(r) % 1 === 0 ? Number(r).toFixed(0) : Number(r).toFixed(2)); export function rewardBadge(reward, status) { if (reward == null) return status === "done" ? `not scored` : `–`; return `${rewardText(reward)}`; } // A spreadsheet-like grid: column letters, row numbers, numbers right-aligned, formulas shown as formulas, // and runs of empty rows collapsed to one thin row. const colName = (i) => { let s = ""; i += 1; while (i) { const m = (i - 1) % 26; s = String.fromCharCode(65 + m) + s; i = Math.floor((i - 1) / 26); } return s; }; export function sheetGrid(rows) { if (!rows || !rows.length) return `

    Empty sheet.

    `; const width = Math.max(...rows.map((r) => r.length)); let used = 0; rows.forEach((r) => r.forEach((c, i) => { if (c !== "" && c != null) used = Math.max(used, i + 1); })); const cols = Math.max(1, Math.min(width, used)); const out = []; let gap = 0; rows.forEach((r, n) => { const empty = !r.slice(0, cols).some((c) => c !== "" && c != null); if (empty) { gap++; return; } if (gap) { out.push(``); gap = 0; } // a lone text cell (a title or a section heading) spills across the empty cells to its right, as in Excel const filled = r.slice(0, cols).filter((c) => c !== "" && c != null).length; if (filled === 1 && r[0] !== "" && r[0] != null && !String(r[0]).startsWith("=") && cols > 1) { out.push(`${n + 1}${esc(r[0])}`); return; } out.push(`${n + 1}${Array.from({ length: cols }, (_, i) => { const v = r[i] ?? ""; const s = String(v); const cls = s.startsWith("=") ? "fx" : NUM.test(s.trim()) && s.trim() ? "num" : ""; return ` 40 ? ` title="${esc(s)}"` : ""}>${cls === "fx" ? `ƒ${esc(s)}` : esc(s)}`; }).join("")}`); }); return `
    ${Array.from({ length: cols }, (_, i) => ``).join("")}${out.join("")}
    ${colName(i)}
    `; } // ── community ──────────────────────────────────────────────────────────────── export const REPORT_URL = "https://huggingface.co/spaces/FineEnvs/RL-Explorer/discussions"; export const PUBLIC_NOTE = "Public rollouts show on the task for everyone, without your name. They may later be released as an open dataset (for example as SFT traces) to help the community study these environments."; export const PRIVATE_NOTE = "Keeping rollouts public helps the broader community compare models on the same tasks and learn from real traces. Private rollouts are visible only to you."; // A short burst of confetti from a point on screen: plain canvas, removed when done, skipped for reduced motion. export function confetti(x = innerWidth / 2, y = innerHeight / 3) { if (matchMedia("(prefers-reduced-motion: reduce)").matches) return; const c = document.createElement("canvas"); c.width = innerWidth; c.height = innerHeight; c.style.cssText = "position:fixed;inset:0;pointer-events:none;z-index:99"; document.body.appendChild(c); const g = c.getContext("2d"); const colors = ["--c-code", "--c-webdev", "--c-cyber", "--c-music", "--c-general"].map((v) => getComputedStyle(document.documentElement).getPropertyValue(v).trim()); const bits = Array.from({ length: 140 }, () => ({ x, y, vx: (Math.random() - 0.5) * 14, vy: -Math.random() * 12 - 4, r: Math.random() * Math.PI, vr: (Math.random() - 0.5) * 0.3, w: 6 + Math.random() * 6, h: 4 + Math.random() * 4, col: colors[(Math.random() * colors.length) | 0] })); const t0 = performance.now(); (function frame(t) { g.clearRect(0, 0, c.width, c.height); for (const b of bits) { b.vy += 0.35; b.vx *= 0.99; b.x += b.vx; b.y += b.vy; b.r += b.vr; g.save(); g.translate(b.x, b.y); g.rotate(b.r); g.fillStyle = b.col; g.fillRect(-b.w / 2, -b.h / 2, b.w, b.h); g.restore(); } if (t - t0 < 2200) requestAnimationFrame(frame); else c.remove(); })(t0); } export function visibilityBadge(v) { return v === "public" ? `${icon("globe", 12)}Public` : `${icon("shield", 12)}Private`; } // "Report an issue" pre-filled with the context it was raised from (HF's new-discussion form reads ?title= and // ?description=). Only ids, settings and versions go in: nothing about who is reporting. export function reportUrl({ task, run, version } = {}) { const lines = []; let title = "Issue: "; if (run) { const p = run.params || {}, pv = run.provenance || {}; title = `Rollout ${run.id}: `; lines.push(`**Rollout:** ${location.origin}/run/${run.id}`, `**Task:** \`${run.task_id}\` (${run.domain || run.runner || "Harbor"})`, `**Environment:** ${run.dataset || "unknown"} · runner ${run.runner || "harbor"}`, `**Status:** ${run.status}, reward ${run.reward ?? "not scored"}`, `**Model:** \`${run.model}\` via ${run.endpoint ? "own endpoint" : run.provider || "auto"}${run.judge ? `, judge \`${run.judge}\`` : ""}`, `**Settings:** ${Object.entries(p).filter(([k]) => k !== "max_tokens_used").map(([k, v]) => `${k}=${v}`).join(", ") || "defaults"}`, `**Versions:** explorer ${pv.app?.version || "?"} (${pv.app?.source || "?"}), ${run.runner === "nemo-gym" ? `NeMo verifier ${pv.commit || "?"}` : `harness ${pv.harness?.installed || pv.harness?.version || "?"}`}, dataset ${(pv.dataset?.revision || "?").slice(0, 10)}`); } else if (task) { title = `Task ${task.id}: `; lines.push(`**Task:** ${location.origin}/task/${encodeURIComponent(task.id)}`, `**Id:** \`${task.id}\` (${task.domain})`); } if (version) lines.push(`**Explorer:** ${version}`); const body = `${lines.join("\n")}\n\n### What happened\n\n\n### What you expected\n\n\n### Anything else (screenshots, steps)\n\n`; return `${REPORT_URL}/new?title=${encodeURIComponent(title)}&description=${encodeURIComponent(body)}`; } // Namespace navigation is exact, not a text search that also matches descriptions. export function ownerLink(owner, suffix = "") { return `${esc(owner + suffix)}`; }