Threshing Atlas: monorepo, route graph, bot importer, daily source checks

- apps/atlas: the web page (valley map, route flow, Dragon Register)
- packages/core: coding rules and statistics (engine.js) and the shared route
  graph (graph.js): scene graph, decision-variable graph, bot-to-form crosswalk,
  Beta credible intervals
- packages/ingest: DragonKind bot importer to anonymised trajectories (no prose,
  no account identifiers); data/bot holds Ken's sample
- research/python: independent reference implementation + update_sources.py
- tests: JS/Python parity checks and graph/importer unit tests
- CI, GitHub Pages deploy, daily check of the community sheets and route PDF
- Email addresses in free-text form answers are redacted; the raw spreadsheet
  is not committed
- MIT code licence, CC BY 4.0 data licence

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UCzTd31GphpMXDhQqWrCMQ
This commit is contained in:
ekcSchiano
2026-11-01 21:54:54 +00:00
co-authored by Claude Opus 5.5
parent 0052d1a5fd
commit c3d067b88c
48 changed files with 8334 additions and 0 deletions
+701
View File
@@ -0,0 +1,701 @@
/* app.js — renders the Threshing Route Atlas from engine.js results. All numbers come from ThreshEngine. */
(function () {
"use strict";
const E = window.ThreshEngine;
const $ = (s, el = document) => el.querySelector(s);
const $$ = (s, el = document) => [...el.querySelectorAll(s)];
const NS = "http://www.w3.org/2000/svg";
const state = {
raw: null, bundled: null, allRuns: [], runs: [], res: null, missing: [],
filters: { source: "all", goal: "all", excludeFlagged: false },
target: "bond_Blue", widthMode: "traffic", minN: 10, conds: {},
fxOutcome: "blue_meadow", fxFactor: "resolution", rtTarget: "see_Blue", rtMin: 10,
};
// ------------------------------------------------------------ formatting
const pct = (p, d = 1) => (p === null || p === undefined || isNaN(p) ? "–" : (p * 100).toFixed(p > 0 && p < 0.001 ? 2 : d) + "%");
const ci = (w, d = 1) => (w && w.n ? `${pct(w.lo, d)}–${pct(w.hi, d)}` : "–");
const fmtOR = (x) => (x === null || x === undefined || !isFinite(x) ? "–" : x >= 100 ? x.toFixed(0) : x >= 10 ? x.toFixed(1) : x.toFixed(2));
const fmtP = (p) => (p === null || p === undefined ? "–" : p < 0.0001 ? "<0.0001" : p < 0.001 ? p.toExponential(1) : p.toFixed(p < 0.01 ? 3 : 2));
const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const kn = (w) => (w ? `${w.k}/${w.n}` : "–");
const rateTxt = (w, d = 1) => (w && w.n ? `${pct(w.p, d)} (${kn(w)}; 95% CI ${ci(w, d)})` : "no data");
function cssVar(name) { return getComputedStyle(document.documentElement).getPropertyValue(name).trim(); }
function rgb(c) {
c = c.trim();
if (c.startsWith("#")) {
const h = c.length === 4 ? c.slice(1).split("").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];
}
function 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(",")})`;
}
const DRAGON_VAR = { Red: "--dr-red", Green: "--dr-green", Orange: "--dr-orange", Brown: "--dr-brown", Blue: "--dr-blue", Black: "--dr-black" };
const dragonColor = (c) => cssVar(DRAGON_VAR[c] || "--dr-any");
const targetColor = (t) => dragonColor(E.TARGETS[t].color);
function svgEl(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 toast(msg) {
const t = document.createElement("div");
t.className = "toast"; t.textContent = msg; document.body.appendChild(t);
setTimeout(() => t.remove(), 2200);
}
async function copyText(text, label) {
try { await navigator.clipboard.writeText(text); toast(`Copied ${label}`); }
catch (e) {
const ta = document.createElement("textarea");
ta.value = text; ta.style.position = "fixed"; ta.style.opacity = "0"; document.body.appendChild(ta); ta.select();
let ok = false; try { ok = document.execCommand("copy"); } catch (_) { /* ignore */ }
ta.remove(); toast(ok ? `Copied ${label}` : "Copy was blocked here. Select the text manually instead.");
}
}
// ------------------------------------------------------------ tooltip
const tip = $("#tip");
function showTip(evt, html) {
tip.innerHTML = html; tip.hidden = false;
const x = evt.clientX ?? (evt.touches && evt.touches[0].clientX) ?? 0, y = evt.clientY ?? 0;
const r = tip.getBoundingClientRect();
tip.style.left = Math.min(window.innerWidth - r.width - 8, x + 14) + "px";
tip.style.top = Math.min(window.innerHeight - r.height - 8, y + 14) + "px";
}
const hideTip = () => (tip.hidden = true);
// ------------------------------------------------------------ data loading
async function loadBundled() {
const resp = await fetch("data/form_responses.json");
const raw = await resp.json();
state.bundled = raw;
useRaw(raw, `bundled snapshot (${raw.source_file}, exported ${raw.exported})`);
}
function useRaw(raw, label) {
const { runs, missing } = E.codeRows(raw.rows, raw.headers);
state.raw = raw; state.allRuns = runs; state.missing = missing; state.dataLabel = label;
state.conds = {};
recompute();
}
$("#upload").addEventListener("change", async (e) => {
const f = e.target.files[0];
if (!f) return;
try {
const buf = await f.arrayBuffer();
const wb = XLSX.read(buf, { type: "array", cellDates: true });
const name = wb.SheetNames.find((n) => /form responses/i.test(n)) || wb.SheetNames[0];
const ws = wb.Sheets[name];
const headers = (XLSX.utils.sheet_to_json(ws, { header: 1, blankrows: false })[0] || []).map(String);
const rows = XLSX.utils.sheet_to_json(ws, { defval: null, raw: true });
useRaw({ rows, headers, source_file: f.name, exported: new Date().toISOString().slice(0, 10) }, `uploaded file ${f.name} (sheet "${name}")`);
$("#btn-reset-data").hidden = false;
toast(`Loaded ${rows.length} rows from ${f.name}`);
} catch (err) {
toast("That file could not be read. Export the responses sheet as .xlsx or .csv and try again.");
console.error(err);
}
e.target.value = "";
});
$("#btn-reset-data").addEventListener("click", () => { useRaw(state.bundled, `bundled snapshot (${state.bundled.source_file}, exported ${state.bundled.exported})`); $("#btn-reset-data").hidden = true; });
function recompute() {
state.runs = E.applyFilters(state.allRuns, state.filters);
state.res = E.analyse(state.allRuns, state.filters);
renderAll();
}
// ------------------------------------------------------------ header
function renderStatus() {
const m = state.res.meta;
const src = Object.entries(m.sources).sort((a, b) => b[1] - a[1]).map(([k, v]) => `${k} ${v.toLocaleString()}`).join(" · ");
const filt = [];
if (state.filters.source !== "all") filt.push(state.filters.source === "form" ? "form submissions only" : "bulk logs only");
if (state.filters.goal !== "all") filt.push(state.filters.goal === "exclude_rare" ? "not chasing Blue/Black" : "chasing Blue/Black");
if (state.filters.excludeFlagged) filt.push("flagged rows dropped");
$("#data-status").innerHTML = `
<span><b>${state.res.n.toLocaleString()}</b> runs${state.res.n !== state.allRuns.length ? ` of ${state.allRuns.length.toLocaleString()}` : ""}</span>
<span>${esc(src)}</span>
<span>Form dates ${m.date_min || "?"} → ${m.date_max || "?"}</span>
<span class="pill">${esc(state.dataLabel)}</span>
${filt.length ? `<span class="pill warn">Filtered: ${esc(filt.join(", "))}</span>` : ""}
${state.missing.length ? `<span class="pill warn">Questions not found in this file: ${esc(state.missing.join(", "))}</span>` : ""}`;
}
// ------------------------------------------------------------ findings
function stratumRate(chance, keyPart) {
const e = Object.entries(chance.by_stratum).find(([k]) => k.startsWith(keyPart));
return e ? e[1] : null;
}
const ROUTE_FACTORS = ["direction", "first_sighting", "resolution", "company"];
const NOT_A_CHOICE = /^(Unsure|Unknown|Multiple|\(not recorded\)|Unknown\/lost count|Unsure\/unknown)/;
function buildFindings() {
const r = state.res, out = [];
const cb = r.chance.blue_meadow, cs = r.chance.shadow;
const bulkB = stratumRate(cb, "Bulk"), chaseB = stratumRate(cb, "Form: chasing Blue"), otherB = stratumRate(cb, "Form: other");
const encBlue = r.encounters.find((e) => e.context === "Blue (meadow)");
const encBlack = r.encounters.find((e) => e.context === "Black (shadow)");
if (cb.overall.n) {
const biasShown = chaseB && bulkB && chaseB.n >= 20 && bulkB.n >= 20 && chaseB.lo > bulkB.hi;
let t;
if (biasShown) {
t = `<p><b>The meadow Blue appeared in ${rateTxt(cb.overall)} of logged meadow visits, but that figure is inflated.</b> Players chasing a Blue report it in ${pct(chaseB.p)} of their visits. Bulk logs, which record every run, show ${rateTxt(bulkB)}. The game cannot see what you are chasing, so that gap comes from which runs get reported.</p>`;
t += `<p>A realistic expectation is nearer the bulk-log rate, about one meadow visit in ${Math.round(1 / Math.max(bulkB.p, 0.001))}, than the headline figure.${otherB ? ` Form players who were not chasing a Blue report ${pct(otherB.p)}, which still carries some selective reporting.` : ""}</p>`;
} else {
t = `<p><b>The meadow Blue appeared in ${rateTxt(cb.overall)} of logged meadow visits in the current selection.</b> Compare the data-source filter settings to see how much this depends on who logged the runs.</p>`;
}
out.push(["bias", "Reporting bias", t]);
}
const mb = r.models.blue_meadow;
if (mb) {
const sig = mb.terms.filter((t) => ROUTE_FACTORS.includes(t.factor) && t.p < 0.05 && !NOT_A_CHOICE.test(t.level));
const rk = E.rankRoutes(state.runs, "see_Blue", state.rtMin);
const adjSig = rk.rows.filter((x) => x.mh_q !== undefined && x.mh_q < 0.05);
let t = sig.length
? `<p><b>After adjusting for reporting bias, ${sig.length === 1 ? "one recorded choice was" : sig.length + " recorded choices were"} linked to the Blue appearing:</b> ${sig.map((s) => `${esc(s.term)} (OR ${fmtOR(s.or)}, 95% CI ${fmtOR(s.lo)}–${fmtOR(s.hi)}, p = ${fmtP(s.p)})`).join("; ")}.</p>`
: `<p><b>No recorded route choice changed the chance of the Blue appearing once reporting bias is held fixed.</b> Direction, first sighting, how you handled the cadet and who you entered with all have adjusted odds ratios whose 95% intervals include 1 (n = ${mb.n} meadow visits).</p>`;
t += `<p>Of ${rk.n_routes_tested} full routes with at least ${state.rtMin} meadow visits, ${adjSig.length} beat the others after adjustment and correction for multiple testing. The "precise pathways" shared on Reddit may still matter through choices the form does not record, such as how you react to the first dragon.</p>`;
out.push(["blue", "Blue", t]);
}
if (encBlue && encBlue.overall.n) {
out.push(["blue", "Blue", `<p><b>Reaching the Blue is not enough. Only ${rateTxt(encBlue.overall)} of Blue attempts ended in a bond</b> (${pct(encBlue.intent_matched.p)} when the player wanted a Blue). The community PDF's step-by-step survival rates multiply out to about 25% for the standard answers. Expect several Blue encounters per bond, and do not treat one death as proof that an answer is wrong.</p>`]);
}
if (cs.overall.n) {
const bulkS = stratumRate(cs, "Bulk"), formS = Object.entries(cs.by_stratum).filter(([k]) => k.startsWith("Form"));
const fk = formS.reduce((a, [, w]) => a + w.k, 0), fn = formS.reduce((a, [, w]) => a + w.n, 0);
const fw = E.wilson(fk, fn);
let t = `<p><b>The tree shadow showed up in ${rateTxt(cs.overall)} of logged tree climbs.</b>${fn ? ` Form submissions: ${rateTxt(fw)}.` : ""}`;
if (bulkS && bulkS.n >= 30 && fn >= 30 && fw.lo > bulkS.hi) t += ` Bulk logs: ${rateTxt(bulkS)}. Those two cannot both be the true rate for the same game. The form figure is the one exposed to selective reporting, so the true rate is probably nearer the bulk logs, whose 95% upper bound is ${pct(bulkS.hi)} per climb.`;
t += `</p>`;
if (encBlack && encBlack.overall.n) t += `<p>Once the Black appears it is the easiest dragon to bond: ${rateTxt(encBlack.overall)}.</p>`;
out.push(["black", "Black", t]);
}
// leads: unadjusted factor rows with q < 0.05 on route-type factors, for the shadow
const leadF = ["post_path", "attempt_group", "direction", "first_sighting", "resolution", "company", "combat_first"];
const sh = r.factors.shadow.rows.filter((x) => leadF.includes(x.factor) && x.q !== undefined && x.q < 0.05 && x.or > 1 && !NOT_A_CHOICE.test(x.level));
if (sh.length) {
const ms = r.models.shadow;
let t = `<p><b>Shadow leads to test, not established:</b> ${sh.map((x) => `<i>${esc(labelFactor(x.factor))}: ${esc(x.level)}</i> had the shadow in ${rateTxt(x)} vs the rest (OR ${fmtOR(x.or)}, q = ${fmtP(x.q)})`).join("; ")}.</p>`;
const att = ms && ms.terms.find((tm) => tm.factor === "attempt" && tm.level === "First attempt");
if (att) t += `<p>The first-attempt pattern survives adjustment for source, goal, direction and date (OR ${fmtOR(att.or)}, 95% CI ${fmtOR(att.lo)}–${fmtOR(att.hi)}). That matches a theory on Reddit that a fresh account rolls the shadow more often, but players who strike lucky on a first run may also be more likely to submit the form.</p>`;
t += `<p>The cheapest test is a bulk log that records every tree climb, including the dull ones, with these choices noted.</p>`;
out.push(["lead", "Lead", t]);
}
// common dragons
const common = r.encounters.filter((e) => ["Red (valley)", "Green (two Greens)", "Orange (meadow)", "Brown (meadow)", "Red (tree, descend quickly)"].includes(e.context) && e.intent_matched.n >= 10);
if (common.length) {
out.push(["", "Common", `<p><b>For the common colours, intent matters more than route.</b> Among players who wanted that colour: ${common.map((e) => `${esc(e.context)} ${pct(e.intent_matched.p, 0)} (${kn(e.intent_matched)})`).join(", ")}. The tree Red is the hardest bond in the game.</p>`]);
}
return out;
}
function renderFindings() {
$("#findings-list").innerHTML = buildFindings().map(([cls, tag, html], i) =>
`<div class="finding ${cls}"><span class="mark">${i + 1}</span><div><span class="tag">${esc(tag)}</span>${html}</div></div>`).join("");
}
const FACTOR_LABEL = { company: "Company", direction: "Direction", first_sighting: "First sighting", scream: "Scream choice", resolution: "Cadet encounter",
combat_first: "First combat move", post_path: "Fork in the road", hour: "After an hour", wing: "Wing", squad: "Squad",
attempt_group: "Attempt", source: "Data source", goal: "Chasing", attempt: "Attempt", period: "Date", };
const labelFactor = (f) => FACTOR_LABEL[f] || f;
// ------------------------------------------------------------ route map
const RARE_T = ["bond_Blue", "bond_Black", "see_Blue", "see_shadow"];
const OTHER_T = ["bond_Red", "bond_Green", "bond_Orange", "bond_Brown", "bond_any"];
function renderTargets() {
const chip = (t, featured) => {
const c = E.TARGETS[t].color ? DRAGON_VAR[E.TARGETS[t].color] : "--dr-any";
return `<button type="button" class="tchip${featured ? " featured" : ""}" data-t="${t}" aria-pressed="${state.target === t}" style="--c: var(${c})"><span class="sw"></span>${esc(E.TARGETS[t].label)}</button>`;
};
$("#targets-rare").innerHTML = RARE_T.map((t) => chip(t, t.startsWith("bond"))).join("");
$("#targets-other").innerHTML = OTHER_T.map((t) => chip(t, false)).join("");
$$(".tchip").forEach((b) => b.addEventListener("click", () => { state.target = b.dataset.t; $("#best-routes").innerHTML = ""; renderTargets(); renderMap(); }));
}
const ORDER = {
company: ["Alone", "1 Squadmate", "2 Squadmates", "Unknown"],
direction: ["East", "Center", "West", "Multiple", "Unknown"],
first_sighting: ["Red", "Orange", "Brown", "Green", "Unsure", "Unknown"],
post_path: ["Forest", "West", "East", "(no fork)", "Unknown"],
hour: ["Climb the tree", "Valley centre"],
encounter: ["Tree: Red below", "Tree: two Greens", "Tree: shadow → Blue/Black", "Valley: bond the Red", "Meadow: Orange", "Meadow: Brown", "Meadow: Orange/Brown", "Meadow: Blue", "Meadow (no attempt recorded)"],
end: ["Bonded Red", "Bonded Green", "Bonded Orange", "Bonded Brown", "Bonded Blue", "Bonded Black", "Incinerated", "Died before the hour"],
};
const SHORT = {
"Help → Killed the bullies yourself": "Help · killed bullies", "Help → Squadmate's revenge": "Help · squadmate's revenge",
"Help → Left bullies to the dragons": "Help · left to dragons", "Help → DIED in combat": "Help · died in combat", "Help → Unknown": "Help · unknown",
"Ignore the scream → Tourniquet": "Ignore · tourniquet", "Ignore the scream → Left injured cadet": "Ignore · left cadet",
"Ignore the scream → Took their weapons": "Ignore · took weapons", "Investigate & leave → Left them to it": "Investigate · walked away",
"Tree: shadow → Blue/Black": "Tree: shadow (Blue→Black)", "Meadow (no attempt recorded)": "Meadow: none recorded", "Unknown → Unknown": "Unknown",
};
const short = (v) => SHORT[v] || v;
const condSets = () => Object.fromEntries(Object.entries(state.conds).map(([k, v]) => [k, new Set(v)]));
function renderMap() {
const svg = $("#map");
svg.innerHTML = "";
const runs = state.runs;
const base = E.buildGraph(runs, state.target, {});
const sel = E.buildGraph(runs, state.target, condSets());
const hasSel = Object.values(state.conds).some((v) => v.length);
const selNode = new Map(sel.nodes.map((n) => [n.id, n]));
const minN = state.minN;
const tcol = targetColor(state.target), low = cssVar("--link-low"), surface = cssVar("--raised");
const shell = $(".map-scroll");
const W = Math.max(1440, shell.clientWidth || 1440), H = 660, top = 40, bottom = 16, left = 10, right = 168, nodeW = 12;
svg.setAttribute("width", W); svg.setAttribute("height", H); svg.setAttribute("viewBox", `0 0 ${W} ${H}`);
const S = E.STAGES.length;
const colX = (i) => left + (i * (W - left - right - nodeW)) / (S - 1);
const cols = E.STAGES.map((s, i) => {
const ns = base.nodes.filter((n) => n.stage === i);
const ord = ORDER[s.key];
ns.sort((a, b) => {
const ia = ord ? ord.indexOf(a.value) : -1, ib = ord ? ord.indexOf(b.value) : -1;
if (ia !== -1 || ib !== -1) return (ia === -1 ? 99 : ia) - (ib === -1 ? 99 : ib);
return b.n - a.n;
});
return ns;
});
const pad = 7;
const maxTotal = Math.max(...cols.map((c) => c.reduce((s, n) => s + n.n, 0)));
const maxCount = Math.max(...cols.map((c) => c.length));
const scale = (H - top - bottom - pad * (maxCount - 1)) / maxTotal;
const pos = new Map();
cols.forEach((ns, i) => {
const hTot = ns.reduce((s, n) => s + Math.max(2, n.n * scale), 0) + pad * (ns.length - 1);
let y = top + (H - top - bottom - hTot) / 2;
ns.forEach((n) => { const h = Math.max(2, n.n * scale); pos.set(n.id, { x: colX(i), y, h, n }); y += h + pad; });
});
// colour scale: anchored on the route steps, not on the outcome column (where the target node is 100% by definition)
const lastStage = S - 1;
const stageOf = (id) => +id.split("|")[0];
const eligible = sel.links.filter((l) => l.n >= minN && stageOf(l.target) < lastStage);
const pmax = Math.max(0.005, ...eligible.map((l) => l.p), ...sel.nodes.filter((n) => n.n >= minN && n.stage < lastStage).map((n) => n.p));
const colorFor = (o) => (o.n < minN ? low : mix(low, tcol, Math.pow(Math.min(1, o.p / pmax), 0.75)));
// stage headers
E.STAGES.forEach((s, i) => {
const chance = s.key === "first_sighting" || s.key === "encounter";
const t = svgEl("text", { x: colX(i), y: 18, class: "stage-label" + (chance ? " stage-chance" : "") }, svg);
t.textContent = s.label;
if (chance) { const r = svgEl("text", { x: colX(i), y: 31, class: "stage-label stage-chance" }, svg); r.textContent = "game roll"; }
});
// links
const gLinks = svgEl("g", {}, svg);
const outOff = new Map(), inOff = new Map();
const linksSorted = sel.links.slice().sort((a, b) => pos.get(a.source).y - pos.get(b.source).y || pos.get(a.target).y - pos.get(b.target).y);
// order out-links by target y and in-links by source y for clean stacking
const byOut = {}, byIn = {};
linksSorted.forEach((l) => { (byOut[l.source] = byOut[l.source] || []).push(l); (byIn[l.target] = byIn[l.target] || []).push(l); });
Object.values(byOut).forEach((ls) => ls.sort((a, b) => pos.get(a.target).y - pos.get(b.target).y));
Object.values(byIn).forEach((ls) => ls.sort((a, b) => pos.get(a.source).y - pos.get(b.source).y));
const offOut = {}, offIn = {};
Object.entries(byOut).forEach(([id, ls]) => { let o = 0; ls.forEach((l) => { offOut[l.id] = o; o += l.n * scale; }); });
Object.entries(byIn).forEach(([id, ls]) => { let o = 0; ls.forEach((l) => { offIn[l.id] = o; o += l.n * scale; }); });
const drawOrder = state.widthMode === "prob" ? sel.links.slice().sort((a, b) => (a.n >= minN) - (b.n >= minN) || a.p - b.p) : linksSorted;
drawOrder.forEach((l) => {
const s = pos.get(l.source), t = pos.get(l.target);
if (!s || !t) return;
const x0 = s.x + nodeW, x1 = t.x, xm = (x0 + x1) / 2;
let el;
if (state.widthMode === "traffic") {
const w = Math.max(0.6, l.n * scale);
const y0 = s.y + offOut[l.id], y1 = t.y + offIn[l.id];
el = svgEl("path", {
d: `M${x0},${y0}C${xm},${y0} ${xm},${y1} ${x1},${y1}L${x1},${y1 + w}C${xm},${y1 + w} ${xm},${y0 + w} ${x0},${y0 + w}Z`,
fill: colorFor(l), "fill-opacity": l.n >= minN ? 0.62 : 0.3, class: "link",
}, gLinks);
} else {
const y0 = s.y + s.h / 2, y1 = t.y + t.h / 2;
const w = l.n >= minN ? 1.2 + 18 * (l.p / pmax) : 1;
el = svgEl("path", { d: `M${x0},${y0}C${xm},${y0} ${xm},${y1} ${x1},${y1}`, fill: "none", stroke: colorFor(l), "stroke-width": w, "stroke-opacity": l.n >= minN ? 0.8 : 0.3, "stroke-linecap": "round", class: "link" }, gLinks);
}
const sv = pos.get(l.source).n.value, tv = pos.get(l.target).n.value;
el.addEventListener("mousemove", (e) => showTip(e, `<div class="t">${esc(sv)} → ${esc(tv)}</div>${l.n} runs${hasSel ? " (in your selection)" : ""}<br>${esc(E.TARGETS[state.target].label)}: <b>${pct(l.p)}</b> (${kn(l)})<br>95% CI ${ci(l)}${l.n < minN ? "<br><i>Too few runs to read</i>" : ""}`));
el.addEventListener("mouseleave", hideTip);
});
// nodes
const gNodes = svgEl("g", {}, svg);
cols.forEach((ns, i) => {
let lastLabelBottom = -1e9;
ns.forEach((bn) => {
const p = pos.get(bn.id), sn = selNode.get(bn.id);
const isSel = (state.conds[E.STAGES[i].key] || []).includes(bn.value);
const g = svgEl("g", { class: "node" + (isSel ? " sel" : "") + (hasSel && !sn ? " dim" : ""), tabindex: 0, role: "button", "aria-label": `${E.STAGES[i].label}: ${bn.value}, ${bn.n} runs` }, gNodes);
const shown = sn || { n: 0, k: 0, p: null };
svgEl("rect", { x: p.x, y: p.y, width: nodeW, height: p.h, rx: 2, fill: sn ? colorFor(sn) : low }, g);
const lx = p.x + nodeW + 5, ly = p.y + p.h / 2 + 4;
if (ly - 11 > lastLabelBottom || isSel) {
const t = svgEl("text", { x: lx, y: ly, "paint-order": "stroke", stroke: surface, "stroke-width": 3, "stroke-linejoin": "round" }, g);
const lab = short(bn.value), maxC = i === S - 1 ? 30 : Math.floor((colX(1) - colX(0) - nodeW - 36) / 5.8);
t.textContent = lab.length > maxC ? lab.slice(0, maxC - 1) + "…" : lab;
const t2 = svgEl("tspan", { fill: cssVar("--muted"), dx: 4 }, t);
t2.textContent = sn && sn.n >= minN ? pct(sn.p, 0) : sn ? `n=${sn.n}` : "";
lastLabelBottom = ly;
}
const html = () => `<div class="t">${esc(E.STAGES[i].label)}: ${esc(bn.value)}</div>${hasSel ? `${shown.n} of ${bn.n} runs in your selection` : `${bn.n} runs`}<br>${esc(E.TARGETS[state.target].label)}: <b>${pct(shown.p)}</b> (${shown.k}/${shown.n})<br>95% CI ${ci(sn)}<br><span class="muted">Click to ${isSel ? "remove from" : "add to"} the selection</span>`;
g.addEventListener("mousemove", (e) => showTip(e, html()));
g.addEventListener("mouseleave", hideTip);
const toggle = () => {
const k = E.STAGES[i].key, cur = new Set(state.conds[k] || []);
cur.has(bn.value) ? cur.delete(bn.value) : cur.add(bn.value);
state.conds[k] = [...cur];
if (!state.conds[k].length) delete state.conds[k];
hideTip(); renderMap();
};
g.addEventListener("click", toggle);
g.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); toggle(); } });
});
});
renderCondChips(); renderSelSummary(sel); renderLegend(pmax, tcol, low);
}
function renderCondChips() {
const entries = Object.entries(state.conds).filter(([, v]) => v.length);
$("#cond-chips").innerHTML = entries.length
? entries.map(([k, vals]) => vals.map((v) => `<span class="cchip">${esc(E.STAGES.find((s) => s.key === k).label)}: ${esc(v)}<button type="button" aria-label="Remove ${esc(v)}" data-k="${esc(k)}" data-v="${esc(v)}">×</button></span>`).join("")).join("")
: `<span class="small muted">Showing all runs. Click a box to follow only the runs through it.</span>`;
$$("#cond-chips button").forEach((b) => b.addEventListener("click", () => {
state.conds[b.dataset.k] = (state.conds[b.dataset.k] || []).filter((v) => v !== b.dataset.v);
if (!state.conds[b.dataset.k].length) delete state.conds[b.dataset.k];
renderMap();
}));
}
function renderSelSummary(sel) {
const T = E.TARGETS[state.target];
const cs = condSets();
const inSel = (r) => Object.entries(cs).every(([k, set]) => !set.size || set.has(E.stageValue(r, k)));
const pool = state.runs.filter(T.pool);
const A = pool.filter(inSel), B = pool.filter((r) => !inSel(r));
const wa = E.wilson(A.filter(T.fn).length, A.length), wb = E.wilson(B.filter(T.fn).length, B.length);
const hasSel = Object.keys(state.conds).length > 0;
let cmp = "";
if (hasSel && A.length && B.length) {
const o = E.oddsRatio(wa.k, wa.n - wa.k, wb.k, wb.n - wb.k);
cmp = `<div>Everyone else: ${pct(wb.p)} (${kn(wb)}). Odds ratio ${fmtOR(o.or)} (95% CI ${fmtOR(o.or_lo)}–${fmtOR(o.or_hi)}), Fisher p = ${fmtP(o.fisher_p)}. This is unadjusted: if your selection mixes in a lot of Blue-chasers, expect it to look better than it is.</div>`;
}
$("#sel-summary").innerHTML = `
<span class="eyebrow">${hasSel ? "Your selection" : "All runs"} · ${esc(T.label)}</span>
<div><span class="big">${pct(wa.p)}</span> <span class="muted">${kn(wa)} runs that could reach it · 95% CI ${ci(wa)}</span></div>
${cmp}`;
}
function renderLegend(pmax, tcol, low) {
$("#legend").innerHTML = `
<span>${state.widthMode === "traffic" ? "Band width = number of runs" : "Line width = chance of the outcome"}</span>
<span style="display:inline-flex;gap:6px;align-items:center">0% <span class="ramp" style="background:linear-gradient(90deg, ${low}, ${tcol})"></span> ${pct(pmax, 0)}</span>
<span>Grey = fewer than ${state.minN} runs</span>
<span><span style="color:var(--accent)">Gold headings</span> = steps the game rolls, not you</span>`;
}
function renderBestRoutes() {
const rk = E.rankRoutes(state.runs, state.target, state.minN);
const rows = rk.rows.slice(0, 8);
const sigN = rk.rows.filter((r) => r.mh_q !== undefined && r.mh_q < 0.05 && r.mh_or > 1).length;
$("#best-routes").innerHTML = `<div class="panel">
<h3>Top routes for "${esc(E.TARGETS[state.target].label)}" <span class="small muted">routes with ≥ ${state.minN} runs, ranked by the lower end of the 95% interval</span></h3>
<p class="small">${rows.length ? `Overall rate in the comparison group: ${rateTxt(rk.overall)}. <b>${sigN} of ${rk.n_routes_tested} routes are better than the rest after adjusting for reporting bias and multiple testing.</b> ${sigN === 0 ? "Treat the ordering below as noise unless a newer export changes this." : ""}` : "No route has enough runs at this threshold. Lower the minimum."}</p>
${rows.length ? `<div class="tbl-wrap"><table><thead><tr><th>Route (choices up to the hour)</th><th class="num">Runs</th><th class="num">Rate</th><th class="num">95% CI</th><th class="num">Adj. OR</th><th class="num">Adj. q</th><th></th></tr></thead><tbody>
${rows.map((r, i) => `<tr class="${r.mh_q < 0.05 && r.mh_or > 1 ? "sig" : ""}"><td class="route-cell">${esc(r.route)}</td><td class="num">${r.n}</td><td class="num">${pct(r.p)}</td><td class="num">${ci(r)}</td><td class="num">${fmtOR(r.mh_or)}</td><td class="num">${fmtP(r.mh_q)}</td><td><button type="button" data-i="${i}">Follow</button></td></tr>`).join("")}
</tbody></table></div>` : ""}</div>`;
$$("#best-routes button[data-i]").forEach((b) => b.addEventListener("click", () => {
const r = rows[+b.dataset.i];
state.conds = {};
E.STAGES.slice(0, 6).forEach((s, i) => { if (r.values[i]) state.conds[s.key] = [r.values[i]]; });
renderMap();
$("#map-sec").scrollIntoView({ behavior: "smooth" });
}));
}
// ------------------------------------------------------------ small charts
// Horizontal rate bars with 95% CI whiskers.
function ciBars(el, rows, opts = {}) {
const W = 640, rowH = opts.rowH || 26, lw = opts.labelW || 190, top = 8, bottom = 26;
const H = top + bottom + rows.length * rowH;
const xmax = opts.max || Math.min(1, Math.max(0.05, ...rows.map((r) => r.hi || 0)) * 1.08);
const x = (v) => lw + (v / xmax) * (W - lw - 120);
const svg = svgEl("svg", { viewBox: `0 0 ${W} ${H}`, width: W, height: H, role: "img" });
const ticks = niceTicks(xmax);
const ga = svgEl("g", { class: "axis" }, svg);
ticks.forEach((t) => {
svgEl("line", { x1: x(t), x2: x(t), y1: top, y2: H - bottom + 4 }, ga);
const tx = svgEl("text", { x: x(t), y: H - 8, "text-anchor": "middle" }, ga); tx.textContent = pct(t, 0);
});
rows.forEach((r, i) => {
const y = top + i * rowH + rowH / 2;
const lab = svgEl("text", { x: lw - 8, y: y + 4, "text-anchor": "end" }, svg); lab.textContent = r.label;
if (r.indent) lab.setAttribute("fill", cssVar("--muted"));
if (!r.n) { const t = svgEl("text", { x: lw, y: y + 4, fill: cssVar("--faint") }, svg); t.textContent = "no runs"; return; }
const col = r.color || cssVar("--muted");
svgEl("rect", { x: lw, y: y - 7, width: Math.max(1, x(r.p) - lw), height: 14, fill: col, "fill-opacity": 0.28, rx: 2 }, svg);
svgEl("line", { x1: x(r.lo), x2: x(r.hi), y1: y, y2: y, stroke: col, "stroke-width": 2 }, svg);
svgEl("line", { x1: x(r.lo), x2: x(r.lo), y1: y - 5, y2: y + 5, stroke: col, "stroke-width": 2 }, svg);
svgEl("line", { x1: x(r.hi), x2: x(r.hi), y1: y - 5, y2: y + 5, stroke: col, "stroke-width": 2 }, svg);
svgEl("circle", { cx: x(r.p), cy: y, r: 4, fill: col }, svg);
const v = svgEl("text", { x: x(r.hi) + 6, y: y + 4, "font-family": "var(--font-data)" }, svg);
v.textContent = `${pct(r.p)} · ${r.k}/${r.n}`;
});
el.innerHTML = ""; el.appendChild(svg);
}
function niceTicks(max) {
const steps = [0.01, 0.02, 0.05, 0.1, 0.2, 0.25];
const step = steps.find((s) => max / s <= 6) || 0.25;
const out = []; for (let v = 0; v <= max + 1e-9; v += step) out.push(+v.toFixed(4)); return out;
}
// Forest plot of odds ratios on a log axis.
function forest(el, terms, opts = {}) {
const W = 640, rowH = 22, lw = opts.labelW || 290, top = 8, bottom = 28;
const H = top + bottom + Math.max(1, terms.length) * rowH;
const lo = 0.05, hi = 20;
const x = (v) => lw + ((Math.log(Math.min(hi, Math.max(lo, v))) - Math.log(lo)) / (Math.log(hi) - Math.log(lo))) * (W - lw - 60);
const svg = svgEl("svg", { viewBox: `0 0 ${W} ${H}`, width: W, height: H, role: "img" });
const ga = svgEl("g", { class: "axis" }, svg);
[0.1, 0.25, 0.5, 1, 2, 4, 10].forEach((t) => {
svgEl("line", { x1: x(t), x2: x(t), y1: top, y2: H - bottom + 4, "stroke-dasharray": t === 1 ? "" : "2 3", "stroke-width": t === 1 ? 1.5 : 1 }, ga);
const tx = svgEl("text", { x: x(t), y: H - 10, "text-anchor": "middle" }, ga); tx.textContent = t;
});
terms.forEach((t, i) => {
const y = top + i * rowH + rowH / 2;
const sig = t.p !== undefined ? t.p < 0.05 : t.q < 0.05;
const col = sig ? cssVar("--accent") : cssVar("--muted");
const lab = svgEl("text", { x: lw - 8, y: y + 4, "text-anchor": "end" }, svg);
lab.textContent = (t.label.length > 40 ? t.label.slice(0, 39) + "…" : t.label) + (t.n !== undefined ? ` (n=${t.n})` : "");
svgEl("line", { x1: x(t.lo), x2: x(t.hi), y1: y, y2: y, stroke: col, "stroke-width": 2 }, svg);
svgEl("rect", { x: x(t.or) - 4, y: y - 4, width: 8, height: 8, fill: col }, svg);
const v = svgEl("text", { x: W - 4, y: y + 4, "text-anchor": "end", "font-family": "var(--font-data)", fill: cssVar("--muted") }, svg);
v.textContent = fmtOR(t.or);
});
el.innerHTML = ""; el.appendChild(svg);
}
// ------------------------------------------------------------ rare section
const STRATUM_ORDER = ["Bulk logs (imports)", "Form: other/blank goal", "Form: chasing Black", "Form: chasing Blue"];
function renderRare() {
const r = state.res;
const blueCol = dragonColor("Blue"), blackCol = dragonColor("Black");
const strataRows = (c, col) => [{ label: "All rows", ...c.overall, color: cssVar("--ink") }].concat(
STRATUM_ORDER.filter((s) => c.by_stratum[s]).map((s) => ({ label: s, ...c.by_stratum[s], color: col })),
Object.entries(c.by_attempt).filter(([k]) => k !== "Unknown/lost count").map(([k, w]) => ({ label: k, ...w, color: cssVar("--accent") })));
ciBars($("#ch-blue-strata"), strataRows(r.chance.blue_meadow, blueCol), { labelW: 180 });
ciBars($("#ch-shadow-strata"), strataRows(r.chance.shadow, blackCol), { labelW: 180 });
const termsOf = (m, skip = []) => (m ? m.terms.filter((t) => t.n >= 5 && !skip.includes(t.factor)).map((t) => ({ label: `${labelFactor(t.factor)}: ${t.level}`, or: t.or, lo: t.lo, hi: t.hi, p: t.p, n: t.n })) : []);
const mb = r.models.blue_meadow, ms = r.models.shadow;
forest($("#ch-model-blue"), termsOf(mb));
forest($("#ch-model-shadow"), termsOf(ms));
const refTxt = (m) => (m ? `Reference answers: ${Object.entries(m.refs).map(([f, v]) => `${labelFactor(f)} = ${v}`).join(", ")}. n = ${m.n}, events = ${m.events}. Gold = p < 0.05 (not corrected for the number of terms).` : "Not enough data.");
$("#model-blue-note").textContent = refTxt(mb);
$("#model-shadow-note").textContent = refTxt(ms);
renderDaily();
const enc = r.encounters.filter((e) => ["Blue (meadow)", "Blue (shadow)", "Black (shadow)"].includes(e.context));
ciBars($("#ch-rare-bond"), enc.flatMap((e) => [
{ label: e.context, ...e.overall, color: dragonColor(e.color) },
{ label: "↳ players who wanted it", ...e.intent_matched, color: dragonColor(e.color), indent: true }]), { labelW: 200, max: 1 });
renderPdfSteps();
}
function renderDaily() {
const d = state.res.daily.filter((x) => x.meadow_n + x.tree_n > 0);
const el = $("#ch-daily");
if (!d.length) { el.textContent = "No dated runs in the current filter."; return; }
const W = 640, H = 250, l = 44, rgt = 24, top = 16, mid = 125, bottom = 30;
const svg = svgEl("svg", { viewBox: `0 0 ${W} ${H}`, width: W, height: H, role: "img" });
const x = (i) => l + (d.length === 1 ? (W - l - rgt) / 2 : (i * (W - l - rgt)) / (d.length - 1));
const panels = [
{ y0: top, y1: mid - 14, k: "blue_k", n: "meadow_n", col: dragonColor("Blue"), name: "Blue in meadow" },
{ y0: mid + 6, y1: H - bottom, k: "shadow_k", n: "tree_n", col: dragonColor("Black"), name: "Shadow at tree" },
];
panels.forEach((P) => {
const vals = d.map((r) => E.wilson(r[P.k], r[P.n]));
const ymax = Math.min(1, Math.max(0.05, ...vals.filter((v) => v.n >= 5).map((v) => v.hi)));
const y = (v) => P.y1 - (v / ymax) * (P.y1 - P.y0);
const ga = svgEl("g", { class: "axis" }, svg);
[0, ymax / 2, ymax].forEach((t) => { svgEl("line", { x1: l, x2: W - rgt, y1: y(t), y2: y(t) }, ga); const tx = svgEl("text", { x: l - 6, y: y(t) + 3, "text-anchor": "end" }, ga); tx.textContent = pct(t, 0); });
const nm = svgEl("text", { x: l + 4, y: P.y0 + 10, fill: P.col, "font-weight": 600 }, svg); nm.textContent = P.name;
const yc = (v) => y(Math.min(ymax, v));
vals.forEach((v, i) => {
if (v.n < 3) return;
svgEl("line", { x1: x(i), x2: x(i), y1: yc(v.lo), y2: yc(v.hi), stroke: P.col, "stroke-opacity": 0.45, "stroke-width": 1.5 }, svg);
const c = svgEl("circle", { cx: x(i), cy: yc(v.p), r: 2 + Math.sqrt(v.n) / 2.2, fill: P.col, "fill-opacity": 0.85 }, svg);
c.addEventListener("mousemove", (e) => showTip(e, `<div class="t">${d[i].date} · ${P.name}</div>${pct(v.p)} (${kn(v)})<br>95% CI ${ci(v)}`));
c.addEventListener("mouseleave", hideTip);
});
});
const ga = svgEl("g", { class: "axis" }, svg);
d.forEach((r, i) => { if (i % Math.ceil(d.length / 8) === 0 || i === d.length - 1) { const t = svgEl("text", { x: x(i), y: H - 10, "text-anchor": "middle" }, ga); t.textContent = r.date.slice(5); } });
el.innerHTML = ""; el.appendChild(svg);
}
function renderPdfSteps() {
const blue = [["Approach the Blue: “Absolutely…”", "90%"], ["Hold the Blue's glare and advance", "80%"], ["Do nothing (it seizes the other cadet)", "82%"], ["Hold glare and watch", "84%"], ["Straighten your spine", "83%"], ["Launch yourself right (boulder)", "93%"], ["“Bring down an empire”", "81%"], ["Move slowly forward, wait for an invitation", "81%"]];
const prod = [0.9, 0.8, 0.82, 0.84, 0.83, 0.93, 0.81, 0.81].reduce((a, b) => a * b, 1);
$("#pdf-steps").innerHTML = `<p class="small muted">As published in the community PDF (u/ClumsyBadger, u/Old_Regular3018). These come from hand-coded free-text answers. The underlying counts are not shown there, and many cells rest on fewer than 10 runs.</p>
<div class="tbl-wrap"><table><thead><tr><th>Meadow Blue, standard answers</th><th class="num">Survived step</th></tr></thead><tbody>${blue.map(([a, b]) => `<tr><td>${a}</td><td class="num">${b}</td></tr>`).join("")}
<tr><td><b>All eight steps (product)</b></td><td class="num"><b>${pct(prod, 0)}</b></td></tr></tbody></table></div>
<p class="small">The product, about ${pct(prod, 0)}, agrees with the form's own Blue bond rate (${rateTxt(state.res.encounters.find((e) => e.context === "Blue (meadow)").overall)}), which is a useful cross-check.</p>
<div class="tbl-wrap"><table><thead><tr><th>Black (after the shadow and the tree Blue)</th><th class="num">PDF outcome</th></tr></thead><tbody>
<tr><td>Turn to face the threat → hold its gaze</td><td class="num">66% bonded · 33% incinerated</td></tr>
<tr><td>Turn to face the threat → lower your eyes → try to mount → meet its gaze</td><td class="num">100% bonded (very few runs)</td></tr></tbody></table></div>`;
}
// ------------------------------------------------------------ every dragon
function renderDragons() {
const r = state.res;
const order = ["Red (valley)", "Red (tree, descend quickly)", "Green (two Greens)", "Orange (meadow)", "Brown (meadow)", "Blue (meadow)", "Blue (shadow)", "Black (shadow)"];
const rows = order.map((c) => r.encounters.find((e) => e.context === c)).filter(Boolean).flatMap((e) => [
{ label: `${e.context}`, ...e.overall, color: dragonColor(e.color) },
{ label: "↳ players who wanted it", ...e.intent_matched, color: dragonColor(e.color), indent: true }]);
const box = $("#ch-encounters");
box.innerHTML = `<h3>Bond rate once the encounter starts</h3><div class="chart" id="ch-enc-inner"></div>`;
ciBars($("#ch-enc-inner"), rows, { labelW: 220, max: 1, rowH: 22 });
const g = r.green_rescue;
const parts = [["Bonded a Green", g.bonded_green, dragonColor("Green")], ["Rescued, bonded the Orange", g.rescued_orange, dragonColor("Orange")], ["Rescued, bonded the Brown", g.rescued_brown, dragonColor("Brown")], ["Incinerated", g.incinerated, cssVar("--faint")], ["No outcome recorded", g.green_encounters - g.bonded_green - g.rescued_orange - g.rescued_brown - g.incinerated, cssVar("--line")]];
const tot = g.green_encounters || 1;
$("#green-rescue").innerHTML = `<p class="small muted">${g.green_encounters} tree runs that descended slowly to the two Greens. A wrong answer sometimes brings an Orange or Brown swooping in to bond you instead.</p>
<div style="display:flex;height:16px;border-radius:3px;overflow:hidden;border:1px solid var(--line)">${parts.map(([, n, c]) => `<span style="width:${(100 * n) / tot}%;background:${c}"></span>`).join("")}</div>
<div class="tbl-wrap"><table><tbody>${parts.map(([l, n, c]) => { const w = E.wilson(n, g.green_encounters); return `<tr><td><span style="display:inline-block;width:10px;height:10px;border-radius:2px;background:${c};margin-right:6px"></span>${l}</td><td class="num">${n}</td><td class="num">${pct(w.p)}</td><td class="num">${ci(w)}</td></tr>`; }).join("")}</tbody></table></div>`;
const cols = ["Red", "Orange", "Brown", "Green", "Unsure", "Unknown"];
const POOL = { "Alone|East": ["Red", "Orange"], "Alone|West": ["Red", "Brown", "Green"], "Alone|Center": ["Red", "Brown"], "1 Squadmate|East": ["Green", "Orange", "Red"], "1 Squadmate|West": ["Red", "Brown", "Green"], "1 Squadmate|Center": ["Red", "Brown"], "2 Squadmates|East": ["Red", "Orange"], "2 Squadmates|West": ["Green", "Brown", "Red"], "2 Squadmates|Center": ["Red", "Brown"] };
$("#tbl-first").innerHTML = `<table><thead><tr><th>Company · direction</th>${cols.map((c) => `<th class="num">${c}</th>`).join("")}<th class="num">Runs</th></tr></thead><tbody>${r.first_sighting.filter((x) => x.n >= 3).map((x) => `<tr><td>${esc(x.key.replace("|", " · "))}</td>${cols.map((c) => { const n = x.colors[c] || 0; const off = n && POOL[x.key] && !["Unsure", "Unknown"].includes(c) && !POOL[x.key].includes(c); return `<td class="num" style="${off ? "color:var(--warn);font-weight:600" : n ? "" : "color:var(--faint)"}" title="${off ? "Outside the documented pool" : ""}">${n ? `${n}<span class="muted"> · ${pct(n / x.n, 0)}</span>` : "·"}</td>`; }).join("")}<td class="num">${x.n}</td></tr>`).join("")}</tbody></table>`;
}
// ------------------------------------------------------------ route table
function renderRouteTable() {
const sel = $("#rt-target");
if (!sel.options.length) {
sel.innerHTML = Object.entries(E.TARGETS).map(([k, t]) => `<option value="${k}">${esc(t.label)}</option>`).join("");
sel.value = state.rtTarget;
sel.addEventListener("change", () => { state.rtTarget = sel.value; renderRouteTable(); });
$("#rt-min").addEventListener("change", (e) => { state.rtMin = Math.max(1, +e.target.value || 10); renderRouteTable(); renderFindings(); });
}
const rk = E.rankRoutes(state.runs, state.rtTarget, state.rtMin);
const sig = rk.rows.filter((x) => x.mh_q < 0.05 && x.mh_or > 1).length;
$("#rt-note").innerHTML = `${rk.n_routes_tested} routes tested · comparison group ${rateTxt(rk.overall)} · <b>${sig}</b> clearly better after adjustment`;
const bar = (w) => `<span class="cibar" aria-hidden="true"><i style="left:${w.lo * 90}px;width:${Math.max(1, (w.hi - w.lo) * 90)}px"></i><b style="left:${w.p * 90 - 1}px"></b></span>`;
$("#tbl-routes").innerHTML = rk.rows.length ? `<table><thead><tr><th>#</th><th>Route (choices up to the hour)</th><th class="num">Runs</th><th class="num">Hits</th><th class="num">Rate</th><th class="num">95% CI</th><th></th><th class="num">Crude OR</th><th class="num">q</th><th class="num">Adj. OR</th><th class="num">Adj. q</th></tr></thead><tbody>
${rk.rows.map((r, i) => `<tr class="${r.mh_q < 0.05 && r.mh_or > 1 ? "sig" : ""}${r.n < 20 ? " thin" : ""}"><td class="num">${i + 1}</td><td class="route-cell">${esc(r.route)}</td><td class="num">${r.n}</td><td class="num">${r.k}</td><td class="num">${pct(r.p)}</td><td class="num">${ci(r)}</td><td>${bar(r)}</td><td class="num">${fmtOR(r.or)}</td><td class="num">${fmtP(r.q)}</td><td class="num">${fmtOR(r.mh_or)}</td><td class="num">${fmtP(r.mh_q)}</td></tr>`).join("")}
</tbody></table>` : `<p class="small muted" style="padding:12px">No routes reach the minimum. Lower it.</p>`;
}
// ------------------------------------------------------------ factor explorer
function renderFactors() {
const so = $("#fx-outcome"), sf = $("#fx-factor");
if (!so.options.length) {
so.innerHTML = Object.entries(E.OUTCOMES).map(([k, o]) => `<option value="${k}">${esc(o.label)}</option>`).join("");
sf.innerHTML = E.FACTORS.map((f) => `<option value="${f}">${esc(labelFactor(f))}</option>`).join("");
so.value = state.fxOutcome; sf.value = state.fxFactor;
so.addEventListener("change", () => { state.fxOutcome = so.value; renderFactors(); });
sf.addEventListener("change", () => { state.fxFactor = sf.value; renderFactors(); });
}
const ft = state.res.factors[state.fxOutcome];
const rows = ft.rows.filter((r) => r.factor === state.fxFactor);
$("#tbl-factors").innerHTML = `<table><thead><tr><th>${esc(labelFactor(state.fxFactor))}</th><th class="num">Hits/runs</th><th class="num">Rate</th><th class="num">95% CI</th><th class="num">OR vs rest</th><th class="num">p</th><th class="num">q</th></tr></thead><tbody>
<tr><td><i>All</i></td><td class="num">${kn(ft.overall)}</td><td class="num">${pct(ft.overall.p)}</td><td class="num">${ci(ft.overall)}</td><td></td><td></td><td></td></tr>
${rows.map((r) => `<tr class="${r.q < 0.05 ? "sig" : ""}${r.or === undefined ? " thin" : ""}"><td>${esc(r.level)}</td><td class="num">${kn(r)}</td><td class="num">${pct(r.p)}</td><td class="num">${ci(r)}</td><td class="num">${r.or !== undefined ? `${fmtOR(r.or)} <span class="muted">(${fmtOR(r.or_lo)}–${fmtOR(r.or_hi)})</span>` : "too few"}</td><td class="num">${fmtP(r.fisher_p)}</td><td class="num">${r.q !== undefined ? `<span class="qbadge${r.q < 0.05 ? " s" : ""}">${fmtP(r.q)}</span>` : ""}</td></tr>`).join("")}
</tbody></table>`;
forest($("#ch-factor"), rows.filter((r) => r.or !== undefined).map((r) => ({ label: r.level, or: r.or, lo: r.or_lo, hi: r.or_hi, q: r.q, p: undefined, n: r.n })), { labelW: 220 });
}
// ------------------------------------------------------------ quality
function renderQuality() {
const r = state.res, m = r.meta;
const flags = Object.entries(m.flag_counts).sort((a, b) => b[1] - a[1]);
const outs = Object.entries(m.outcomes).sort((a, b) => b[1] - a[1]);
$("#quality-panels").innerHTML = `
<div class="panel"><h3>Who logged the runs</h3><div class="tbl-wrap"><table><thead><tr><th>Source</th><th class="num">Runs</th><th class="num">Blue in meadow</th><th class="num">Shadow at tree</th></tr></thead><tbody>
${Object.entries(m.sources).sort((a, b) => b[1] - a[1]).map(([s, n]) => { const b = sourceRate("blue_meadow", s), t = sourceRate("shadow", s); return `<tr><td>${esc(s)}</td><td class="num">${n}</td><td class="num">${pct(b.p)} <span class="muted">${kn(b)}</span></td><td class="num">${pct(t.p)} <span class="muted">${kn(t)}</span></td></tr>`; }).join("")}
</tbody></table></div><p class="small">Bulk logs come from players who recorded every run, so they are the least selective rows. Their rare-dragon rates are several times lower than the form's, which is the strongest sign of reporting bias in this data.</p></div>
<div class="panel"><h3>Rows flagged for contradictions</h3><p class="small muted">${m.n_flagged} of ${r.n} rows (${pct(m.n_flagged / r.n)}). Flagged rows stay in unless you drop them above.</p><div class="tbl-wrap"><table><tbody>${flags.map(([f, n]) => `<tr><td>${esc(f)}</td><td class="num">${n}</td></tr>`).join("") || `<tr><td>None</td></tr>`}</tbody></table></div></div>
<div class="panel"><h3>How runs ended</h3><div class="tbl-wrap"><table><tbody>${outs.map(([f, n]) => `<tr><td>${esc(f)}</td><td class="num">${n}</td><td class="num">${pct(n / r.n)}</td></tr>`).join("")}</tbody></table></div><p class="small muted">"No outcome recorded" rows reached the hour but the form shows no Bonded or Incinerated. They count toward reaching a branch but not toward bond rates.</p></div>
<div class="panel"><h3>Independence</h3><p class="small">The form has no player ID. One player's 50 runs count as 50 independent runs, so intervals are somewhat narrower than they should be. ${pct((r.n - (m.sources["Form"] || 0)) / r.n, 0)} of rows arrived as bulk imports, each probably one player's or one group's log.</p></div>
<div class="panel"><h3>What the form does not ask</h3><p class="small">How you reacted to the first dragon, whether you assessed or charged the bullies (asked only on later forms: ${r.factors.reach_hour.rows.filter((x) => x.factor === "combat_first" && x.level !== "(not recorded)").reduce((a, x) => a + x.n, 0)} rows), and most choices inside encounters. Theories that rely on those choices cannot be confirmed or refuted here.</p></div>`;
}
function sourceRate(outKey, source) {
const O = E.OUTCOMES[outKey];
const D = state.runs.filter((r) => r.source === source).filter(O.denom);
return E.wilson(D.filter(O.event).length, D.length);
}
// ------------------------------------------------------------ share
function redditPost() {
const r = state.res, cb = r.chance.blue_meadow, cs = r.chance.shadow;
const bulkB = stratumRate(cb, "Bulk"), chaseB = stratumRate(cb, "Form: chasing Blue"), bulkS = stratumRate(cs, "Bulk");
const encB = r.encounters.find((e) => e.context === "Blue (meadow)"), encK = r.encounters.find((e) => e.context === "Black (shadow)");
const mb = r.models.blue_meadow;
const sigRoute = mb ? mb.terms.filter((t) => ROUTE_FACTORS.includes(t.factor) && t.p < 0.05 && !NOT_A_CHOICE.test(t.level)) : [];
const rk = E.rankRoutes(state.runs, "see_Blue", state.rtMin);
const adjSig = rk.rows.filter((x) => x.mh_q < 0.05 && x.mh_or > 1).length;
const leads = r.factors.shadow.rows.filter((x) => ["post_path", "attempt_group"].includes(x.factor) && x.q < 0.05 && x.or > 1 && !NOT_A_CHOICE.test(x.level));
const L = [];
L.push(`# I ran the numbers on ${r.n.toLocaleString()} logged threshing runs. Here's what holds up (and what doesn't)`);
L.push("");
L.push(`*Per the megathread rules, anything that names a specific route is behind spoiler tags.*`);
L.push("");
L.push(`Data: the community Threshing Routes form/spreadsheet (thanks u/ClumsyBadger, u/Old_Regular3018, u/Smart_Trifle_2099 and everyone who logged runs). ${Object.entries(r.meta.sources).map(([k, v]) => `${v} ${k === "Form" ? "form submissions" : k}`).join(", ")}; form dates ${r.meta.date_min} to ${r.meta.date_max}. Every rate below has a 95% confidence interval.`);
L.push("");
L.push(`**TL;DR**`);
L.push("");
L.push(`* **The meadow Blue shows up a lot less than the spreadsheet suggests.** Runs logged by Blue-chasers show it ${pct(chaseB && chaseB.p)} of the time, but bulk logs (people who recorded *every* run) show ${bulkB ? `${pct(bulkB.p)} (${kn(bulkB)})` : "n/a"}. The game can't know what you're chasing, so that gap is reporting bias. Expect something closer to the bulk-log number.`);
L.push(`* **${sigRoute.length ? "Only these route choices mattered for the Blue appearing" : "No recorded route choice changed the Blue's odds"}** once you account for that bias${sigRoute.length ? `: ${sigRoute.map((s) => s.term).join("; ")}` : ""} (direction, first dragon, how you handled the cadet, company). ${adjSig} of ${rk.n_routes_tested} full routes beat the rest after correcting for multiple testing. The "precise pathways" might still matter through choices the form doesn't record (like how you react to the first dragon), but the form can't confirm them.`);
L.push(`* **Getting the Blue to show up is only half of it.** Only ${encB ? `${pct(encB.overall.p)} (${kn(encB.overall)})` : "n/a"} of Blue attempts bonded, which matches the PDF's step-by-step numbers (~25%). Dying with the "right" answer is normal.`);
L.push(`* **The tree shadow (→ Black) is rarer than the spreadsheet suggests.** All rows: ${pct(cs.overall.p)} (${kn(cs.overall)}), but bulk logs show ${bulkS ? `${kn(bulkS)} (upper 95% bound ${pct(bulkS.hi)})` : "n/a"}. ${bulkS && bulkS.n ? `Plan on roughly 1 in ${Math.round(1 / Math.max(bulkS.hi, 0.001) / 10) * 10} climbs at best.` : ""} Once you get the Black, it bonds ${encK ? `${pct(encK.overall.p)} (${kn(encK.overall)})` : "n/a"} of the time.`);
if (leads.length) L.push(`* **Leads worth testing (not proven):** >!${leads.map((x) => `${labelFactor(x.factor)} = ${x.level}: shadow in ${pct(x.p)} (${kn(x)}) vs the rest`).join("; ")}!<. If you bulk-log your tree climbs *including the boring ones*, we can settle this.`);
L.push("");
L.push(`**How to help:** log every run in the form, including the ones where nothing rare happened. Those dull runs are what make the rates trustworthy.`);
L.push("");
L.push(`Interactive route map, full methods, and code to reproduce every number: [Threshing Route Atlas](LINK)`);
L.push("");
L.push(`*Caveats: self-reported data, no player IDs (so runs from one person aren't independent), and the form doesn't record every in-game choice. The author has said there's a ~10% chaos roll, so nothing is guaranteed.*`);
return L.join("\n");
}
function runsCSV() {
const cols = Object.keys(state.runs[0] || {});
const q = (v) => { if (v === null || v === undefined) return ""; const s = String(v); return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; };
return [cols.join(","), ...state.runs.map((r) => cols.map((c) => q(r[c])).join(","))].join("\n");
}
$("#cp-reddit").addEventListener("click", () => copyText(redditPost(), "Reddit post"));
$("#cp-csv").addEventListener("click", () => copyText(runsCSV(), `${state.runs.length} coded runs`));
$("#cp-json").addEventListener("click", () => copyText(JSON.stringify(state.res, null, 1), "results JSON"));
$$("button[data-src]").forEach((b) => b.addEventListener("click", async () => {
const pre = $("#srcview");
try { const t = await (await fetch(b.dataset.src)).text(); pre.textContent = t; pre.hidden = false; pre.scrollTop = 0; }
catch (e) { pre.textContent = "Could not load " + b.dataset.src; pre.hidden = false; }
}));
// ------------------------------------------------------------ controls
$$("#width-mode button").forEach((b) => b.addEventListener("click", () => {
state.widthMode = b.dataset.v;
$$("#width-mode button").forEach((x) => x.setAttribute("aria-pressed", x === b));
renderMap();
}));
$("#minn").addEventListener("change", (e) => { state.minN = Math.max(1, +e.target.value || 10); renderMap(); });
$("#f-source").addEventListener("change", (e) => { state.filters.source = e.target.value; recompute(); });
$("#f-goal").addEventListener("change", (e) => { state.filters.goal = e.target.value; recompute(); });
$("#f-flag").addEventListener("change", (e) => { state.filters.excludeFlagged = e.target.checked; recompute(); });
$("#btn-clear").addEventListener("click", () => { state.conds = {}; renderMap(); $("#best-routes").innerHTML = ""; });
$("#btn-best").addEventListener("click", renderBestRoutes);
function renderAll() {
renderStatus(); renderFindings(); renderTargets(); renderMap(); renderRare(); renderDragons(); renderRouteTable(); renderFactors(); renderQuality();
if ($("#best-routes").innerHTML) renderBestRoutes();
if (window.AtlasUI) window.AtlasUI.render(state);
}
// re-colour when the theme changes
const mq = window.matchMedia("(prefers-color-scheme: dark)");
const rerender = () => state.res && renderAll();
mq.addEventListener && mq.addEventListener("change", rerender);
new MutationObserver(rerender).observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
let rz; window.addEventListener("resize", () => { clearTimeout(rz); rz = setTimeout(() => state.res && renderMap(), 200); });
window.ThreshAtlas = { state, redditPost, runsCSV };
if (window.DragonRegister) window.DragonRegister.mount({ copy: copyText, toast });
loadBundled().catch((e) => { $("#data-status").innerHTML = `<span class="pill warn">The bundled data could not load (${esc(e.message)}). Use "Load a newer export" to load the responses file.</span>`; console.error(e); });
})();
+592
View File
@@ -0,0 +1,592 @@
<title>Threshing Route Atlas</title>
<meta name="claude:viewport-fit-sides" content="cover">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Marcellus&family=Josefin+Sans:wght@400;600&family=Alegreya+Sans:ital,wght@0,400;0,500;0,700;1,400&family=IBM+Plex+Mono:wght@400;500&display=swap">
<style>
/* Layout: a field atlas — one wide route chart flanked by narrow reading columns; numbers set in mono, dragons carry their own colours. */
/* Layout: a dusk-lit field atlas — arched, deco-framed panels on deep plum; gold line work; each dragon tints its own frame; deaths turn steel and ember. Single dark world by design. */
:root {
color-scheme: dark;
--bg: #170911; --surface: #210f19; --raised: #2a1420; --ink: #f6e8d6; --muted: #cba890; --faint: #8e7069; --line: #4b2a36;
--accent: #e8b483; --accent-ink: #1d0a12; --good: #8fc98a; --warn: #f0a55a; --bad: #ef6b6b;
--dr-red: #e4566d; --dr-green: #84c27c; --dr-orange: #f29a4c; --dr-brown: #c8976b; --dr-blue: #82a8f2; --dr-black: #b9abd3; --dr-any: #e0a9c6;
--link-low: #4f2f3c; --death: #9fb6c3; --ember: #e3692f; --death-bg: #1b0811; --frame: var(--accent);
--font-display: "Marcellus", "Iowan Old Style", Georgia, serif;
--font-crest: "Marcellus", "Iowan Old Style", Georgia, serif;
--font-label: "Josefin Sans", "Gill Sans", "Trebuchet MS", sans-serif;
--font-body: "Alegreya Sans", "Segoe UI", system-ui, sans-serif;
--font-data: "IBM Plex Mono", ui-monospace, "SFMono-Regular", Menlo, monospace;
--hero-bg: #1a0912; --hero-bg2: #3a1526; --hero-ink: #f6e8d6; --hero-muted: #d2b096; --hero-line: #6b4148;
--map-ground: #2a1420; --map-ground2: #34192a; --map-forest: #4b2b3b; --map-forest2: #3b2030; --map-rock: #5e3d4a; --map-water: #6f90a5; --map-path: #e8b483; --map-label: #f6e8d6; --map-halo: #1c0a13;
--step--1: 0.84rem; --step-0: 1rem; --step-1: 1.18rem; --step-2: 1.6rem; --step-3: 2.3rem; --radius: 10px;
}
* { box-sizing: border-box; }
body { background: var(--bg); color: var(--ink); font-family: var(--font-body); font-size: var(--step-0); line-height: 1.55; }
.wrap { max-width: 1260px; margin: 0 auto; padding-left: max(16px, env(safe-area-inset-left, 0px)); padding-right: max(16px, env(safe-area-inset-right, 0px)); padding-block: 0; }
h1, h2, h3 { font-family: var(--font-display); font-weight: 650; line-height: 1.15; text-wrap: balance; margin: 0; }
h1 { font-size: var(--step-3); letter-spacing: -0.01em; }
h2 { font-size: var(--step-2); }
h3 { font-size: var(--step-1); font-family: var(--font-body); font-weight: 600; }
p { margin: 0; max-width: 68ch; }
a { color: var(--accent); }
code, .num, .mono { font-family: var(--font-data); font-variant-numeric: tabular-nums; }
.eyebrow { font-family: var(--font-data); font-size: var(--step--1); letter-spacing: 0.08em; text-transform: uppercase; color: var(--muted); }
.muted { color: var(--muted); }
.small { font-size: var(--step--1); }
header.top { border-bottom: 1px solid var(--line); background: var(--surface); }
header.top .wrap { display: grid; gap: 14px; padding-block: 28px 22px; }
.title-row { display: flex; flex-wrap: wrap; align-items: flex-end; justify-content: space-between; gap: 16px; }
.lede { color: var(--muted); max-width: 72ch; }
.data-status { display: flex; flex-wrap: wrap; gap: 8px 18px; font-size: var(--step--1); color: var(--muted); align-items: center; }
.data-status b { color: var(--ink); font-weight: 600; }
.pill { display: inline-flex; align-items: center; gap: 6px; padding: 2px 9px; border-radius: 999px; border: 1px solid var(--line); background: var(--raised); font-size: var(--step--1); white-space: nowrap; }
.data-status .pill { white-space: normal; overflow-wrap: anywhere; max-width: 100%; }
.data-status > span { min-width: 0; overflow-wrap: anywhere; }
.pill.warn { border-color: color-mix(in srgb, var(--warn) 55%, var(--line)); color: var(--warn); }
nav.toc { display: flex; flex-wrap: wrap; gap: 6px 14px; font-size: var(--step--1); }
nav.toc a { color: var(--muted); text-decoration: none; border-bottom: 1px solid transparent; }
nav.toc a:hover, nav.toc a:focus-visible { color: var(--ink); border-bottom-color: var(--accent); }
main { display: grid; gap: 44px; padding-block: 30px 60px; }
section { display: grid; gap: 16px; scroll-margin-top: 16px; }
.section-head { display: grid; gap: 6px; }
/* controls */
.controls { display: flex; flex-wrap: wrap; gap: 12px 22px; align-items: end; padding: 14px 16px; background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); }
.ctl { display: grid; gap: 4px; min-width: 0; }
.ctl label, .ctl .lbl { font-size: var(--step--1); color: var(--muted); }
select, input[type="number"], button, .filebtn { font: inherit; font-size: var(--step--1); color: var(--ink); background: var(--raised); border: 1px solid var(--line); border-radius: 5px; padding: 6px 10px; }
input[type="number"] { width: 5.5em; }
button, .filebtn { cursor: pointer; }
button:hover, .filebtn:hover { border-color: var(--accent); }
button:focus-visible, select:focus-visible, input:focus-visible, .filebtn:focus-within, a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
button.primary { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); font-weight: 600; }
.seg { display: inline-flex; border: 1px solid var(--line); border-radius: 6px; overflow: hidden; }
.seg button { border: 0; border-radius: 0; border-right: 1px solid var(--line); }
.seg button:last-child { border-right: 0; }
.seg button[aria-pressed="true"] { background: var(--ink); color: var(--bg); }
.check { display: inline-flex; gap: 6px; align-items: center; font-size: var(--step--1); }
.targets { display: flex; flex-wrap: wrap; gap: 8px; }
.tchip { display: inline-flex; align-items: center; gap: 7px; padding: 6px 11px; border-radius: 999px; border: 1px solid var(--line); background: var(--raised); font-size: var(--step--1); cursor: pointer; }
.tchip .sw { width: 11px; height: 11px; border-radius: 50%; background: var(--c, var(--faint)); box-shadow: 0 0 0 1px color-mix(in srgb, var(--ink) 25%, transparent); }
.tchip[aria-pressed="true"] { border-color: var(--c, var(--ink)); box-shadow: inset 0 0 0 1px var(--c, var(--ink)); font-weight: 600; }
.tchip.featured { padding: 7px 14px; font-size: var(--step-0); }
.target-group { display: grid; gap: 6px; }
/* map */
.map-shell { border: 1px solid var(--line); border-radius: var(--radius); background: var(--raised); overflow: hidden; }
.map-top { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; justify-content: space-between; padding: 10px 14px; border-bottom: 1px solid var(--line); background: var(--surface); }
.cond-chips { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; min-width: 0; }
.cchip { display: inline-flex; gap: 6px; align-items: center; padding: 2px 4px 2px 9px; border: 1px solid var(--accent); color: var(--ink); border-radius: 999px; font-size: var(--step--1); background: color-mix(in srgb, var(--accent) 10%, var(--raised)); }
.cchip button { border: 0; background: transparent; padding: 0 6px; line-height: 1; font-size: 1rem; color: var(--muted); }
.map-scroll { overflow-x: auto; }
#map { display: block; }
#map text { font-family: var(--font-body); font-size: 11px; fill: var(--ink); }
#map .stage-label { font-family: var(--font-data); font-size: 10px; letter-spacing: 0.08em; text-transform: uppercase; fill: var(--muted); }
#map .stage-chance { fill: var(--accent); }
#map .node rect { stroke: color-mix(in srgb, var(--ink) 40%, transparent); stroke-width: 0.6; cursor: pointer; }
#map .node.sel rect { stroke: var(--accent); stroke-width: 2.4; }
#map .node.dim { opacity: 0.35; }
#map .link { mix-blend-mode: normal; }
#map .link:hover { opacity: 1 !important; }
#map .node:focus-visible rect { stroke: var(--accent); stroke-width: 3; }
.map-foot { display: grid; grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr); gap: 18px; padding: 14px; border-top: 1px solid var(--line); background: var(--surface); }
@media (max-width: 820px) { .map-foot { grid-template-columns: minmax(0, 1fr); } }
.legend { display: flex; flex-wrap: wrap; gap: 10px 18px; align-items: center; font-size: var(--step--1); color: var(--muted); }
.ramp { width: 150px; height: 10px; border-radius: 3px; border: 1px solid var(--line); }
.sel-summary { display: grid; gap: 6px; font-size: var(--step--1); }
.sel-summary .big { font-family: var(--font-data); font-size: var(--step-2); color: var(--ink); }
#tip { position: fixed; z-index: 50; pointer-events: none; background: var(--raised); color: var(--ink); border: 1px solid var(--line); border-radius: 6px; padding: 8px 10px; font-size: var(--step--1); box-shadow: 0 6px 20px rgba(0,0,0,0.18); max-width: 300px; }
#tip .t { font-weight: 600; }
/* cards & grids */
.grid2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 420px), 1fr)); gap: 18px; }
.grid3 { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr)); gap: 18px; }
.panel { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); padding: 16px; display: grid; gap: 10px; min-width: 0; align-content: start; }
.panel h3 { display: flex; gap: 8px; align-items: baseline; flex-wrap: wrap; }
.chart { width: 100%; overflow-x: auto; }
.chart svg { display: block; width: 100%; max-width: 760px; min-width: 540px; height: auto; }
.chart svg text { font-family: var(--font-body); font-size: 11px; fill: var(--ink); }
.chart svg .axis text { fill: var(--muted); font-family: var(--font-data); font-size: 10px; }
.chart svg .axis line, .chart svg .grid line { stroke: var(--line); }
.findings { display: grid; gap: 12px; counter-reset: f; }
.finding { display: grid; grid-template-columns: 26px minmax(0, 1fr); gap: 10px; padding: 12px 14px; background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); }
.finding .mark { width: 22px; height: 22px; border-radius: 50%; display: grid; place-items: center; font-family: var(--font-data); font-size: 11px; color: var(--accent-ink); background: var(--muted); }
.finding.blue .mark { background: var(--dr-blue); color: #fff; }
.finding.black .mark { background: var(--dr-black); color: var(--bg); }
.finding.bias .mark { background: var(--warn); color: #fff; }
.finding.lead .mark { background: var(--accent); }
.finding p + p { margin-top: 4px; }
.finding .tag { font-family: var(--font-data); font-size: 10.5px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted); }
/* tables */
.tbl-wrap { overflow-x: auto; border: 1px solid var(--line); border-radius: var(--radius); background: var(--raised); }
table { border-collapse: collapse; width: 100%; font-size: var(--step--1); }
th, td { padding: 6px 10px; text-align: left; border-bottom: 1px solid var(--line); vertical-align: top; }
th { font-weight: 600; color: var(--muted); background: var(--surface); position: sticky; top: 0; white-space: nowrap; }
th[data-sort] { cursor: pointer; }
th[data-sort]:hover { color: var(--ink); }
td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-numeric: tabular-nums; white-space: nowrap; }
tr.sig td { background: color-mix(in srgb, var(--accent) 9%, transparent); }
tr.thin td { color: var(--faint); }
.route-cell { min-width: 280px; }
.cibar { display: inline-block; position: relative; width: 90px; height: 10px; vertical-align: middle; }
.cibar i { position: absolute; top: 4px; height: 2px; background: var(--muted); }
.cibar b { position: absolute; top: 1px; width: 2px; height: 8px; background: var(--ink); }
.qbadge { font-family: var(--font-data); font-size: 10.5px; padding: 1px 6px; border-radius: 4px; border: 1px solid var(--line); }
.qbadge.s { border-color: var(--accent); color: var(--accent); }
.method { display: grid; gap: 14px; }
.method p, .method li { max-width: 74ch; }
.method ul, .method ol { margin: 0; padding-left: 1.2em; display: grid; gap: 4px; }
.formula { font-family: var(--font-data); font-size: var(--step--1); background: var(--surface); border: 1px solid var(--line); border-left: 3px solid var(--accent); padding: 10px 12px; border-radius: 4px; overflow-x: auto; white-space: pre; }
details.fold { border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface); }
details.fold > summary { cursor: pointer; padding: 10px 14px; font-weight: 600; }
details.fold > div { padding: 0 14px 14px; display: grid; gap: 10px; }
.btnrow { display: flex; flex-wrap: wrap; gap: 8px; }
#srcview { white-space: pre; overflow: auto; max-height: 420px; font-family: var(--font-data); font-size: 12px; background: var(--raised); border: 1px solid var(--line); border-radius: 4px; padding: 10px; }
.toast { position: fixed; bottom: calc(16px + env(safe-area-inset-bottom, 0px)); left: 50%; transform: translateX(-50%); background: var(--ink); color: var(--bg); padding: 8px 14px; border-radius: 6px; font-size: var(--step--1); z-index: 60; }
.loading { padding: 40px 0; color: var(--muted); }
footer { border-top: 1px solid var(--line); padding-block: 22px 40px; color: var(--muted); font-size: var(--step--1); }
@media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
/* ---------- hero, tabs, overview, valley map, gallery ---------- */
body::before { content: ""; position: fixed; inset: 0 0 auto; height: env(safe-area-inset-top, 0px); z-index: 10; background: var(--hero-bg); }
.hero { background: radial-gradient(120% 140% at 70% 0%, var(--hero-bg2), var(--hero-bg) 60%); color: var(--hero-ink); position: relative; overflow: hidden; }
.hero .wrap { position: relative; z-index: 1; display: grid; gap: 14px; padding-block: 34px 0; }
.hero-art { position: absolute; inset: auto 0 0 0; height: 100%; width: 100%; z-index: 0; pointer-events: none; }
.hero h1 { font-family: var(--font-crest); font-weight: 700; font-size: clamp(1.9rem, 4.6vw, 3.1rem); letter-spacing: 0.04em; color: var(--hero-ink); }
.hero .kicker { font-family: var(--font-data); font-size: var(--step--1); letter-spacing: 0.14em; text-transform: uppercase; color: var(--hero-muted); }
.hero .tagline { color: var(--hero-muted); max-width: 60ch; font-size: var(--step-1); }
.hero .unofficial { display: inline-block; font-size: var(--step--1); color: var(--hero-muted); border: 1px solid var(--hero-line); border-radius: 999px; padding: 2px 10px; width: fit-content; }
.tabs { display: flex; gap: 2px; overflow-x: auto; margin-top: 18px; scrollbar-width: none; }
.tabs::-webkit-scrollbar { display: none; }
.tab { font-family: var(--font-crest); font-weight: 700; letter-spacing: 0.06em; font-size: 0.9rem; color: var(--hero-muted); background: transparent; border: 0; border-radius: 8px 8px 0 0; padding: 12px 16px 11px; white-space: nowrap; cursor: pointer; border-top: 2px solid transparent; }
.tab:hover { color: var(--hero-ink); }
.tab[aria-selected="true"] { background: var(--bg); color: var(--ink); border-top-color: var(--accent); }
.tab:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
.tabpanel { display: grid; gap: 44px; }
.tabpanel[hidden] { display: none !important; }
section h2 { font-family: var(--font-crest); letter-spacing: 0.03em; }
.odds { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 230px), 1fr)); gap: 16px; }
.odd { background: var(--surface); border: 1px solid var(--line); border-radius: 10px; padding: 16px; display: grid; gap: 10px; align-content: start; position: relative; overflow: hidden; }
.odd .big { font-family: var(--font-crest); font-weight: 700; font-size: 2.1rem; line-height: 1; color: var(--c, var(--ink)); }
.odd .what { font-weight: 600; }
.odd .how { font-size: var(--step--1); color: var(--muted); }
.odd svg { display: block; width: 100%; max-width: 220px; height: auto; }
.odd::before { content: ""; position: absolute; inset: 0 auto 0 0; width: 4px; background: var(--c, var(--line)); }
.combo { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 320px), 1fr)); gap: 16px; }
.combo .odd { grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 14px; }
.journey { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 150px), 1fr)); gap: 0; counter-reset: st; border: 1px solid var(--line); border-radius: 10px; overflow: hidden; background: var(--surface); }
.stop { padding: 14px; display: grid; gap: 6px; align-content: start; border-right: 1px solid var(--line); border-bottom: 1px solid var(--line); }
.stop .n { font-family: var(--font-crest); font-weight: 700; color: var(--accent); font-size: 1.3rem; }
.stop .t { font-weight: 600; }
.stop .d { font-size: var(--step--1); color: var(--muted); }
.stop .verdict { font-size: var(--step--1); border-top: 1px dashed var(--line); padding-top: 6px; }
.stop.roll .n::after { content: " · roll"; font-family: var(--font-data); font-size: 10px; letter-spacing: 0.1em; color: var(--muted); }
.truths { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr)); gap: 16px; }
.truth { padding: 18px; border-radius: 10px; background: var(--surface); border: 1px solid var(--line); display: grid; gap: 8px; align-content: start; }
.truth h3 { font-family: var(--font-crest); font-size: 1.05rem; letter-spacing: 0.02em; }
.cta { display: flex; flex-wrap: wrap; gap: 10px; }
.cta button { font-size: var(--step-0); padding: 9px 16px; }
.lore { border-left: 3px solid var(--accent); padding: 4px 0 4px 14px; color: var(--muted); font-size: var(--step--1); max-width: 70ch; }
.valley-shell { border: 1px solid var(--line); border-radius: 10px; overflow: hidden; background: var(--map-ground); }
.valley-wrap { overflow-x: auto; }
#valley { display: block; width: 100%; min-width: 820px; height: auto; background: #d9b07a; }
#valley .loc { cursor: pointer; }
#valley .loc:focus-visible circle.ring { stroke: var(--accent); stroke-width: 4; }
#valley text { font-family: var(--font-body); }
#valley .place { font-family: var(--font-crest); font-weight: 700; font-size: 15px; letter-spacing: 0.04em; fill: var(--map-label); paint-order: stroke; stroke: var(--map-halo); stroke-width: 4px; stroke-linejoin: round; }
#valley .sub { font-size: 12px; fill: var(--map-label); opacity: 0.85; paint-order: stroke; stroke: var(--map-halo); stroke-width: 3px; }
#valley .trail { fill: none; stroke-linecap: round; }
#valley .flow { fill: none; stroke-linecap: round; stroke-dasharray: 2 14; animation: march 1.6s linear infinite; }
@keyframes march { to { stroke-dashoffset: -32; } }
@media (prefers-reduced-motion: reduce) { #valley .flow { animation: none; } }
.valley-foot { display: grid; grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr); gap: 18px; padding: 14px; border-top: 1px solid var(--line); background: var(--surface); }
@media (max-width: 820px) { .valley-foot { grid-template-columns: minmax(0, 1fr); } }
.loc-card { display: grid; gap: 6px; font-size: var(--step--1); }
.loc-card h3 { font-family: var(--font-crest); font-size: 1.1rem; }
.bars { display: grid; gap: 4px; }
.bar { display: grid; grid-template-columns: 120px minmax(0, 1fr) 96px; gap: 8px; align-items: center; font-size: var(--step--1); }
.bar i { display: block; height: 10px; border-radius: 3px; background: var(--c, var(--muted)); min-width: 2px; }
.bar span:last-child { text-align: right; font-family: var(--font-data); white-space: nowrap; }
.gallery { display: grid; gap: 22px; }
.gal-group { display: grid; gap: 10px; }
.gal-group h3 { font-family: var(--font-crest); display: flex; gap: 10px; align-items: center; font-size: 1.15rem; }
.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 168px), 1fr)); gap: 10px; }
.dcard { background: var(--surface); border: 1px solid var(--line); border-radius: 10px; padding: 12px; display: grid; gap: 6px; justify-items: center; text-align: center; position: relative; }
.dcard svg { width: 64px; height: 64px; }
.dcard .nm { font-family: var(--font-crest); font-weight: 700; font-size: 1rem; letter-spacing: 0.03em; overflow-wrap: anywhere; }
.dcard .meta { font-size: 12px; color: var(--muted); line-height: 1.35; }
.dcard .age { position: absolute; top: 8px; right: 10px; font-family: var(--font-data); font-size: 11px; color: var(--muted); }
.viewtoggle { display: inline-flex; }
/* ---------- dusk & gold theme layer ---------- */
body { background: radial-gradient(140% 90% at 50% -10%, #2b0f1f 0%, var(--bg) 55%) fixed, var(--bg); }
.eyebrow, .kicker, .lbl, .tab, .tchip, button, .filebtn, th, .stage-label { font-family: var(--font-label); letter-spacing: 0.12em; text-transform: uppercase; }
.eyebrow { font-size: 0.72rem; color: var(--accent); }
h1, h2, h3 { font-family: var(--font-display); font-weight: 400; }
h2 { font-size: var(--step-2); letter-spacing: 0.04em; }
.panel h3, .truth h3, .gal-group h3, .loc-card h3 { font-family: var(--font-display); font-weight: 400; letter-spacing: 0.03em; }
button, .filebtn { border-radius: 999px; border: 1px solid color-mix(in srgb, var(--accent) 70%, transparent); background: color-mix(in srgb, var(--raised) 80%, #000); color: var(--ink); font-size: 0.74rem; padding: 8px 16px; box-shadow: inset 0 0 0 1px rgba(0,0,0,0.35), 0 0 12px rgba(232,180,131,0.08); }
button:hover, .filebtn:hover { border-color: var(--accent); box-shadow: inset 0 0 0 1px rgba(0,0,0,0.35), 0 0 14px rgba(232,180,131,0.25); }
button.primary { background: var(--accent); color: var(--accent-ink); }
select, input[type="number"], input[type="search"] { background: var(--raised) !important; color: var(--ink) !important; border: 1px solid var(--line) !important; border-radius: 8px !important; }
.seg { border-radius: 999px; border-color: color-mix(in srgb, var(--accent) 60%, transparent); }
.seg button { border-radius: 0; box-shadow: none; }
.seg button[aria-pressed="true"] { background: var(--accent); color: var(--accent-ink); }
.tchip { border-radius: 999px; border: 1px solid color-mix(in srgb, var(--c, var(--accent)) 55%, var(--line)); background: color-mix(in srgb, var(--raised) 85%, #000); font-size: 0.72rem; padding: 7px 14px; }
.tchip[aria-pressed="true"] { background: color-mix(in srgb, var(--c, var(--accent)) 22%, var(--raised)); box-shadow: 0 0 14px color-mix(in srgb, var(--c, var(--accent)) 35%, transparent), inset 0 0 0 1px var(--c, var(--accent)); }
.tchip.featured { font-size: 0.8rem; }
/* deco frame: double line + sunburst corners, tinted by --frame */
.deco { position: relative; border: 1px solid color-mix(in srgb, var(--frame) 75%, transparent); box-shadow: inset 0 0 0 4px var(--surface), inset 0 0 0 5px color-mix(in srgb, var(--frame) 40%, transparent); }
.deco::before, .deco::after { content: ""; position: absolute; width: 46px; height: 46px; pointer-events: none; background: var(--frame); opacity: 0.55;
-webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 46 46'%3E%3Cg stroke='black' stroke-width='1' fill='none'%3E%3Cpath d='M2 2 L44 9 M2 2 L40 16 M2 2 L35 22 M2 2 L29 28 M2 2 L22 35 M2 2 L16 40 M2 2 L9 44'/%3E%3Cpath d='M2 14 A12 12 0 0 0 14 2' stroke-width='1.4'/%3E%3C/g%3E%3C/svg%3E") no-repeat;
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 46 46'%3E%3Cg stroke='black' stroke-width='1' fill='none'%3E%3Cpath d='M2 2 L44 9 M2 2 L40 16 M2 2 L35 22 M2 2 L29 28 M2 2 L22 35 M2 2 L16 40 M2 2 L9 44'/%3E%3Cpath d='M2 14 A12 12 0 0 0 14 2' stroke-width='1.4'/%3E%3C/g%3E%3C/svg%3E") no-repeat; }
.deco::before { top: 6px; left: 6px; }
.deco::after { bottom: 6px; right: 6px; transform: rotate(180deg); }
.panel, .odd, .truth, .finding, .controls, .map-shell, .valley-shell, .journey, .dcard, .tbl-wrap { border-color: color-mix(in srgb, var(--frame) 30%, var(--line)); }
.panel, .odd, .truth { background: linear-gradient(180deg, color-mix(in srgb, var(--surface) 92%, var(--frame) 8%), var(--surface)); }
.controls { background: color-mix(in srgb, var(--surface) 80%, #000); }
.odd::before { display: none; }
.odd { border-radius: 120px 120px 14px 14px / 60px 60px 14px 14px; padding-top: 26px; text-align: center; justify-items: center; }
.odd .big { font-family: var(--font-display); font-weight: 400; text-shadow: 0 0 18px color-mix(in srgb, var(--c) 45%, transparent); }
.combo .odd { border-radius: 14px; text-align: left; justify-items: start; }
.truth { border-radius: 14px; }
table { background: transparent; }
th { background: color-mix(in srgb, var(--surface) 70%, #000); color: var(--accent); font-size: 0.7rem; }
td { border-bottom-color: color-mix(in srgb, var(--line) 70%, transparent); }
.tbl-wrap { background: color-mix(in srgb, var(--raised) 60%, var(--bg)); }
.formula { background: var(--death-bg); border-left-color: var(--accent); }
#tip { background: #2a1420; border-color: var(--accent); box-shadow: 0 6px 24px rgba(0,0,0,0.5), 0 0 12px rgba(232,180,131,0.15); }
.toast { background: var(--accent); color: var(--accent-ink); }
.pill { background: color-mix(in srgb, var(--raised) 70%, #000); }
.lore { border-left-color: var(--accent); font-style: italic; }
/* hero: arched title card over a dusk forest */
.hero { background: radial-gradient(90% 120% at 50% 0%, var(--hero-bg2), var(--hero-bg) 70%); }
.hero .wrap { justify-items: center; text-align: center; padding-block: 28px 0; }
.arch { --frame: var(--accent); position: relative; padding: 34px clamp(18px, 5vw, 64px) 26px; border-radius: 260px 260px 18px 18px / 150px 150px 18px 18px; border: 1px solid color-mix(in srgb, var(--accent) 80%, transparent);
box-shadow: inset 0 0 0 5px rgba(26,9,18,0.9), inset 0 0 0 6px color-mix(in srgb, var(--accent) 45%, transparent), 0 0 40px rgba(0,0,0,0.45);
background: radial-gradient(70% 80% at 50% 40%, rgba(40,10,26,0.92), rgba(22,7,15,0.95)); display: grid; gap: 10px; justify-items: center; max-width: 760px; width: 100%; }
.arch .crest { width: 120px; height: 34px; margin-top: -8px; }
.hero h1 { font-family: var(--font-display); font-weight: 400; letter-spacing: 0.08em; text-transform: uppercase; font-size: clamp(1.7rem, 5vw, 3rem); text-shadow: 0 0 22px rgba(232,180,131,0.25); }
.hero .kicker { font-family: var(--font-label); color: var(--accent); letter-spacing: 0.22em; font-size: 0.7rem; }
.hero .tagline { color: var(--hero-muted); font-size: var(--step-1); }
.hero .unofficial { border-color: var(--hero-line); color: var(--hero-muted); }
.tabs { justify-content: flex-start; gap: 6px; margin-top: 22px; padding-bottom: 14px; flex-wrap: nowrap; width: fit-content; max-width: 100%; }
.tab { border-radius: 999px; border: 1px solid color-mix(in srgb, var(--accent) 45%, transparent); padding: 9px 16px; font-size: 0.7rem; color: var(--hero-muted); background: rgba(20,6,13,0.6); border-top-width: 1px; }
.tab[aria-selected="true"] { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); box-shadow: 0 0 16px rgba(232,180,131,0.35); }
.embers { position: absolute; inset: 0; pointer-events: none; z-index: 0; overflow: hidden; }
.embers i { position: absolute; bottom: -10px; width: 4px; height: 4px; border-radius: 50%; background: var(--ember); box-shadow: 0 0 8px var(--ember); opacity: 0; animation: rise linear infinite; }
@keyframes rise { 0% { transform: translateY(0); opacity: 0; } 10% { opacity: 0.9; } 100% { transform: translateY(-340px) translateX(20px); opacity: 0; } }
@media (prefers-reduced-motion: reduce) { .embers i { animation: none; opacity: 0.5; bottom: auto; } }
/* death palette: steel frame, ember glow */
.death { --frame: var(--death); background: radial-gradient(80% 90% at 50% 30%, #2a0b19, var(--death-bg)) !important; color: #efe6f2; }
.death .big { color: #efe6f2 !important; text-shadow: 0 0 22px rgba(227,105,47,0.45), 0 0 4px rgba(255,255,255,0.4) !important; font-family: var(--font-display); text-transform: uppercase; letter-spacing: 0.04em; }
.death .how, .death p { color: #c8bcc9; }
.arch::before { top: auto; bottom: 6px; left: 6px; transform: rotate(270deg); }
.odds { grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr)); }
@media (max-width: 600px) { .hero .tagline { font-size: var(--step-0); } }
/* dragon-tinted frames */
.dcard { --frame: var(--dc, var(--accent)); border-radius: 60px 60px 12px 12px / 34px 34px 12px 12px; border: 1px solid color-mix(in srgb, var(--frame) 60%, transparent); box-shadow: inset 0 0 0 3px var(--surface), inset 0 0 0 4px color-mix(in srgb, var(--frame) 30%, transparent); padding-top: 16px; }
.dcard .nm { font-family: var(--font-display); font-weight: 400; }
.gal-group h3 { color: var(--ink); }
.loc-card { --frame: var(--lc, var(--accent)); }
.valley-shell { --frame: var(--vt, var(--accent)); border-color: color-mix(in srgb, var(--frame) 60%, transparent); box-shadow: 0 0 0 4px var(--bg), 0 0 0 5px color-mix(in srgb, var(--frame) 40%, transparent), 0 0 30px color-mix(in srgb, var(--frame) 15%, transparent); }
#panel-rare .panel:nth-child(odd) { --frame: var(--dr-blue); }
#panel-rare .panel:nth-child(even) { --frame: var(--dr-black); }
.stop .n { font-family: var(--font-display); font-weight: 400; color: var(--accent); }
.journey { background: color-mix(in srgb, var(--surface) 85%, #000); }
footer { border-top-color: var(--line); }
</style>
<header class="hero">
<svg class="hero-art" id="hero-art" viewBox="0 0 1200 420" preserveAspectRatio="xMidYMax slice" aria-hidden="true"></svg>
<div class="embers" id="embers" aria-hidden="true"></div>
<div class="wrap">
<div class="arch deco">
<svg class="crest" viewBox="0 0 120 34" aria-hidden="true"><g fill="none" stroke="#e8b483" stroke-width="1.1"><path d="M4 20 H44 M76 20 H116"/><path d="M60 4 L68 17 L60 30 L52 17 Z"/><path d="M60 10 L64 17 L60 24 L56 17 Z" fill="#e8b483"/><path d="M44 20 C50 12, 54 12, 52 17 M76 20 C70 12, 66 12, 68 17"/><circle cx="4" cy="20" r="2" fill="#e8b483"/><circle cx="116" cy="20" r="2" fill="#e8b483"/></g></svg>
<span class="kicker">Basgiath · Riders Quadrant · Threshing</span>
<h1>Threshing Route Atlas</h1>
<p class="tagline" id="hero-tagline">Every path through the valley, mapped from the runs riders logged.</p>
<span class="unofficial">Unofficial fan atlas for readers of Rebecca Yarros's <i>Fourth Wing</i> · not affiliated with Dragonkind</span>
</div>
<nav class="tabs" role="tablist" aria-label="Atlas pages">
<button class="tab" role="tab" id="tab-overview" aria-controls="panel-overview" aria-selected="true">The Threshing</button>
<button class="tab" role="tab" id="tab-valley" aria-controls="panel-valley" aria-selected="false">Valley Map</button>
<button class="tab" role="tab" id="tab-flow" aria-controls="panel-flow" aria-selected="false">Route Flow</button>
<button class="tab" role="tab" id="tab-rare" aria-controls="panel-rare" aria-selected="false">Blue &amp; Black</button>
<button class="tab" role="tab" id="tab-dragons" aria-controls="panel-dragons" aria-selected="false">The Dragons</button>
<button class="tab" role="tab" id="tab-deep" aria-controls="panel-deep" aria-selected="false">Deep Dive</button>
<button class="tab" role="tab" id="tab-share" aria-controls="panel-share" aria-selected="false">Data &amp; Share</button>
</nav>
</div>
</header>
<div class="wrap">
<main>
<div class="tabpanel" id="panel-overview" role="tabpanel" aria-labelledby="tab-overview">
<section id="overview" aria-labelledby="h-odds">
<div class="section-head">
<span class="eyebrow">Before you walk into the valley</span>
<h2 id="h-odds">Your odds, honestly</h2>
<p class="muted small">Each grid of dots is 100 runs. These numbers lean on the riders who logged <i>every</i> run, including the dull ones, because people mostly share their lucky runs.</p>
</div>
<div class="odds" id="odds"></div>
<div class="combo" id="combo"></div>
</section>
<section aria-labelledby="h-journey">
<div class="section-head">
<span class="eyebrow">Seven steps, two of them pure luck</span>
<h2 id="h-journey">How a run unfolds</h2>
</div>
<div class="journey" id="journey"></div>
<p class="lore">In the books, first-years who survive to Threshing walk into a valley of unbonded dragons, and the dragons do the choosing. The Dragonkind site recreates that: every choice can end with you incinerated, and the author has said there is a 10% chance of that no matter what you pick.</p>
</section>
<section aria-labelledby="h-truths">
<div class="section-head"><span class="eyebrow">What 2,500 runs say</span><h2 id="h-truths">Three things worth knowing</h2></div>
<div class="truths" id="truths"></div>
<div class="cta"><button type="button" class="primary" data-go="valley">Walk the valley map</button><button type="button" data-go="rare">Chasing a Blue or Black?</button><button type="button" data-go="dragons">Meet the bonded dragons</button></div>
</section>
</div>
<div class="tabpanel" id="panel-valley" role="tabpanel" aria-labelledby="tab-valley" hidden>
<section id="valley-sec" aria-labelledby="h-valley">
<div class="section-head">
<span class="eyebrow">Interactive · drawn from the in-game descriptions, not an official map</span>
<h2 id="h-valley">The valley</h2>
<p class="muted small">Trails are as thick as the number of riders who walked them. Their colour shows how often walking that way ended with the dragon you pick below. Tap a place for what happened there.</p>
</div>
<div class="controls"><div class="target-group"><span class="lbl small muted">Colour the trails by</span><div class="targets" id="valley-targets"></div></div></div>
<div class="valley-shell deco">
<div class="valley-wrap"><svg id="valley" viewBox="0 0 1000 780" role="img" aria-label="Illustrated map of the threshing valley with trails"></svg></div>
<div class="valley-foot"><div class="loc-card" id="loc-card"></div><div class="legend" id="valley-legend"></div></div>
</div>
</section>
</div>
<div class="tabpanel" id="panel-flow" role="tabpanel" aria-labelledby="tab-flow" hidden>
<section id="map-sec" aria-labelledby="h-map">
<div class="section-head">
<span class="eyebrow">Interactive</span>
<h2 id="h-map">Route map</h2>
<p class="muted small">Pick an outcome. Click any box to keep only the runs that passed through it, and click more boxes to narrow further. Hover or tap a box or band for its numbers.</p>
</div>
<div class="controls" id="map-controls">
<div class="target-group">
<span class="lbl small muted">Rare dragons</span>
<div class="targets" id="targets-rare"></div>
</div>
<div class="target-group">
<span class="lbl small muted">Other outcomes</span>
<div class="targets" id="targets-other"></div>
</div>
</div>
<div class="controls">
<div class="ctl"><span class="lbl">Band width shows</span>
<div class="seg" id="width-mode"><button type="button" data-v="traffic" aria-pressed="true">How many runs</button><button type="button" data-v="prob" aria-pressed="false">Chance of outcome</button></div></div>
<div class="ctl"><label for="minn">Grey out steps with fewer runs than</label><input id="minn" type="number" min="1" max="200" value="10"></div>
<div class="ctl"><label for="f-source">Data source</label>
<select id="f-source"><option value="all">All rows</option><option value="form">Form submissions only</option><option value="bulk">Bulk logs only (imports)</option></select></div>
<div class="ctl"><label for="f-goal">Players chasing</label>
<select id="f-goal"><option value="all">Any goal</option><option value="exclude_rare">Not chasing Blue/Black</option><option value="only_rare">Chasing Blue/Black</option></select></div>
<label class="check" for="f-flag"><input id="f-flag" type="checkbox"> Drop rows with data-quality flags</label>
</div>
<div class="map-shell deco">
<div class="map-top">
<div class="cond-chips" id="cond-chips"><span class="small muted">Showing all runs. Click a box to follow only the runs through it.</span></div>
<div class="btnrow"><button type="button" id="btn-best">Show top routes for this outcome</button><button type="button" id="btn-clear">Clear selection</button></div>
</div>
<div class="map-scroll"><svg id="map" role="img" aria-label="Route map"></svg></div>
<div class="map-foot">
<div class="sel-summary" id="sel-summary"></div>
<div class="legend" id="legend"></div>
</div>
</div>
<div id="best-routes"></div>
</section>
</div>
<div class="tabpanel" id="panel-rare" role="tabpanel" aria-labelledby="tab-rare" hidden>
<section id="rare" aria-labelledby="h-rare">
<div class="section-head">
<span class="eyebrow">Blue &amp; Black</span>
<h2 id="h-rare">The rare dragons</h2>
<p class="muted small">Two separate rolls. The meadow Blue can join the Orange and Brown after you turn down the valley Red. The tree's shadow option leads to a Blue and then a Black.</p>
</div>
<div class="grid2">
<div class="panel"><h3>Does the Blue show up in the meadow?</h3><p class="small muted">Share of meadow visits where a Blue was attempted, by who logged the run. The game cannot know which dragon a player is chasing, so gaps between these bars come from how people report, not from the game.</p><div class="chart" id="ch-blue-strata"></div></div>
<div class="panel"><h3>Does the shadow show up at the tree?</h3><p class="small muted">Share of tree climbs where the shadow option led to a Blue and/or Black.</p><div class="chart" id="ch-shadow-strata"></div></div>
</div>
<div class="grid2">
<div class="panel"><h3>What changes the Blue's appearance, once reporting bias is held fixed?</h3><p class="small muted">Adjusted odds ratios from one logistic model: route choices plus data source and chase goal. Bars that cross 1 mean no detectable effect.</p><div class="chart" id="ch-model-blue"></div><p class="small muted" id="model-blue-note"></p></div>
<div class="panel"><h3>What changes the shadow's appearance?</h3><p class="small muted">Same approach for the shadow. With so few shadows, intervals are wide.</p><div class="chart" id="ch-model-shadow"></div><p class="small muted" id="model-shadow-note"></p></div>
</div>
<div class="grid2">
<div class="panel"><h3>Day by day (form submissions)</h3><p class="small muted">Bulk imports carry no dates, so they are left out here. Dots are sized by the number of runs, and whiskers show 95% intervals.</p><div class="chart" id="ch-daily"></div></div>
<div class="panel"><h3>Bonding once you reach them</h3><div class="chart" id="ch-rare-bond"></div>
<details class="fold"><summary>Step-by-step survival inside the encounter (from the community PDF)</summary><div id="pdf-steps"></div></details>
</div>
</div>
</section>
</div>
<div class="tabpanel" id="panel-dragons" role="tabpanel" aria-labelledby="tab-dragons" hidden>
<section id="register" aria-labelledby="h-register">
<div class="section-head">
<span class="eyebrow">Bonded dragons, as riders registered them</span>
<h2 id="h-register">The bonded dragons</h2>
<p class="muted small">Every bonded dragon we could collect, sorted by colour, then tail, then lineage, then oldest first. Most come from ClumsyBadger's Unofficial Dragon Register form, and the rest from dragonkind.com result pages linked in the megathreads. Rider names and photos are left out. Misspelled lineages are corrected when they are within two letters of a lineage seen at least three times for the same colour. The original spelling is kept in the notes.</p>
</div>
<div class="data-status" id="reg-status"></div>
<div class="grid2">
<div class="panel"><h3>Colour × tail</h3><div class="tbl-wrap" id="reg-matrix"></div></div>
<div class="panel"><h3>Lineages</h3><div class="tbl-wrap" id="reg-lineages" style="max-height:340px"></div></div>
</div>
<div class="controls">
<div class="ctl"><label for="reg-colour">Colour</label><select id="reg-colour"></select></div>
<div class="ctl"><label for="reg-tail">Tail</label><select id="reg-tail"></select></div>
<div class="ctl"><label for="reg-lineage">Lineage</label><select id="reg-lineage"></select></div>
<div class="ctl"><label for="reg-sex">Sex</label><select id="reg-sex"></select></div>
<div class="ctl"><label for="reg-q">Search names</label><input id="reg-q" type="search" placeholder="Dragon or lineage" style="font:inherit;font-size:var(--step--1);padding:6px 10px;border:1px solid var(--line);border-radius:5px;background:var(--raised);color:var(--ink)"></div>
<div class="ctl"><span class="lbl">View</span><div class="seg" id="reg-view"><button type="button" data-v="cards" aria-pressed="true">Cards</button><button type="button" data-v="table" aria-pressed="false">Table</button></div></div>
<div class="btnrow" style="align-self:end"><button type="button" id="reg-copy">Copy as CSV</button><label class="filebtn" for="reg-upload">Load a newer register export…<input id="reg-upload" type="file" accept=".xlsx,.csv" hidden></label></div>
<span class="small muted" id="reg-count" style="align-self:center"></span>
</div>
<div class="gallery" id="reg-gallery"></div>
<div class="tbl-wrap" id="reg-table" style="max-height:640px" hidden></div>
</section>
<section id="bondrates" aria-labelledby="h-dragons">
<div class="section-head">
<span class="eyebrow">All six colours</span>
<h2 id="h-dragons">Every dragon: how often the attempt ends in a bond</h2>
<p class="muted small">A run counts here when the player reached that dragon's bonding encounter and the form shows Bonded or Incinerated. Many players die on purpose to reroll, which drags the raw rate down. "Wanted it" keeps only runs where the player said they were after that colour, or any dragon.</p>
</div>
<div class="chart panel" id="ch-encounters"></div>
<div class="grid2">
<div class="panel"><h3>The two Greens</h3><div id="green-rescue"></div></div>
<div class="panel"><h3>First sighting: what the game rolls</h3><p class="small muted">Which dragon met the cadet first, by company and direction. Pools come from the community PDF, and cells outside them are counted as data-quality flags.</p><div class="tbl-wrap" id="tbl-first"></div></div>
</div>
</section>
</div>
<div class="tabpanel" id="panel-deep" role="tabpanel" aria-labelledby="tab-deep" hidden>
<section id="findings" aria-labelledby="h-findings">
<div class="section-head">
<span class="eyebrow">What the data supports</span>
<h2 id="h-findings">Findings</h2>
<p class="muted small">These sentences are generated from the current data and filters, so they update when the data does. "Lead" means a pattern worth testing that is not yet established.</p>
</div>
<div class="findings" id="findings-list"></div>
</section>
<section id="routes" aria-labelledby="h-routes">
<div class="section-head">
<span class="eyebrow">Ranked</span>
<h2 id="h-routes">Route table</h2>
<p class="muted small">A route here means every choice up to the hour. Routes are ranked by the lower end of their 95% interval, so a route needs both a high rate and enough runs to rank high. Each route is compared with every other route that could reach the same outcome. "Adjusted" holds data source and chase goal fixed (Mantel–Haenszel). q-values correct for testing many routes at once.</p>
</div>
<div class="controls"><div class="ctl"><label for="rt-target">Outcome</label><select id="rt-target"></select></div><div class="ctl"><label for="rt-min">Minimum runs per route</label><input id="rt-min" type="number" min="1" max="200" value="10"></div><p class="small muted" id="rt-note" style="align-self:center"></p></div>
<div class="tbl-wrap" id="tbl-routes"></div>
</section>
<section id="factors" aria-labelledby="h-factors">
<div class="section-head">
<span class="eyebrow">One choice at a time</span>
<h2 id="h-factors">Factor explorer</h2>
<p class="muted small">Each row compares runs with that answer against runs with any other answer to the same question, using Fisher's exact test. These comparisons are unadjusted, so check the adjusted models above before trusting a difference. Shaded rows have q &lt; 0.05 after correcting for every comparison in this table.</p>
</div>
<div class="controls"><div class="ctl"><label for="fx-outcome">Outcome</label><select id="fx-outcome"></select></div><div class="ctl"><label for="fx-factor">Question</label><select id="fx-factor"></select></div></div>
<div class="grid2"><div class="tbl-wrap" id="tbl-factors"></div><div class="panel"><h3>Odds ratios</h3><div class="chart" id="ch-factor"></div></div></div>
</section>
<section id="quality" aria-labelledby="h-quality">
<div class="section-head">
<span class="eyebrow">Read this before quoting a number</span>
<h2 id="h-quality">Data quality and bias</h2>
</div>
<div class="grid3" id="quality-panels"></div>
</section>
<section id="methods" aria-labelledby="h-methods" class="method">
<div class="section-head"><span class="eyebrow">How every number is made</span><h2 id="h-methods">Methods</h2></div>
<div class="grid2">
<div class="method">
<h3>1. From form answers to runs</h3>
<p>Each row of the "Threshing Routes" form (and each row pasted in from players' own logs) is one threshing run. The page reads the raw export and codes every row with the same fixed rules, which are visible in <code>engine.js</code>:</p>
<ul>
<li><b>Source.</b> Rows with a real timestamp are form submissions. Rows labelled "Data Import", "Manual Upload" or "Historical import" were bulk-pasted from players' own run logs and are called <i>bulk logs</i> here.</li>
<li><b>Cadet encounter.</b> Split into the scream choice (help, investigate and leave, or ignore) and its resolution (killed the bullies, squadmate's revenge, left them to the dragons, tourniquet, left the cadet, took their weapons). The fork in the road only exists after helping, so other branches are coded "(no fork)".</li>
<li><b>Encounter branch.</b> A tree run with a Blue or Black recorded took the shadow. A tree run with Greens recorded descended slowly, and one with only a Red descended quickly. A valley run with an Orange, Brown or Blue recorded (or a Red marked "Changed my mind") passed the Red and reached the meadow.</li>
<li><b>Outcome.</b> Bonded to the one dragon marked "Bonded!". Otherwise incinerated by the last dragon marked "Incinerated" in encounter order, or died before the hour. "Saved by another" on the Greens plus a bonded Orange or Brown counts as a rescue bond.</li>
<li><b>Flags.</b> Rows are flagged, not deleted, when answers contradict each other: several directions or wings, Greens in the valley, two bonds, or a first sighting outside the documented pool. You can drop flagged rows with the checkbox above the map.</li>
</ul>
<h3>2. Rates and their uncertainty</h3>
<p>A rate is k events out of n runs that could have had that event. The denominator matters. The meadow Blue rate divides by runs that reached the meadow, not by all runs. Intervals are 95% Wilson score intervals, which behave well for small n and for rates near 0%:</p>
<div class="formula">p̂ = k / n, z = 1.96
centre = (p̂ + z²/2n) / (1 + z²/n)
half = z·√(p̂(1−p̂)/n + z²/4n²) / (1 + z²/n)
CI = centre ± half</div>
<p>With 0 events in n runs, the upper end is still informative. For example, 0 shadows in 367 bulk-log tree climbs gives an upper bound near 1.0%.</p>
</div>
<div class="method">
<h3>3. Comparing choices</h3>
<p>For one answer against the rest, the 2×2 table is [a b; c d] = [event, no event] × [this answer, other answers].</p>
<div class="formula">OR = (a·d) / (b·c)
95% CI = exp( ln OR ± 1.96·√(1/a + 1/b + 1/c + 1/d) )
(0.5 is added to every cell when any cell is 0)
p = Fisher's exact test, two-sided
q = Benjamini–Hochberg: sort p, q(i) = min over j≥i of p(j)·m/j</div>
<p>An odds ratio of 2 means the odds of the outcome are twice as high with that answer. q-values control the false-discovery rate. With dozens of comparisons, some p &lt; 0.05 results are expected by chance, so a "real" difference needs q &lt; 0.05.</p>
<h3>4. Adjusting for who reports what</h3>
<p>Players chasing a Blue log runs where they saw a Blue far more often than other players do. Bulk loggers record every run, including dull ones. To separate route effects from reporting effects, the page fits a logistic regression with every route choice plus data source and chase goal:</p>
<div class="formula">logit P(event) = β₀ + Σ βⱼ·xⱼ (x = 0/1 indicators; reference = most common answer)
fitted by Newton–Raphson with a small ridge penalty λ = 1 on the slopes
adjusted OR = exp(βⱼ), 95% CI = exp(βⱼ ± 1.96·SEⱼ)</div>
<p>The ridge penalty keeps estimates finite when an answer has 0 events. It shrinks extreme odds ratios slightly toward 1, which makes the model more cautious. Route rankings use the Mantel–Haenszel odds ratio across four strata (bulk logs, form runs chasing Blue, chasing Black, everything else) for the same reason.</p>
<h3>5. What this data cannot tell you</h3>
<ul>
<li>It is self-reported and self-selected. Runs worth bragging about are over-represented, and that inflates every rare-dragon rate. Bulk logs are the least selected rows.</li>
<li>Runs are not independent. One player may log dozens of runs, and the form has no player ID, so intervals are somewhat too narrow.</li>
<li>The form records only stage-level choices. It does not record how you reacted to the first dragon (lower eyes, hold still…) or most choices inside an encounter, so route claims that depend on those cannot be tested here.</li>
<li>The form records dragons you <i>attempted</i>. A player who saw the Blue but chose the Orange would not record the Blue, so Blue sightings are slightly undercounted.</li>
<li>Step-by-step survival inside an encounter comes from the community PDF, which coded the free-text answers by hand. It is shown as published and cannot be recomputed here.</li>
</ul>
</div>
</div>
</section>
</div>
<div class="tabpanel" id="panel-share" role="tabpanel" aria-labelledby="tab-share" hidden>
<section id="data-sec" aria-labelledby="h-data">
<div class="section-head"><span class="eyebrow">Where the numbers come from</span><h2 id="h-data">Data</h2></div>
<div class="data-status" id="data-status"><span class="loading">Loading data…</span></div>
<div class="btnrow"><label class="filebtn" for="upload">Load a newer route export…<input id="upload" type="file" accept=".xlsx,.csv" hidden></label><button id="btn-reset-data" type="button" hidden>Back to bundled data</button></div>
</section>
<section id="share" aria-labelledby="h-share">
<div class="section-head"><span class="eyebrow">Open by design</span><h2 id="h-share">Share &amp; reproduce</h2>
<p class="muted small">Everything on this page is recomputed in your browser from the raw form export. To update it, download the latest responses sheet (File → Download → Microsoft Excel) and load it with "Load a newer export" at the top. Column order does not matter, because questions are matched by their wording.</p></div>
<div class="grid2">
<div class="panel"><h3>Copy the outputs</h3>
<div class="btnrow"><button type="button" id="cp-reddit" class="primary">Copy Reddit post (Markdown)</button><button type="button" id="cp-csv">Copy coded runs (CSV)</button><button type="button" id="cp-json">Copy all results (JSON)</button></div>
<p class="small muted">The Reddit post is written from the current numbers and filters.</p></div>
<div class="panel"><h3>Read the code</h3>
<div class="btnrow"><button type="button" data-src="engine.js">engine.js (all rules and statistics)</button><button type="button" data-src="app.js">app.js (this page)</button><button type="button" data-src="python/clean.py">clean.py</button><button type="button" data-src="python/analyze.py">analyze.py</button><button type="button" data-src="python/stats_core.py">stats_core.py</button><button type="button" data-src="register.js">register.js</button><button type="button" data-src="README.md">README</button></div>
<p class="small muted">The Python files are an independent second implementation. The test scripts confirm that both produce identical coded runs and identical odds ratios, p-values and model estimates.</p>
<pre id="srcview" hidden></pre></div>
</div>
</section>
</div>
</main>
</div>
<footer><div class="wrap"><p>Data: the community "Threshing Routes" Google Form and spreadsheet compiled by u/ClumsyBadger, with percentages in the route PDF by u/ClumsyBadger, u/Old_Regular3018 and u/Smart_Trifle_2099. This is an unofficial fan analysis, not affiliated with the Dragonkind site or its authors. A 10% "chaos" chance of incineration on any choice has been described by the author, so no route guarantees a bond.</p></div></footer>
<div id="tip" hidden></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script src="engine.js"></script>
<script src="register.js"></script>
<script src="app.js"></script>
<script src="valley.js"></script>
<script src="ui.js"></script>
+204
View File
@@ -0,0 +1,204 @@
/* register.js — the Dragon Register section: clean, merge, sort and display bonded dragons.
* Works in the browser (window.DragonRegister) and in Node (module.exports) for testing. */
(function (root, factory) {
if (typeof module === "object" && module.exports) module.exports = factory();
else root.DragonRegister = factory();
})(typeof self !== "undefined" ? self : this, function () {
"use strict";
const COLOUR_ORDER = ["Red", "Orange", "Brown", "Green", "Blue", "Black"];
const TAILS = ["Clubtail", "Daggertail", "Morningstartail", "Scorpiontail", "Swordtail"];
const KEYS = {
timestamp: ["timestamp"], cadet: ["cadet name"], wing: ["assignment - wing"], section: ["assignment - section"],
squad: ["assignment - squad"], name: ["dragon", "name"], lineage: ["lineage"], colour: ["colour"], tail: ["tail"],
sex: ["sex"], age: [/\bage\b/],
};
const str = (v) => (v === null || v === undefined ? null : String(v).trim() || null);
const title = (s) => (s ? s.charAt(0).toUpperCase() + s.slice(1).toLowerCase() : s);
function findCols(headers) {
const C = {};
for (const [k, words] of Object.entries(KEYS)) {
const h = headers.find((x) => words.every((w) => (w instanceof RegExp ? w.test(String(x).toLowerCase()) : String(x).toLowerCase().includes(w))) && !(k === "name" && /cadet/i.test(x)));
if (h) C[k] = h;
}
return C;
}
function tailOf(v) {
const t = (str(v) || "").toLowerCase().replace(/[^a-z]/g, "");
return TAILS.find((x) => x.toLowerCase() === t || x.toLowerCase().replace("tail", "") === t) || (t ? title(t) : "Unknown");
}
function lev(a, b) {
const m = a.length, n = b.length, d = Array.from({ length: m + 1 }, (_, i) => [i, ...new Array(n).fill(0)]);
for (let j = 1; j <= n; j++) d[0][j] = j;
for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++)
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
return d[m][n];
}
const lkey = (s) => (str(s) || "").toLowerCase().replace(/[^a-z]/g, "");
// rows: raw register form rows; extra: dragons from other sources (already structured)
function build(raw) {
const C = findCols(raw.headers || Object.keys(raw.rows[0] || {}));
const items = raw.rows.map((r, i) => ({
source: "Register form", source_url: null, submitted: str(r[C.timestamp]),
cadet: str(r[C.cadet]), wing: str(r[C.wing]), section: str(r[C.section]), squad: str(r[C.squad]),
name: str(r[C.name]), lineage_raw: str(r[C.lineage]), colour: title(str(r[C.colour])), tail: tailOf(r[C.tail]),
sex: title(str(r[C.sex])), age: parseInt(r[C.age], 10), flags: [],
}));
(raw.extra || []).forEach((e) => items.push({
source: "Reddit (dragonkind.com result page)", source_url: e.url, submitted: null, cadet: null, wing: null, section: null, squad: null,
name: str(e.name), lineage_raw: str(e.lineage), colour: title(e.colour), tail: tailOf(e.tail), sex: title(e.sex), age: parseInt(e.age, 10), flags: [],
}));
// lineage spelling: spellings used 3+ times are canonical; others snap to a canonical of the same colour within 2 edits
const counts = {};
items.forEach((it) => { const k = lkey(it.lineage_raw); if (k) counts[k] = (counts[k] || 0) + 1; });
// spellings confirmed by an official dragonkind.com result page also count as canonical
const official = new Set(items.filter((it) => it.source_url).map((it) => lkey(it.lineage_raw)));
const canon = Object.keys(counts).filter((k) => counts[k] >= 3 || official.has(k));
const colourOfKey = {};
items.forEach((it) => { const k = lkey(it.lineage_raw); if (canon.includes(k)) (colourOfKey[k] = colourOfKey[k] || new Set()).add(it.colour); });
items.forEach((it) => {
let k = lkey(it.lineage_raw);
if (k && !canon.includes(k)) {
const best = canon.filter((c) => colourOfKey[c] && colourOfKey[c].has(it.colour)).map((c) => [c, lev(k, c)]).sort((a, b) => a[1] - b[1])[0];
if (best && best[1] <= 2) { it.flags.push(`lineage spelled "${it.lineage_raw}"`); k = best[0]; }
else it.flags.push("lineage seen fewer than 3 times");
}
it.lineage = k ? title(k) : "Unknown";
if (!Number.isFinite(it.age)) { it.age = null; it.flags.push("age missing"); }
if (!COLOUR_ORDER.includes(it.colour)) it.flags.push("unrecognised colour");
});
// a lineage should belong to one colour
const lc = {};
items.forEach((it) => (lc[it.lineage] = lc[it.lineage] || new Set()).add(it.colour));
items.forEach((it) => { if (lc[it.lineage].size > 1) it.flags.push(`lineage also recorded under ${[...lc[it.lineage]].filter((c) => c !== it.colour).join("/")}`); });
// duplicates: same dragon name + colour + tail + sex + age + lineage
const seen = new Map(), out = [];
items.forEach((it) => {
const key = [it.name && it.name.toLowerCase(), it.colour, it.tail, it.sex, it.age, it.lineage].join("|");
if (seen.has(key)) {
const first = seen.get(key);
first.duplicates = (first.duplicates || 0) + 1;
if (!first.also.includes(it.source) && it.source !== first.source) first.also.push(it.source);
if (it.source_url && !first.source_url) first.source_url = it.source_url;
return;
}
it.also = []; seen.set(key, it); out.push(it);
});
out.sort(compare);
return out;
}
function compare(a, b) {
const ci = (c) => (COLOUR_ORDER.indexOf(c) + 1 || 99);
return ci(a.colour) - ci(b.colour) || a.tail.localeCompare(b.tail) || a.lineage.localeCompare(b.lineage) ||
(b.age ?? -1) - (a.age ?? -1) || (a.name || "").localeCompare(b.name || "");
}
// ---------------------------------------------------------------- browser UI
function mount(opts) {
const $ = (q) => document.querySelector(q);
const esc = (x) => String(x ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const cssVar = (n) => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
const DV = { Red: "--dr-red", Green: "--dr-green", Orange: "--dr-orange", Brown: "--dr-brown", Blue: "--dr-blue", Black: "--dr-black" };
const st = { all: [], label: "", f: { colour: "", tail: "", lineage: "", sex: "", q: "" }, bundled: null };
function load(raw, label) { st.all = build(raw); st.label = label; st.f = { colour: "", tail: "", lineage: "", sex: "", q: "" }; ["reg-colour", "reg-tail", "reg-lineage", "reg-sex", "reg-q"].forEach((id) => ($("#" + id).value = "")); render(); }
const filtered = () => st.all.filter((d) => (!st.f.colour || d.colour === st.f.colour) && (!st.f.tail || d.tail === st.f.tail) &&
(!st.f.lineage || d.lineage === st.f.lineage) && (!st.f.sex || d.sex === st.f.sex) &&
(!st.f.q || [d.name, d.lineage].join(" ").toLowerCase().includes(st.f.q.toLowerCase())));
const sw = (c) => `<span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:var(${DV[c] || "--faint"});margin-right:6px;vertical-align:-1px;box-shadow:0 0 0 1px color-mix(in srgb, var(--ink) 25%, transparent)"></span>`;
const median = (a) => { const s = a.slice().sort((x, y) => x - y); const m = s.length >> 1; return s.length ? (s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2) : null; };
function fillSelect(id, values, label) {
const el = $("#" + id), cur = el.value;
el.innerHTML = `<option value="">${label}</option>` + values.map((v) => `<option>${esc(v)}</option>`).join("");
el.value = values.includes(cur) ? cur : "";
}
function render() {
const all = st.all, rows = filtered();
const colours = COLOUR_ORDER.filter((c) => all.some((d) => d.colour === c));
fillSelect("reg-colour", colours, "All colours");
fillSelect("reg-tail", TAILS.filter((t) => all.some((d) => d.tail === t)), "All tails");
fillSelect("reg-lineage", [...new Set(all.filter((d) => !st.f.colour || d.colour === st.f.colour).map((d) => d.lineage))].sort(), "All lineages");
fillSelect("reg-sex", [...new Set(all.map((d) => d.sex).filter(Boolean))].sort(), "Any sex");
const src = {}; all.forEach((d) => (src[d.source] = (src[d.source] || 0) + 1));
$("#reg-status").innerHTML = `<b>${all.length}</b> bonded dragons · ${Object.entries(src).map(([k, v]) => `${esc(k)} ${v}`).join(" · ")} · <span class="pill">${esc(st.label)}</span>`;
// colour x tail matrix
$("#reg-matrix").innerHTML = `<table><thead><tr><th>Colour</th>${TAILS.map((t) => `<th class="num">${t.replace("tail", "")}</th>`).join("")}<th class="num">Total</th></tr></thead><tbody>${colours.map((c) => {
const cs = rows.filter((d) => d.colour === c);
return `<tr><td>${sw(c)}${c}</td>${TAILS.map((t) => { const n = cs.filter((d) => d.tail === t).length; return `<td class="num"${n ? "" : ' style="color:var(--faint)"'}>${n || "·"}</td>`; }).join("")}<td class="num"><b>${cs.length}</b></td></tr>`;
}).join("")}</tbody></table>`;
// lineages
const lin = {};
rows.forEach((d) => { const k = d.colour + "|" + d.lineage; (lin[k] = lin[k] || []).push(d); });
$("#reg-lineages").innerHTML = `<table><thead><tr><th>Colour</th><th>Lineage</th><th class="num">Dragons</th><th class="num">Ages</th><th class="num">Median</th><th class="num">F / M</th></tr></thead><tbody>${Object.keys(lin).sort((a, b) => COLOUR_ORDER.indexOf(a.split("|")[0]) - COLOUR_ORDER.indexOf(b.split("|")[0]) || a.localeCompare(b)).map((k) => {
const g = lin[k], ages = g.map((d) => d.age).filter(Number.isFinite), [c, l] = k.split("|");
return `<tr><td>${sw(c)}${c}</td><td>${esc(l)}</td><td class="num">${g.length}</td><td class="num">${ages.length ? Math.min(...ages) + "–" + Math.max(...ages) : "–"}</td><td class="num">${ages.length ? median(ages) : "–"}</td><td class="num">${g.filter((d) => d.sex === "Female").length} / ${g.filter((d) => d.sex === "Male").length}</td></tr>`;
}).join("")}</tbody></table>`;
// main table, grouped by colour then tail
let lastGroup = "";
$("#reg-table").innerHTML = rows.length ? `<table><thead><tr><th>Colour</th><th>Tail</th><th>Lineage</th><th class="num">Age</th><th>Sex</th><th>Dragon</th><th>Rider's assignment</th><th>Source</th><th>Notes</th></tr></thead><tbody>${rows.map((d) => {
const g = d.colour + "|" + d.tail, head = g !== lastGroup; lastGroup = g;
return `<tr${head ? ' style="border-top:2px solid var(--line)"' : ""}><td>${sw(d.colour)}${esc(d.colour)}</td><td>${esc(d.tail)}</td><td>${esc(d.lineage)}</td><td class="num">${d.age ?? "–"}</td><td>${esc(d.sex)}</td><td><b>${esc(d.name)}</b></td><td class="small">${[d.wing, d.section, d.squad].filter(Boolean).map(esc).join(" · ") || "–"}</td><td class="small">${[d.source === "Register form" || d.also.includes("Register form") ? "form" : null, d.source_url ? `<a href="${esc(d.source_url)}" target="_blank" rel="noopener">result page</a>` : null].filter(Boolean).join(" + ")}${d.duplicates ? ` <span class="muted">(${d.duplicates + 1} entries merged)</span>` : ""}</td><td class="small muted">${esc(d.flags.join("; "))}</td></tr>`;
}).join("")}</tbody></table>` : `<p class="small muted" style="padding:12px">No dragons match these filters.</p>`;
$("#reg-count").textContent = `${rows.length} shown`;
renderGallery(rows);
}
// tail glyphs (24-unit box), drawn as simple original marks
const TAIL_GLYPH = {
Clubtail: '<path d="M5 19 L14 10" stroke-width="2.4"/><circle cx="16" cy="8" r="3.6" stroke="none" fill="currentColor"/>',
Daggertail: '<path d="M5 19 L8.5 15.5" stroke-width="2.4"/><path d="M7 14 L10 17" stroke-width="1.8"/><path d="M8.5 15.5 L19 5 L13.5 15.5 Z" fill="currentColor" stroke="none"/>',
Morningstartail: '<path d="M5 19 L11 13" stroke-width="2.4"/><circle cx="14.5" cy="9.5" r="3.4" fill="currentColor" stroke="none"/><path d="M14.5 3.5v2.5M14.5 13v2.5M8.5 9.5h2.5M18 9.5h2.5M10.3 5.3l1.8 1.8M16.9 11.9l1.8 1.8M18.7 5.3l-1.8 1.8M12.1 11.9l-1.8 1.8" stroke-width="1.6"/>',
Scorpiontail: '<path d="M5 19 C5 10 11 5.5 17 6.5 C20.5 7.2 20.5 11.5 17.5 12.5" stroke-width="2.2"/><path d="M17.5 12.5 L14.5 11 L16.2 15 Z" fill="currentColor" stroke="none"/>',
Swordtail: '<path d="M5 19 L19 5" stroke-width="2.6"/><path d="M6.5 13.5 L10.5 17.5" stroke-width="2"/><path d="M19 5 L16 6 L18 8 Z" fill="currentColor" stroke="none"/>',
};
function emblem(d) {
const col = cssVar(DV[d.colour] || "--faint");
const rgbv = (col.match(/[0-9a-f]{2}/gi) || ["80", "80", "80"]).slice(0, 3).map((h) => parseInt(h, 16));
const lum = col.startsWith("#") ? (0.299 * rgbv[0] + 0.587 * rgbv[1] + 0.114 * rgbv[2]) / 255 : 0.4;
const ink = lum > 0.6 ? "#14181d" : "#f4f1ea";
return `<svg viewBox="0 0 64 64" aria-hidden="true"><defs><radialGradient id="g${d.colour}" cx="35%" cy="30%" r="80%"><stop offset="0" stop-color="${col}" stop-opacity="0.85"/><stop offset="1" stop-color="${col}"/></radialGradient></defs>
<path d="M32 3 L57 17 L57 47 L32 61 L7 47 L7 17 Z" fill="url(#g${d.colour})" stroke="var(--ink)" stroke-opacity="0.25"/>
<path d="M32 9 L52 20 L52 44 L32 55 L12 44 L12 20 Z" fill="none" stroke="${ink}" stroke-opacity="0.35"/>
<g transform="translate(16 16) scale(1.35)" stroke="${ink}" fill="none" stroke-linecap="round" style="color:${ink}">${TAIL_GLYPH[d.tail] || ""}</g></svg>`;
}
function renderGallery(rows) {
const g = $("#reg-gallery");
if (!g) return;
const byC = {};
rows.forEach((d) => (byC[d.colour] = byC[d.colour] || []).push(d));
g.innerHTML = Object.keys(byC).sort((a, b) => COLOUR_ORDER.indexOf(a) - COLOUR_ORDER.indexOf(b)).map((c) => `
<div class="gal-group"><h3>${sw(c)}${esc(c)} dragons <span class="small muted" style="font-family:var(--font-body);letter-spacing:0">${byC[c].length}</span></h3>
<div class="cards">${byC[c].map((d) => `<div class="dcard" style="--dc: var(${DV[d.colour] || "--accent"})" title="${esc(d.flags.join("; "))}"><span class="age">${d.age ?? "?"} yrs</span>${emblem(d)}<span class="nm">${esc(d.name)}</span><span class="meta">${esc(d.sex || "")} ${esc(d.tail)}<br>${esc(d.lineage)} lineage${d.source_url ? `<br><a href="${esc(d.source_url)}" target="_blank" rel="noopener">result page</a>` : ""}</span></div>`).join("")}</div></div>`).join("") || `<p class="small muted">No dragons match these filters.</p>`;
}
document.querySelectorAll("#reg-view button").forEach((b) => b.addEventListener("click", () => {
document.querySelectorAll("#reg-view button").forEach((x) => x.setAttribute("aria-pressed", x === b));
$("#reg-gallery").hidden = b.dataset.v !== "cards";
$("#reg-table").hidden = b.dataset.v !== "table";
}));
function csv() {
const cols = ["colour", "tail", "lineage", "age", "sex", "name", "wing", "section", "squad", "source", "source_url", "lineage_raw", "flags"];
const q = (v) => { if (v === null || v === undefined) return ""; const s = Array.isArray(v) ? v.join("; ") : String(v); return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; };
return [cols.join(","), ...filtered().map((d) => cols.map((c) => q(d[c])).join(","))].join("\n");
}
[["reg-colour", "colour"], ["reg-tail", "tail"], ["reg-lineage", "lineage"], ["reg-sex", "sex"]].forEach(([id, k]) =>
$("#" + id).addEventListener("change", (e) => { st.f[k] = e.target.value; if (k === "colour") st.f.lineage = ""; render(); }));
$("#reg-q").addEventListener("input", (e) => { st.f.q = e.target.value.trim(); render(); });
$("#reg-copy").addEventListener("click", () => opts.copy(csv(), "register CSV"));
$("#reg-upload").addEventListener("change", async (e) => {
const f = e.target.files[0]; if (!f) return;
try {
const wb = XLSX.read(await f.arrayBuffer(), { type: "array", cellDates: true });
const ws = wb.Sheets[wb.SheetNames.find((n) => /form responses/i.test(n)) || wb.SheetNames[0]];
const headers = (XLSX.utils.sheet_to_json(ws, { header: 1, blankrows: false })[0] || []).map(String);
const rows = XLSX.utils.sheet_to_json(ws, { defval: null, raw: true });
load({ headers, rows, extra: st.bundled.extra }, `uploaded ${f.name} + Reddit result pages`);
opts.toast(`Loaded ${rows.length} register rows`);
} catch (err) { opts.toast("That file could not be read. Export the register sheet as .xlsx or .csv."); console.error(err); }
e.target.value = "";
});
fetch("data/register.json").then((r) => r.json()).then((raw) => { st.bundled = raw; load(raw, `bundled snapshot (${raw.source_file}, exported ${raw.exported})`); })
.catch((e) => ($("#reg-status").textContent = "The register data could not load."));
}
return { build, compare, mount, COLOUR_ORDER, TAILS, lev };
});
+194
View File
@@ -0,0 +1,194 @@
/* 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 = ["overview", "valley", "flow", "rare", "dragons", "deep", "share"];
function showTab(name, focus) {
if (!TABS.includes(name)) name = "overview";
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 */ }
try { history.replaceState(null, "", "#" + name); } catch (e) { /* ignore */ }
if (name === "flow" && 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 (TABS.includes(id)) { e.preventDefault(); showTab(id); 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" }); }
});
window.addEventListener("hashchange", () => { const h = location.hash.slice(1); if (TABS.includes(h)) showTab(h); });
const initial = (location.hash || "").slice(1);
showTab(TABS.includes(initial) ? initial : "overview");
// ------------------------------------------------------------ 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;
}
function renderOverview(state) {
const r = state.res;
const reach = r.factors.reach_hour.overall;
const cb = r.chance.blue_meadow, cs = r.chance.shadow;
const bulkB = stratum(cb, "Bulk"), bulkS = stratum(cs, "Bulk");
const blueSeen = bulkB && bulkB.n >= 30 ? bulkB : cb.overall;
const shadow = bulkS && bulkS.n >= 30 ? bulkS : cs.overall;
const encB = r.encounters.find((e) => e.context === "Blue (meadow)").overall;
const encK = r.encounters.find((e) => e.context === "Black (shadow)").overall;
const shadowP = shadow.k === 0 ? shadow.hi : shadow.p;
const tag = (txt) => `<span class="how">${txt}</span>`;
const cards = [
{ c: "--accent", big: pct(reach.p), what: "reach the hour alive", how: `${reach.k.toLocaleString()} of ${reach.n.toLocaleString()} logged runs made it past the cadets to the tree-or-valley choice.`, w: reach },
{ c: DV.Blue, big: `1 in ${oneIn(blueSeen.p)}`, what: "meadow visits has a Blue", how: blueSeen === bulkB ? `From riders who logged every run (${blueSeen.k}/${blueSeen.n}). The spreadsheet's headline says ${pct(cb.overall.p)}, inflated by lucky runs being shared more.` : `${blueSeen.k}/${blueSeen.n} meadow visits.`, w: blueSeen },
{ c: DV.Blue, big: pct(encB.p), what: "of Blue attempts end in a bond", how: `${encB.k} of ${encB.n}. Riders who reached a Blue were usually burned, even with the community's best answers.`, w: encB },
{ c: DV.Black, big: shadow.k === 0 ? `< ${pct(shadow.hi, 0)}` : `1 in ${oneIn(shadow.p)}`, what: "of tree climbs show the shadow", how: shadow === bulkS ? `Riders who logged every climb saw it ${shadow.k} times in ${shadow.n}. Form posts show more (${pct(cs.overall.p, 1)}), again because lucky runs get shared.` : `${shadow.k}/${shadow.n} tree climbs.`, w: shadow, scale: 1000 },
{ c: DV.Black, big: pct(encK.p), what: "of riders who meet the Black bond it", how: `${encK.k} of ${encK.n}. Getting there is the hard part.`, w: encK },
];
const dead = Object.entries(r.meta.outcomes).filter(([k]) => k.startsWith("Incinerated") || k.startsWith("Died")).reduce((a, [, v]) => a + v, 0);
cards.push({ c: "--death", big: dead.toLocaleString(), what: "riders sent to Malek", how: `${pct(dead / r.n)} of logged runs ended in fire or worse. Most were riders dying on purpose to try again.`, w: { k: dead, n: r.n }, 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>${c.scale ? "" : dots(c.w.k, c.w.n, cssVar(c.c))}${tag(c.how)}</div>`).join("");
const pBlueRun = blueSeen.p * encB.p, pBlackRun = shadowP * encK.p;
$("#combo").innerHTML = `
<div class="odd" style="--c: var(${DV.Blue})"><span class="big">≈ 1 in ${oneIn(pBlueRun)}</span><div><div class="what">valley runs ends bonded to a Blue</div>${tag(`A Blue has to show up (about ${pct(blueSeen.p)}) and then accept you (about ${pct(encB.p)}).`)}</div></div>
<div class="odd" style="--c: var(${DV.Black})"><span class="big">${shadow.k === 0 ? "<" : "≈"} 1 in ${oneIn(pBlackRun)}</span><div><div class="what">tree climbs ends bonded to a Black</div>${tag(`The shadow has to appear (${shadow.k === 0 ? "under " + pct(shadow.hi, 1) : "about " + pct(shadow.p, 1)}) and the Black has to accept you (about ${pct(encK.p)}).`)}</div></div>`;
// 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 mb = r.models.blue_meadow;
const routeSig = mb ? mb.terms.filter((t) => ["direction", "first_sighting", "resolution", "company"].includes(t.factor) && t.p < 0.05 && !/Unsure|Unknown|Multiple/.test(t.level)) : [];
const fork = r.factors.shadow.rows.find((x) => x.factor === "post_path" && x.level === "Forest");
const rest = r.factors.shadow.rows.filter((x) => x.factor === "post_path" && x.level !== "Forest");
const restK = rest.reduce((a, x) => a + x.k, 0), restN = rest.reduce((a, x) => a + x.n, 0);
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: routeSig.some((x) => x.factor === "direction") ? "Direction shows some link to the Blue." : "No sign that direction changes your Blue odds." },
{ 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: fork && restN ? `Shadows came from "deeper" ${pct(fork.p, 1)} of the time, vs ${pct(restK / restN, 1)} otherwise. A lead, not proof.` : "" },
{ t: "Tree or valley", d: "Climb the tallest tree, or walk to the valley centre.", v: "The tree holds Reds, Greens and the rare shadow. The valley holds Red, Orange, Brown and the meadow 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 Blue logged one 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.</p></div>
<div class="truth"><h3>No secret route to the Blue, so far</h3><p class="small">${routeSig.length ? `A few recorded choices showed a link: ${esc(routeSig.map((t) => t.term).join(", "))}.` : "Once that reporting bias is accounted for, none of the recorded choices (direction, first dragon, the cadets, company) changed how often the Blue appeared."} Choices the form doesn't record might still matter.</p></div>
<div class="truth"><h3>The right answer can still burn</h3><p class="small">Only ${pct(encB.p)} of Blue attempts bonded, about what the community's step-by-step odds predict. One death with the "right" answer doesn't mean the answer was wrong. Try again in four hours.</p></div>`;
$("#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.ValleyMap) window.ValleyMap.render(state);
},
showTab,
};
if (window.ThreshAtlas && window.ThreshAtlas.state && window.ThreshAtlas.state.res) window.AtlasUI.render(window.ThreshAtlas.state);
})();
+387
View File
@@ -0,0 +1,387 @@
/* valley.js — the watercolour valley map.
* Every place on the map is a step in a run. Trails are drawn from the coded runs (engine.js):
* thickness = riders who walked it, colour = share of those riders who reached the chosen outcome.
* Dashed trails are routes the community has described but the form does not record. */
(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" };
// painted-map dragon inks (darker than the UI tones so they read on gold paper)
const INK = { Red: "#b8293f", Green: "#3f7a3a", Orange: "#d06a1c", Brown: "#7a4e2e", Blue: "#2f5fb8", Black: "#2a2230" };
const PAPER = { ink: "#3b2416", halo: "#f6e6c4", trailLow: "#8a6446", death: "#c4471c" };
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); }
// ------------------------------------------------------------ places
// kind: start | way (a choice point) | dragon (a dragon is met here) | small (a choice made here)
const L = {
"comp:Alone": { x: 500, y: 736, name: "Alone", kind: "start", lab: "below", desc: "Enter the valley alone. The most common start, and the one that survives most often." },
"comp:1 Squadmate": { x: 380, y: 740, name: "One squadmate", kind: "start", lab: "below", desc: "Enter with one squadmate. You can later leave them and go on alone." },
"comp:2 Squadmates": { x: 620, y: 740, name: "Two squadmates", kind: "start", lab: "below", desc: "Enter with two squadmates. The first dragon is often deadlier for a group." },
"dir:West": { x: 190, y: 662, name: "West", sub: "toward the scent", kind: "way", lab: "left", desc: "Follow a scent west. A Brown, Green or Red finds you first." },
"dir:Center": { x: 500, y: 668, name: "Forest centre", kind: "way", lab: "right", desc: "Straight into the forest. Alone, a Red or a Brown finds you first." },
"dir:East": { x: 810, y: 662, name: "East", sub: "toward the roar", kind: "way", lab: "right", desc: "Toward the roar. Alone, a Red or an Orange finds you first. With one squadmate, a Green or an Orange." },
// first sightings (game roll)
"see:West:Red": { x: 110, y: 598, colour: "Red", kind: "dragon", first: true },
"see:West:Brown": { x: 185, y: 584, colour: "Brown", kind: "dragon", first: true },
"see:West:Green": { x: 262, y: 598, colour: "Green", kind: "dragon", first: true },
"see:Center:Red": { x: 448, y: 600, colour: "Red", kind: "dragon", first: true },
"see:Center:Brown": { x: 552, y: 600, colour: "Brown", kind: "dragon", first: true },
"see:East:Red": { x: 738, y: 598, colour: "Red", kind: "dragon", first: true },
"see:East:Orange": { x: 815, y: 584, colour: "Orange", kind: "dragon", first: true },
"see:East:Green": { x: 892, y: 598, colour: "Green", kind: "dragon", first: true },
scream: { x: 500, y: 512, name: "The scream", kind: "way", lab: "right", desc: "A scream in the trees. Help the squadmate fighting two cadets, walk away, or ignore it." },
bully: { x: 318, y: 462, name: "The bully fight", kind: "way", lab: "left", desc: "A squadmate is cornered by two cadets. Assess, even the numbers, or put yourself in the middle." },
"res:Killed the bullies yourself": { x: 222, y: 410, name: "Kill them", kind: "small", lab: "left", desc: "End the bullies yourself." },
"res:Squadmate's revenge": { x: 312, y: 398, name: "Squadmate's revenge", kind: "small", lab: "above", desc: "Let your squadmate take revenge." },
"res:Left bullies to the dragons": { x: 404, y: 410, name: "Dragons decide", kind: "small", lab: "right", desc: "Leave the bullies to the dragons." },
away: { x: 500, y: 440, name: "Walked away", kind: "small", lab: "right", desc: "Investigated the scream, then left them to it." },
wounded: { x: 684, y: 462, name: "The wounded cadet", kind: "way", lab: "right", desc: "Ignore the scream and you trip over a cadet missing a leg." },
"res:Tourniquet": { x: 600, y: 410, name: "Tourniquet", kind: "small", lab: "left", desc: "Use their belt as a tourniquet." },
"res:Left injured cadet": { x: 690, y: 398, name: "Leave them", kind: "small", lab: "above", desc: "Leave them to die." },
"res:Took their weapons": { x: 780, y: 410, name: "Take their weapons", kind: "small", lab: "right", desc: "Take their weapons and go." },
"fork:West": { x: 196, y: 336, name: "West fork", kind: "way", lab: "left", desc: "After the fight, the path splits: west." },
"fork:Forest": { x: 318, y: 318, name: "Deeper in", kind: "way", lab: "above", desc: "After the fight: deeper into the forest. Most recorded shadows came after this choice." },
"fork:East": { x: 432, y: 336, name: "East fork", kind: "way", lab: "right", desc: "After the fight, the path splits: east." },
hour: { x: 520, y: 272, name: "An hour's walk", sub: "the thorn", kind: "way", lab: "right", desc: "An hour of walking, and a thorn draws blood. No dragon bonds before this point." },
tree: { x: 316, y: 204, name: "The tallest tree", kind: "way", lab: "right", desc: "Climb for a view: a Red below, two Greens in a clearing and, very rarely, a shadow moving west." },
valley: { x: 694, y: 204, name: "Valley centre", kind: "way", lab: "left", desc: "Walk on to the valley centre." },
treeRed: { x: 168, y: 250, name: "The Red below", colour: "Red", kind: "dragon", lab: "left", desc: "Descend quickly onto a Red prowling under the tree. The hardest bond in the game." },
greens: { x: 124, y: 140, name: "Two Greens", colour: "Green", kind: "dragon", lab: "below", desc: "Two Greens in a clearing test you. A wrong answer sometimes brings an Orange or Brown to the rescue." },
stream: { x: 372, y: 142, name: "The shadow", sub: "a stream, a claw print", kind: "way", lab: "right", desc: "The rare third option at the tree. Follow the shadow west, past a stream and a claw print." },
redwood: { x: 452, y: 84, name: "Blue at the redwood", colour: "Blue", kind: "dragon", lab: "above", desc: "A Blue coiled around a redwood. Hold still and let it pass to reach the Black." },
black: { x: 262, y: 70, name: "Behind you", colour: "Black", kind: "dragon", lab: "left", desc: "A branch snaps behind you. Turn to face the threat." },
valleyRed: { x: 846, y: 250, name: "The valley Red", colour: "Red", kind: "dragon", lab: "below", desc: "A Red that has just incinerated another cadet. Most who choose to bond it succeed. Say it isn't your dragon to walk on to the meadow." },
meadow: { x: 742, y: 146, name: "The meadow", kind: "way", lab: "below", desc: "A meadow where an Orange and a Brown wait. Sometimes a Blue joins them." },
"meadow:Orange": { x: 652, y: 100, name: "Orange", colour: "Orange", kind: "dragon", lab: "left", desc: "The meadow Orange." },
"meadow:Brown": { x: 744, y: 80, name: "Brown", colour: "Brown", kind: "dragon", lab: "above", desc: "The meadow Brown." },
"meadow:Blue": { x: 836, y: 100, name: "Meadow Blue", colour: "Blue", kind: "dragon", lab: "right", desc: "The rare meadow Blue. Most riders who approach it are burned, even with the community's best answers." },
};
// routes described by the community that the form does not record
const KNOWN = [
["treeRed", "greens", "Wait and pursue the Green"],
["redwood", "greens", "Retreat, then find the Green"],
["redwood", "valley", "Retreat toward the valley"],
["comp:1 Squadmate", "comp:Alone", "Leave your squadmate"],
["comp:2 Squadmates", "comp:Alone", "Leave your squadmates"],
];
const SIGHT_NODES = new Set(Object.keys(L).filter((k) => k.startsWith("see:")));
function path(r) {
const s = [];
if (L["comp:" + r.company]) s.push("comp:" + r.company);
if (!["East", "West", "Center"].includes(r.direction)) return s;
s.push("dir:" + r.direction);
const sight = `see:${r.direction}:${r.first_sighting}`;
if (SIGHT_NODES.has(sight)) s.push(sight);
if (r.scream === "DIED at first sighting" || r.scream === "Unknown") return s;
s.push("scream");
if (r.scream === "Investigate & help") {
s.push("bully");
if (L["res:" + r.resolution]) s.push("res:" + r.resolution);
if (r.resolution.startsWith("DIED")) return s;
if (["Forest", "West", "East"].includes(r.post_path)) s.push("fork:" + r.post_path);
} else if (r.scream === "Ignore the scream") {
s.push("wounded");
if (L["res:" + r.resolution]) s.push("res:" + r.resolution);
} else if (r.scream === "Investigate & leave") s.push("away");
if (r.hour !== "Tree" && r.hour !== "Valley") return s;
s.push("hour");
if (r.hour === "Tree") {
s.push("tree");
if (r.branch === "Descend quickly: Red") s.push("treeRed");
else if (r.branch === "Descend slowly: two Greens") s.push("greens");
else if (r.branch === "Shadow (rare)") { s.push("stream"); if (r.enc_Blue || r.enc_Black) s.push("redwood"); if (r.enc_Black) s.push("black"); }
} else {
s.push("valley");
if (r.branch === "Valley Red") s.push("valleyRed");
else if (r.branch === "Passed the Red: meadow") {
s.push("meadow");
const tried = r.enc_Blue ? "Blue" : (r.outcome_color === "Orange" || r.outcome_color === "Brown") ? r.outcome_color : r.enc_Orange ? "Orange" : r.enc_Brown ? "Brown" : null;
if (tried) s.push("meadow:" + tried);
}
}
return s;
}
// ------------------------------------------------------------ painting
function defs(svg) {
const d = el("defs", {}, svg);
d.innerHTML = `
<linearGradient id="vm-sky" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#f3d69c"/><stop offset="0.35" stop-color="#e9c88f"/><stop offset="0.7" stop-color="#d9b07a"/><stop offset="1" stop-color="#c8955f"/>
</linearGradient>
<radialGradient id="vm-sun" cx="0.62" cy="0.12" r="0.55"><stop offset="0" stop-color="#fff3d1" stop-opacity="0.9"/><stop offset="1" stop-color="#fff3d1" stop-opacity="0"/></radialGradient>
<radialGradient id="vm-vignette" cx="0.5" cy="0.5" r="0.72"><stop offset="0.6" stop-color="#2a0f1c" stop-opacity="0"/><stop offset="1" stop-color="#2a0f1c" stop-opacity="0.55"/></radialGradient>
<filter id="vm-wash" x="-10%" y="-10%" width="120%" height="120%">
<feTurbulence type="fractalNoise" baseFrequency="0.022" numOctaves="3" seed="4" result="n"/>
<feDisplacementMap in="SourceGraphic" in2="n" scale="16" xChannelSelector="R" yChannelSelector="G" result="d"/>
<feGaussianBlur in="d" stdDeviation="0.7"/>
</filter>
<filter id="vm-wash2" x="-10%" y="-10%" width="120%" height="120%">
<feTurbulence type="fractalNoise" baseFrequency="0.05" numOctaves="2" seed="9" result="n"/>
<feDisplacementMap in="SourceGraphic" in2="n" scale="8" xChannelSelector="R" yChannelSelector="G"/>
</filter>
<filter id="vm-brush" x="-5%" y="-5%" width="110%" height="110%">
<feTurbulence type="fractalNoise" baseFrequency="0.09" numOctaves="2" seed="3" result="n"/>
<feDisplacementMap in="SourceGraphic" in2="n" scale="4" xChannelSelector="R" yChannelSelector="G"/>
</filter>
<filter id="vm-paper" x="0" y="0" width="100%" height="100%">
<feTurbulence type="fractalNoise" baseFrequency="0.85" numOctaves="2" seed="1" result="g"/>
<feColorMatrix in="g" type="matrix" values="0 0 0 0 0.36 0 0 0 0 0.24 0 0 0 0 0.14 0 0 0 0.55 -0.18"/>
</filter>
<filter id="vm-haze"><feGaussianBlur stdDeviation="10"/></filter>`;
}
function blob(g, x, y, r, fill, op, R) {
// irregular canopy blob from a few overlapping circles
for (let i = 0; i < 3; i++) el("circle", { cx: x + (R() - 0.5) * r * 0.9, cy: y + (R() - 0.5) * r * 0.6, r: r * (0.6 + R() * 0.45), fill, "fill-opacity": op }, g);
}
function paint(svg) {
const R = rng(21);
el("rect", { x: 0, y: 0, width: 1000, height: 780, fill: "url(#vm-sky)" }, svg);
el("rect", { x: 0, y: 0, width: 1000, height: 780, fill: "url(#vm-sun)" }, svg);
// far ridge and hazy hills
const far = el("g", { filter: "url(#vm-wash)" }, svg);
let d = "M-20 120";
for (let x = -20; x <= 1020; x += 60) d += ` Q${x + 30} ${40 + R() * 40} ${x + 60} ${90 + R() * 40}`;
el("path", { d: d + " L1020 -10 L-20 -10 Z", fill: "#c99a72", "fill-opacity": 0.55 }, far);
el("path", { d: "M-20 150 Q200 90 420 140 T820 120 T1020 150 L1020 200 L-20 200 Z", fill: "#d4a677", "fill-opacity": 0.45 }, far);
// forest: three depth tiers of canopy washes, kept out of the clearings
const clear = [[742, 100, 150, 85], [124, 140, 92, 58], [694, 205, 80, 44], [520, 272, 70, 32], [846, 250, 70, 40], [500, 740, 190, 46], [318, 455, 120, 60], [684, 455, 120, 60], [500, 660, 80, 30]];
const inClear = (x, y) => clear.some(([cx, cy, rx, ry]) => ((x - cx) / rx) ** 2 + ((y - cy) / ry) ** 2 < 1);
const tiers = [
{ y0: 120, y1: 330, n: 150, r: [10, 20], cols: ["#b39a63", "#a99158"], op: 0.32 },
{ y0: 300, y1: 560, n: 170, r: [12, 24], cols: ["#8e8a54", "#7f7e4b"], op: 0.4 },
{ y0: 520, y1: 780, n: 170, r: [14, 30], cols: ["#6c6b40", "#5b5c37", "#6b5a35"], op: 0.45 },
];
tiers.forEach((t, ti) => {
const g = el("g", { filter: "url(#vm-wash)" }, svg);
// tall pale trunks, like a sunlit wood
for (let i = 0; i < t.n * 0.25; i++) {
const x = R() * 1000, y = t.y0 + R() * (t.y1 - t.y0);
if (inClear(x, y)) continue;
el("rect", { x, y: y - 50 - ti * 10, width: 2 + ti * 1.5, height: 60 + ti * 14, fill: "#7a5c3c", "fill-opacity": 0.18 + ti * 0.07 }, g);
}
for (let i = 0; i < t.n; i++) {
const x = R() * 1000, y = t.y0 + R() * (t.y1 - t.y0);
if (inClear(x, y)) continue;
blob(g, x, y, t.r[0] + R() * (t.r[1] - t.r[0]), t.cols[Math.floor(R() * t.cols.length)], t.op, R);
}
});
// clearings: warm ochre light
const cg = el("g", { filter: "url(#vm-wash)" }, svg);
clear.forEach(([cx, cy, rx, ry]) => el("ellipse", { cx, cy, rx: rx * 0.85, ry: ry * 0.8, fill: "#f0cf93", "fill-opacity": 0.55 }, cg));
// mist bands
const mg = el("g", { filter: "url(#vm-haze)" }, svg);
[[230, 0.35], [380, 0.2], [560, 0.18]].forEach(([y, o]) => el("rect", { x: -40, y, width: 1080, height: 26, fill: "#fbe9c4", "fill-opacity": o }, mg));
// the stream
const sg = el("g", { filter: "url(#vm-wash2)" }, svg);
const stream = "M560 -10 C 520 40, 470 70, 420 112 S 330 170, 270 150 S 170 120, 110 220 S 40 320, -10 350";
el("path", { d: stream, fill: "none", stroke: "#7fa3a6", "stroke-width": 13, "stroke-opacity": 0.65, "stroke-linecap": "round" }, sg);
el("path", { d: stream, fill: "none", stroke: "#cfe1dc", "stroke-width": 3, "stroke-opacity": 0.6, "stroke-linecap": "round" }, sg);
// rock outcrop for the valley Red, standing stones by the meadow
const rk = el("g", { filter: "url(#vm-wash2)" }, svg);
el("path", { d: "M800 272 L826 236 L862 230 L892 262 L880 284 L812 288 Z", fill: "#6e5c63", "fill-opacity": 0.75 }, rk);
el("path", { d: "M826 236 L862 230 L870 246 L834 252 Z", fill: "#9b8790", "fill-opacity": 0.6 }, rk);
// the tallest tree and the redwood
const big = el("g", { filter: "url(#vm-wash2)" }, svg);
el("rect", { x: 312, y: 150, width: 9, height: 70, fill: "#5a3f28", "fill-opacity": 0.85 }, big);
[[316, 150, 30], [302, 172, 22], [332, 168, 22], [316, 124, 22]].forEach(([x, y, r]) => el("circle", { cx: x, cy: y, r, fill: "#46502e", "fill-opacity": 0.75 }, big));
el("rect", { x: 446, y: 40, width: 11, height: 56, fill: "#8a4430", "fill-opacity": 0.85 }, big);
[[452, 40, 20], [440, 54, 14], [464, 54, 14]].forEach(([x, y, r]) => el("circle", { cx: x, cy: y, r, fill: "#3f4a2b", "fill-opacity": 0.7 }, big));
}
function overlay(svg) {
el("rect", { x: 0, y: 0, width: 1000, height: 780, filter: "url(#vm-paper)", opacity: 0.45, style: "mix-blend-mode:multiply", "pointer-events": "none" }, svg);
el("rect", { x: 0, y: 0, width: 1000, height: 780, fill: "url(#vm-vignette)", "pointer-events": "none" }, svg);
}
// tiny original winged glyph for dragon places
const WING = "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";
// ------------------------------------------------------------ rendering
let target = "bond_Blue", selected = "meadow:Blue", lastState = null, tipEl = null;
const TGT = ["bond_Blue", "bond_Black", "see_Blue", "see_shadow", "bond_Red", "bond_Green", "bond_Orange", "bond_Brown", "bond_any"];
function tip(e, html) {
tipEl = tipEl || $("#tip");
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 = () => { if (tipEl) tipEl.hidden = true; };
function renderTargets() {
$("#valley-targets").innerHTML = TGT.map((t) => {
const c = E.TARGETS[t].color ? DV[E.TARGETS[t].color] : "--dr-any";
return `<button type="button" class="tchip${t.startsWith("bond_B") ? " featured" : ""}" data-vt="${t}" aria-pressed="${t === target}" style="--c: var(${c})"><span class="sw"></span>${esc(E.TARGETS[t].label)}</button>`;
}).join("");
$$("#valley-targets .tchip").forEach((b) => b.addEventListener("click", () => { target = b.dataset.vt; render(lastState); }));
}
function curve(A, B, bend) {
const mx = (A.x + B.x) / 2, my = (A.y + B.y) / 2, dx = B.x - A.x, dy = B.y - A.y;
return `M${A.x} ${A.y} Q${mx - dy * bend} ${my + dx * bend} ${B.x} ${B.y}`;
}
const isDeath = (r) => r.outcome === "Incinerated" || r.outcome === "Died before the hour";
function render(state) {
if (!state || !state.res) return;
lastState = state;
renderTargets();
const svg = $("#valley");
svg.setAttribute("viewBox", "0 0 1000 790");
svg.innerHTML = "";
defs(svg); paint(svg);
const T = E.TARGETS[target].fn;
const nodes = new Map(), edges = new Map();
state.runs.forEach((r) => {
const seq = path(r), hit = T(r) ? 1 : 0;
seq.forEach((id, i) => {
const n = nodes.get(id) || { id, n: 0, k: 0, runs: [], endDeaths: 0 };
n.n++; n.k += hit; n.runs.push(r);
if (i === seq.length - 1 && isDeath(r)) n.endDeaths++;
nodes.set(id, n);
if (i) { const key = seq[i - 1] + ">" + id; const e = edges.get(key) || { a: seq[i - 1], b: id, n: 0, k: 0 }; e.n++; e.k += hit; edges.set(key, e); }
});
});
const minN = state.minN || 10;
const ES = [...edges.values()];
const maxN = Math.max(1, ...ES.map((e) => e.n));
const pmax = Math.max(0.005, ...ES.filter((e) => e.n >= minN).map((e) => e.k / e.n));
const tcol = E.TARGETS[target].color ? INK[E.TARGETS[target].color] : "#8a3f6e";
$(".valley-shell").style.setProperty("--vt", cssVar(E.TARGETS[target].color ? DV[E.TARGETS[target].color] : "--dr-any"));
const colourOf = (e) => (e.n < minN ? "#a58a70" : mix(PAPER.trailLow, tcol, Math.pow(Math.min(1, e.k / e.n / pmax), 0.7)));
// known-but-untracked routes
const gK = el("g", { "pointer-events": "stroke" }, svg);
KNOWN.forEach(([a, b, label]) => {
const A = L[a], B = L[b];
const p = el("path", { d: curve(A, B, 0.18), fill: "none", stroke: PAPER.ink, "stroke-opacity": 0.45, "stroke-width": 2, "stroke-dasharray": "2 7", "stroke-linecap": "round" }, gK);
p.addEventListener("mousemove", (ev) => tip(ev, `<div class="t">${esc(label)}</div>A route the community has described. The form doesn't record it, so it has no numbers.`));
p.addEventListener("mouseleave", hideTip);
});
// trails
const gT = el("g", { filter: "url(#vm-brush)" }, svg);
ES.sort((a, b) => b.n - a.n).forEach((e) => {
const A = L[e.a], B = L[e.b];
if (!A || !B) return;
const w = 2 + 24 * Math.sqrt(e.n / maxN);
const d = curve(A, B, 0.08);
el("path", { d, fill: "none", stroke: PAPER.halo, "stroke-width": w + 3, "stroke-opacity": 0.45, "stroke-linecap": "round" }, gT);
const p = el("path", { d, fill: "none", stroke: colourOf(e), "stroke-width": w, "stroke-opacity": e.n >= minN ? 0.85 : 0.45, "stroke-linecap": "round" }, gT);
p.addEventListener("mousemove", (ev) => tip(ev, `<div class="t">${esc(name(e.a))} → ${esc(name(e.b))}</div>${e.n.toLocaleString()} riders<br>${esc(E.TARGETS[target].label)}: <b>${pct(e.k / e.n, 1)}</b> (${e.k}/${e.n})${e.n < minN ? "<br><i>Too few riders to read</i>" : ""}`));
p.addEventListener("mouseleave", hideTip);
});
// places
const gN = el("g", {}, svg);
const total = Math.max(1, ...[...nodes.values()].map((n) => n.n));
Object.entries(L).forEach(([id, P]) => {
const nd = nodes.get(id) || { n: 0, k: 0, runs: [], endDeaths: 0 };
const g = el("g", { class: "loc", tabindex: 0, role: "button", "aria-label": `${name(id)}: ${nd.n} riders` }, gN);
const sel = id === selected;
if (P.kind === "dragon") {
const r = 11 + 9 * Math.sqrt(nd.n / total);
el("circle", { cx: P.x, cy: P.y, r: r + 4, fill: PAPER.halo, "fill-opacity": 0.85, stroke: sel ? "#1d0a12" : INK[P.colour], "stroke-width": sel ? 3 : 1.6 }, g);
el("circle", { cx: P.x, cy: P.y, r, fill: "#fbf0d6", stroke: INK[P.colour], "stroke-width": 2.2 }, g);
el("path", { d: WING, fill: INK[P.colour], transform: `translate(${P.x - r * 0.82} ${P.y - r * 0.5}) scale(${(r * 1.64) / 100})` }, g);
} else if (P.kind === "start") {
el("path", { d: `M${P.x} ${P.y - 11} L${P.x + 9} ${P.y} L${P.x} ${P.y + 11} L${P.x - 9} ${P.y} Z`, fill: sel ? "#1d0a12" : PAPER.ink, stroke: PAPER.halo, "stroke-width": 2 }, g);
} else {
const r = P.kind === "small" ? 5 : 7 + 5 * Math.sqrt(nd.n / total);
el("circle", { cx: P.x, cy: P.y, r: r + 2.5, fill: PAPER.halo, stroke: sel ? "#1d0a12" : "none", "stroke-width": 2.5 }, g);
el("circle", { cx: P.x, cy: P.y, r, fill: P.kind === "small" ? "#7a5236" : PAPER.ink }, g);
}
// deaths that ended here
if (nd.endDeaths) {
const bx = P.x + (P.kind === "dragon" ? 18 : 10), by = P.y - (P.kind === "dragon" ? 16 : 10);
el("circle", { cx: bx, cy: by, r: 8.5, fill: PAPER.death, stroke: PAPER.halo, "stroke-width": 1.4 }, g);
const t = el("text", { x: bx, y: by + 3.2, "text-anchor": "middle", "font-size": 8.5, fill: "#fff3e0", "font-family": "var(--font-data)" }, g);
t.textContent = nd.endDeaths > 999 ? Math.round(nd.endDeaths / 100) / 10 + "k" : nd.endDeaths;
}
// labels (first sightings are labelled by their dragon glyph and tooltip only)
if (!P.first) {
const pos = P.lab || "right", off = P.kind === "dragon" ? 24 : 12;
let x = P.x, y = P.y + 4, anchor = "middle";
if (pos === "right") { x = P.x + off; anchor = "start"; }
else if (pos === "left") { x = P.x - off; anchor = "end"; }
else if (pos === "below") y = P.y + off + 12;
else if (pos === "above") y = P.y - off - 18;
const t1 = el("text", { x, y, "text-anchor": anchor, "font-family": "var(--font-display)", "font-size": P.kind === "small" ? 12.5 : 15, fill: PAPER.ink, "paint-order": "stroke", stroke: PAPER.halo, "stroke-width": 3.5, "stroke-linejoin": "round" }, g);
t1.textContent = P.name;
if (P.kind !== "small") {
const t2 = el("text", { x, y: y + 14, "text-anchor": anchor, "font-size": 11, fill: PAPER.ink, "fill-opacity": 0.85, "paint-order": "stroke", stroke: PAPER.halo, "stroke-width": 3, "font-family": "var(--font-body)" }, g);
t2.textContent = `${nd.n.toLocaleString()} riders${P.sub ? " · " + P.sub : ""}`;
}
}
const pick = () => { selected = id; render(state); };
g.addEventListener("click", pick);
g.addEventListener("keydown", (ev) => { if (ev.key === "Enter" || ev.key === " ") { ev.preventDefault(); pick(); } });
g.addEventListener("mousemove", (ev) => tip(ev, `<div class="t">${esc(name(id))}</div>${nd.n.toLocaleString()} riders${nd.endDeaths ? ` · ${nd.endDeaths} died here` : ""}<br>${esc(E.TARGETS[target].label)}: ${pct(nd.n ? nd.k / nd.n : null, 1)}`));
g.addEventListener("mouseleave", hideTip);
});
// sighting captions per direction
["West", "Center", "East"].forEach((dname) => {
const xs = Object.keys(L).filter((k) => k.startsWith(`see:${dname}:`)).map((k) => L[k]);
const cx = xs.reduce((a, p) => a + p.x, 0) / xs.length, cy = Math.min(...xs.map((p) => p.y)) - 26;
const t = el("text", { x: cx, y: cy, "text-anchor": "middle", "font-size": 10.5, "letter-spacing": "0.12em", fill: PAPER.ink, "fill-opacity": 0.8, "font-family": "var(--font-label)", "paint-order": "stroke", stroke: PAPER.halo, "stroke-width": 3 }, svg);
t.textContent = "FIRST DRAGON · ROLL";
});
// compass
const cr = el("g", { transform: "translate(52 726)", "aria-hidden": "true" }, svg);
el("circle", { r: 24, fill: PAPER.halo, "fill-opacity": 0.7, stroke: PAPER.ink, "stroke-opacity": 0.5 }, cr);
el("path", { d: "M0 -20 L5 0 L0 20 L-5 0 Z", fill: PAPER.ink }, cr);
const nT = el("text", { y: -28, "text-anchor": "middle", "font-size": 11, fill: PAPER.ink, "font-family": "var(--font-display)" }, cr); nT.textContent = "N";
overlay(svg);
renderCard(nodes, edges);
$("#valley-legend").innerHTML = `<span>Trail width = riders who walked it</span>
<span style="display:inline-flex;gap:6px;align-items:center">0% <span class="ramp" style="background:linear-gradient(90deg, ${PAPER.trailLow}, ${tcol})"></span> ${pct(pmax)}</span>
<span><span style="display:inline-block;width:12px;height:12px;border-radius:50%;background:${PAPER.death};vertical-align:-2px"></span> riders who died at that spot</span>
<span>Dotted = described by the community, not tracked by the form</span>
<span>Faded = fewer than ${minN} riders · positions are illustrative</span>`;
}
function name(id) {
const P = L[id];
if (!P) return id;
if (P.first) { const [, d, c] = id.split(":"); return `${c} dragon (first sighting, ${d === "Center" ? "forest centre" : d.toLowerCase()})`; }
return P.name;
}
function renderCard(nodes, edges) {
const P = L[selected], nd = nodes.get(selected) || { n: 0, k: 0, runs: [], endDeaths: 0 };
const card = $("#loc-card");
card.style.setProperty("--lc", P.colour ? cssVar(DV[P.colour]) : cssVar("--accent"));
const w = E.wilson(nd.k, nd.n);
const out = [...edges.values()].filter((e) => e.a === selected).sort((a, b) => b.n - a.n);
const outN = out.reduce((a, e) => a + e.n, 0);
const ends = {};
nd.runs.forEach((r) => {
const k = r.outcome === "Bonded" ? "Bonded " + r.outcome_color : r.outcome === "Incinerated" ? "Incinerated" : r.outcome === "Died before the hour" ? "Died before the hour" : "Not recorded";
ends[k] = (ends[k] || 0) + 1;
});
const order = ["Bonded Red", "Bonded Orange", "Bonded Brown", "Bonded Green", "Bonded Blue", "Bonded Black", "Incinerated", "Died before the hour", "Not recorded"];
const bar = (label, n, of, c) => `<div class="bar" style="--c:${c}"><span>${esc(label)}</span><i style="width:${(100 * n) / Math.max(1, of)}%"></i><span>${n} · ${pct(n / Math.max(1, nd.n))}</span></div>`;
const maxEnd = Math.max(1, ...Object.values(ends));
const P2 = P.first ? { desc: "The game rolls which dragon finds you first. Lower your eyes and keep still." } : P;
card.innerHTML = `<span class="eyebrow">${P.kind === "dragon" ? "A dragon waits here" : "Selected place"}</span><h3>${esc(name(selected))}</h3>
<p class="small muted">${esc(P2.desc || "")}</p>
<p class="small"><b>${nd.n.toLocaleString()}</b> logged runs reached this spot${nd.endDeaths ? `, and <b style="color:var(--ember)">${nd.endDeaths}</b> died here` : ""}. ${esc(E.TARGETS[target].label)}: <b>${pct(w.p, 1)}</b> of them (95% CI ${pct(w.lo, 1)}–${pct(w.hi, 1)}).</p>
${out.length ? `<span class="eyebrow">Where they went next</span><div class="bars">${out.map((e) => bar(name(e.b).replace(/ \(first sighting.*\)/, " first"), e.n, out[0].n, L[e.b].colour ? `var(${DV[L[e.b].colour]})` : "var(--accent)")).join("")}</div>` : ""}
<span class="eyebrow">How those runs ended</span><div class="bars">${order.filter((k) => ends[k]).map((k) => bar(k, ends[k], maxEnd, k.startsWith("Bonded") ? `var(${DV[k.split(" ")[1]]})` : k === "Incinerated" ? "var(--ember)" : "var(--faint)")).join("") || '<span class="small muted">No runs.</span>'}</div>`;
}
window.ValleyMap = { render, path, places: L };
})();