Files
threshing-atlas/apps/atlas/ui.js
T

234 lines
17 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* ui.js — tabs, hero art, the plain-language overview and the illustrated valley map.
* Reads the same coded runs and results as the rest of the page (window.ThreshAtlas.state). */
(function () {
"use strict";
const E = window.ThreshEngine;
const $ = (q, el = document) => el.querySelector(q);
const $$ = (q, el = document) => [...el.querySelectorAll(q)];
const NS = "http://www.w3.org/2000/svg";
const cssVar = (n) => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
const esc = (x) => String(x ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const pct = (p, d = 0) => (p === null || p === undefined || isNaN(p) ? "–" : (p * 100).toFixed(d) + "%");
const DV = { Red: "--dr-red", Green: "--dr-green", Orange: "--dr-orange", Brown: "--dr-brown", Blue: "--dr-blue", Black: "--dr-black" };
const oneIn = (p) => (p > 0 ? Math.max(1, Math.round(1 / p)) : null);
function el(tag, attrs = {}, parent) {
const e = document.createElementNS(NS, tag);
for (const [k, v] of Object.entries(attrs)) if (v !== null && v !== undefined) e.setAttribute(k, v);
if (parent) parent.appendChild(e);
return e;
}
function rgb(c) {
c = (c || "").trim();
if (c.startsWith("#")) { const h = c.length === 4 ? [...c.slice(1)].map((x) => x + x).join("") : c.slice(1); return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16)); }
const m = c.match(/\d+(\.\d+)?/g); return m ? m.slice(0, 3).map(Number) : [128, 128, 128];
}
const mix = (a, b, t) => { const A = rgb(a), B = rgb(b); return `rgb(${A.map((v, i) => Math.round(v + (B[i] - v) * t)).join(",")})`; };
function rng(seed) { let s = seed >>> 0; return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296); }
// ------------------------------------------------------------ tabs
const TABS = ["valley", "odds", "dragons", "deep", "data"];
// old links (#overview, #flow, #planner ...) still land somewhere sensible
const ALIAS = { overview: "odds", planner: "valley", flow: "deep", rare: "deep", share: "data" };
const tabOf = (hash) => { const t = (hash || "").replace(/^#/, "").split("/")[0]; return TABS.includes(t) ? t : ALIAS[t] || null; };
function showTab(name, focus, keepHash) {
if (!TABS.includes(name)) name = ALIAS[name] || "valley";
TABS.forEach((t) => {
const on = t === name;
$("#tab-" + t).setAttribute("aria-selected", on);
$("#tab-" + t).tabIndex = on ? 0 : -1;
$("#panel-" + t).hidden = !on;
});
if (focus) $("#tab-" + name).focus();
try { $("#tab-" + name).scrollIntoView({ block: "nearest", inline: "center" }); } catch (e) { /* ignore */ }
if (!keepHash) { try { history.replaceState(null, "", "#" + name); } catch (e) { /* ignore */ } }
if (name === "valley" && window.ValleyExplorer) window.ValleyExplorer.fromHash();
if (name === "deep" && window.ThreshAtlas && window.ThreshAtlas.state.res) window.dispatchEvent(new Event("resize"));
}
TABS.forEach((t, i) => {
const b = $("#tab-" + t);
b.addEventListener("click", () => showTab(t));
b.addEventListener("keydown", (e) => {
if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
const j = (i + (e.key === "ArrowRight" ? 1 : TABS.length - 1)) % TABS.length;
showTab(TABS[j], true); e.preventDefault();
}
});
});
$$("[data-go]").forEach((b) => b.addEventListener("click", () => { showTab(b.dataset.go); window.scrollTo({ top: 0, behavior: "smooth" }); }));
// in-page links that point at sections inside other tabs
document.addEventListener("click", (e) => {
const a = e.target.closest('a[href^="#"]');
if (!a) return;
const id = a.getAttribute("href").slice(1);
if (tabOf(id)) {
// keep sub-paths such as #valley/blue so the destination can open on that selection
e.preventDefault();
try { history.replaceState(null, "", "#" + id); } catch (err) { /* ignore */ }
showTab(tabOf(id), false, true);
window.scrollTo({ top: 0, behavior: "smooth" });
return;
}
const target = document.getElementById(id);
const panel = target && target.closest(".tabpanel");
if (panel && panel.hidden) { e.preventDefault(); showTab(panel.id.replace("panel-", "")); target.scrollIntoView({ behavior: "smooth" }); }
});
// #valley/blue/meadow-Blue keeps its sub-path (the explorer reads it)
window.addEventListener("hashchange", () => { const t = tabOf(location.hash); if (t) showTab(t, false, t === "valley"); });
const initial = tabOf(location.hash);
showTab(initial || "valley", false, initial === "valley");
// ------------------------------------------------------------ hero art (original, generic silhouettes)
function drawHero() {
const svg = $("#hero-art");
svg.innerHTML = "";
const g = el("g", {}, svg);
el("path", { d: "M0 330 L120 250 L210 290 L330 200 L430 270 L560 180 L690 260 L800 210 L930 280 L1040 220 L1200 290 L1200 420 L0 420 Z", fill: "#2c1120" }, g);
el("path", { d: "M0 360 L160 300 L300 330 L470 270 L620 330 L780 285 L960 335 L1100 300 L1200 330 L1200 420 L0 420 Z", fill: "#220a17" }, g);
// tree line
const R = rng(3); let tl = "M0 420 L0 380";
for (let x = 0; x <= 1200; x += 14) { const h = 18 + R() * 30; tl += ` L${x + 7} ${392 - h} L${x + 14} ${392 - R() * 6}`; }
el("path", { d: tl + " L1200 420 Z", fill: "#16060e" }, g);
// a generic cliff-top keep, right side
const keep = el("g", { fill: "#1a0812", transform: "translate(0 40)" }, g);
el("path", { d: "M930 360 L930 250 L960 240 L990 250 L1010 236 L1040 250 L1070 232 L1100 250 L1130 245 L1150 360 Z" }, keep);
[[952, 196, 20, 58], [1000, 180, 22, 70], [1058, 190, 18, 60], [1098, 205, 16, 46]].forEach(([x, y, w, h]) => {
el("rect", { x, y, width: w, height: h }, keep);
el("path", { d: `M${x - 3} ${y} L${x + w / 2} ${y - 18} L${x + w + 3} ${y} Z` }, keep);
});
// distant riders: simple winged silhouettes
const shape = "M50 30 L18 6 L27 21 L3 16 L25 32 Z M50 30 L82 6 L73 21 L97 16 L75 32 Z M37 30 Q50 23 63 30 Q50 37 37 30 Z M63 30 L76 26 L80 28 L73 31 Z M37 30 Q24 37 10 34 Q22 33 36 31 Z";
[[700, 70, 0.9, 0.9], [560, 120, 0.55, 0.7], [820, 130, 0.42, 0.55], [380, 95, 0.32, 0.45]].forEach(([x, y, s, o]) =>
el("path", { d: shape, transform: `translate(${x} ${y}) scale(${s})`, fill: "#0f040a", "fill-opacity": o }, g));
const em = $("#embers");
if (em && !em.childElementCount) {
const R2 = rng(11);
for (let i = 0; i < 26; i++) {
const e = document.createElement("i");
e.style.left = (R2() * 100).toFixed(1) + "%";
e.style.animationDuration = (6 + R2() * 7).toFixed(1) + "s";
e.style.animationDelay = (-R2() * 12).toFixed(1) + "s";
const sz = (2 + R2() * 3).toFixed(1); e.style.width = e.style.height = sz + "px";
if (matchMedia("(prefers-reduced-motion: reduce)").matches) e.style.top = (10 + R2() * 80).toFixed(1) + "%";
em.appendChild(e);
}
}
}
drawHero();
// ------------------------------------------------------------ overview
function stratum(c, prefix) { const e = Object.entries(c.by_stratum).find(([k]) => k.startsWith(prefix)); return e ? e[1] : null; }
function dots(k, n, color, total = 100) {
const p = n ? k / n : 0, filled = p * total;
const cols = 20, r = 4, gap = 11, rows = Math.ceil(total / cols);
const svg = el("svg", { viewBox: `0 0 ${cols * gap} ${rows * gap}`, role: "img", "aria-label": `${pct(p, 1)} shown as ${total} dots` });
for (let i = 0; i < total; i++) {
const x = (i % cols) * gap + gap / 2, y = Math.floor(i / cols) * gap + gap / 2;
const on = i < Math.floor(filled), part = i === Math.floor(filled) && filled % 1 > 0.05;
el("circle", { cx: x, cy: y, r, fill: on ? color : "none", stroke: on || part ? color : cssVar("--line"), "stroke-width": 1.2, "fill-opacity": part ? 0.35 : 1 }, svg);
if (part) el("circle", { cx: x, cy: y, r: r * Math.sqrt(filled % 1), fill: color }, svg);
}
return svg.outerHTML;
}
// The odds for all six dragons come from the route model (data/policy.json); fetched once.
let policyP = null;
const getPolicy = () => policyP || (policyP = fetch("data/policy.json").then((r) => r.json()).catch(() => null));
const ENC_OF = { Red: "valley-Red", Orange: "meadow-Orange", Brown: "meadow-Brown", Green: "tree-Greens", Blue: "meadow-Blue", Black: "shadow-Black" };
const ENC_LABEL = { "valley-Red": "the valley Red", "meadow-Orange": "the meadow Orange", "meadow-Brown": "the meadow Brown", "tree-Greens": "the two Greens", "meadow-Blue": "the meadow Blue", "shadow-Black": "the Black, after the shadow" };
const POSE = { Red: "roaring", Orange: "flying", Brown: "resting", Green: "prowling", Blue: "coiled", Black: "flying" };
function renderColourOdds(policy) {
if (!policy) { $("#odds-colours").innerHTML = '<p class="small muted">The route model could not be loaded.</p>'; return; }
const lb = policy.samples.lowBias, all = policy.samples.all;
const cols = ["Red", "Green", "Orange", "Brown", "Blue", "Black"]
.map((c) => ({ c, p: lb.targets[c].eventually.pX.mean, pAll: all.targets[c].eventually.pX.mean, lo: lb.targets[c].eventually.pX.lo, hi: lb.targets[c].eventually.pX.hi }))
.sort((a, b) => b.p - a.p);
const enc = (c) => { const e = (all.model.tables.encounter || {})[ENC_OF[c]] || { outcomes: {} }; const n = Object.values(e.outcomes).reduce((a, b) => a + b, 0); return { k: e.outcomes[c] || 0, n }; };
const art = (c) => window.DragonArt ? `<svg class="odd-art" viewBox="0 0 200 160" aria-hidden="true">${window.DragonArt.svg(POSE[c], { fill: `var(${DV[c]})`, eyeFill: "var(--bg)" })}</svg>` : "";
$("#odds-colours").innerHTML = cols.map(({ c, p, pAll, lo, hi }) => {
const e = enc(c);
return `<a class="odd odd-colour" href="#valley/${c.toLowerCase()}" style="--c: var(${DV[c]})">${art(c)}
<span class="big">1 in ${oneIn(p)}</span><span class="what">runs end bonded to ${/^[AEIOU]/.test(c) ? "an" : "a"} ${c}, on the best route</span>
${dots(Math.round(p * 1000), 1000, cssVar(DV[c]))}
<span class="how">${pct(p, p < 0.1 ? 1 : 0)} per attempt (95% ${pct(lo, 1)}–${pct(hi, 1)}), from riders who logged every run${Math.abs(pAll - p) / p > 0.25 ? `; all form posts suggest ${pct(pAll, 1)}` : ""}. At ${ENC_LABEL[ENC_OF[c]]}, ${e.k} of ${e.n} genuine attempts bonded.</span>
<span class="go">See the route →</span></a>`;
}).join("");
const meadowAlpha = all.model.alphas.meadow, shadowAlpha = all.model.alphas.shadow;
const t2 = $("#truth-history");
if (t2) t2.innerHTML = `<h3>Earlier choices barely change who waits</h3><p class="small">${meadowAlpha >= 10000 ? "Which dragon waits in the meadow shows no link to anything you chose before." : "Which dragon waits in the meadow depends only a little on earlier choices."} ${shadowAlpha >= 500 ? "The shadow at the tree depends on them only weakly." : "The shadow at the tree shows some dependence on earlier choices, but the evidence is thin."} The model lets every roll depend on your history, and measured how much it does. Choices the form doesn't record (what you answered inside an encounter) might still matter.</p>`;
const t3 = $("#truth-burn");
if (t3) {
const rates = cols.map(({ c }) => ({ c, ...enc(c) })).filter((x) => x.n >= 20).map((x) => ({ ...x, p: x.k / x.n })).sort((a, b) => a.p - b.p);
t3.innerHTML = `<h3>The right answer can still burn</h3><p class="small">Even with the community's best answers, bond chances at the encounter run from ${pct(rates[0].p)} (${esc(ENC_LABEL[ENC_OF[rates[0].c]])}) to ${pct(rates[rates.length - 1].p)} (${esc(ENC_LABEL[ENC_OF[rates[rates.length - 1].c]])}). One death with the "right" answer doesn't mean the answer was wrong.</p>`;
}
}
function renderOverview(state) {
const r = state.res;
const reach = r.factors.reach_hour.overall;
const cb = r.chance.blue_meadow;
const bulkB = stratum(cb, "Bulk");
const tag = (txt) => `<span class="how">${txt}</span>`;
// A cadet who walks in and either dies or bonds. Deliberate deaths are left out: a rider burned at a bonding
// encounter they did not genuinely attempt (they were after another colour and planned to seek Malek). Runs with
// no recorded outcome are left out too. Same rule the solver uses for encounter odds (ThreshSolver.genuineAttempt).
const S = window.ThreshSolver;
const ended = state.runs.filter((x) => ["Bonded", "Incinerated", "Died before the hour"].includes(x.outcome));
const deliberate = (x) => { if (x.outcome !== "Incinerated" || !S) return false; const v = S.prepareRun(x); return !!v.encCtx && !S.genuineAttempt(x, v.encCtx); };
const cadets = ended.filter((x) => !deliberate(x));
const nDeliberate = ended.length - cadets.length;
const bonded = cadets.filter((x) => x.outcome === "Bonded").length;
const dead = cadets.length - bonded;
const earlyDeaths = cadets.filter((x) => x.outcome === "Died before the hour").length;
const cards = [
{ c: "--accent", big: pct(bonded / cadets.length), what: "become a rider", how: `${bonded.toLocaleString()} of ${cadets.length.toLocaleString()} cadets bonded a dragon. ${pct(1 - earlyDeaths / cadets.length)} made it to the tree-or-valley choice alive.`, w: { k: bonded, n: cadets.length } },
{ c: "--death", big: dead.toLocaleString(), what: "riders sent to Malek", how: `${pct(dead / cadets.length)} of cadets were burned or killed. Deliberate deaths (${nDeliberate.toLocaleString()} runs where the rider chose to die and try again) are not counted.`, w: { k: dead, n: cadets.length }, death: true },
];
$("#odds").innerHTML = cards.map((c) => `<div class="odd${c.death ? " death deco" : ""}" style="--c: var(${c.c})"><span class="big">${esc(c.big)}</span><span class="what">${esc(c.what)}</span>${dots(c.w.k, c.w.n, cssVar(c.c))}${tag(c.how)}</div>`).join("");
getPolicy().then(renderColourOdds);
// journey
const fr = r.factors.reach_hour.rows;
const lvl = (f, l) => fr.find((x) => x.factor === f && x.level === l);
const alone = lvl("company", "Alone"), two = lvl("company", "2 Squadmates");
const helpK = lvl("resolution", "DIED in combat");
const greens = r.green_rescue;
const stops = [
{ t: "Choose company", d: "Go in alone, or with one or two squadmates.", v: alone && two ? `Alone, ${pct(alone.p)} reached the hour. With two squadmates, ${pct(two.p)} did.` : "" },
{ t: "Pick a direction", d: "East toward the roar, west toward the scent, or the forest centre.", v: "Direction decides which first dragon can find you." },
{ t: "The first dragon", d: "A dragon finds you. Which colour is the game's roll, not yours.", v: "Keep your eyes down. This one is about surviving, not bonding.", roll: true },
{ t: "The scream", d: "Help the squadmate fighting two cadets, walk away, or ignore it and find a wounded cadet.", v: helpK ? `${helpK.n} logged runs died in the fight.` : "" },
{ t: "Fork in the road", d: "After the fight: west, deeper into the forest, or east.", v: "Only the bully path has a fork." },
{ t: "Tree or valley", d: "Climb the tallest tree, or walk to the valley centre.", v: "The tree holds a Red, two Greens and the rare shadow. The valley holds a Red, then the meadow's Orange, Brown and sometimes a Blue." },
{ t: "The bonding", d: "Who is waiting is partly luck. Then every answer is a test.", v: greens.green_encounters ? `At the two Greens, ${pct((greens.rescued_orange + greens.rescued_brown) / greens.green_encounters)} were rescued by an Orange or Brown.` : "", roll: true },
];
$("#journey").innerHTML = stops.map((s, i) => `<div class="stop${s.roll ? " roll" : ""}"><span class="n">${["I", "II", "III", "IV", "V", "VI", "VII"][i]}</span><span class="t">${esc(s.t)}</span><span class="d">${esc(s.d)}</span>${s.v ? `<span class="verdict">${esc(s.v)}</span>` : ""}</div>`).join("");
const chase = stratum(cb, "Form: chasing Blue");
$("#truths").innerHTML = `
<div class="truth"><h3>Lucky runs get shared</h3><p class="small">Riders hunting a rare dragon logged a Blue in ${pct(chase ? chase.p : null)} of their meadow visits. Riders who logged every run saw it in ${pct(bulkB ? bulkB.p : null)}. The game can't know what you're chasing, so the difference is who chose to write in. The Odds page leans on the riders who logged every run.</p></div>
<div class="truth" id="truth-history"></div>
<div class="truth" id="truth-burn"></div>`;
$("#h-truths-kicker").textContent = `What ${r.n.toLocaleString()} runs say`;
$("#hero-tagline").textContent = `Every path through the valley, mapped from ${r.n.toLocaleString()} runs riders logged.`;
}
// tooltip shared with app.js
const tipEl = $("#tip");
function tip(e, html) {
tipEl.innerHTML = html; tipEl.hidden = false;
const r = tipEl.getBoundingClientRect();
tipEl.style.left = Math.min(window.innerWidth - r.width - 8, e.clientX + 14) + "px";
tipEl.style.top = Math.min(window.innerHeight - r.height - 8, e.clientY + 14) + "px";
}
const hideTip = () => (tipEl.hidden = true);
window.AtlasUI = {
render(state) {
renderOverview(state);
if (window.ValleyExplorer) window.ValleyExplorer.setRuns(state);
},
showTab,
};
if (window.ThreshAtlas && window.ThreshAtlas.state && window.ThreshAtlas.state.res) window.AtlasUI.render(window.ThreshAtlas.state);
})();