/* 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) => ({ "&": "&", "<": "<", ">": ">", '"': """ }[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 = `
${state.res.n.toLocaleString()} runs${state.res.n !== state.allRuns.length ? ` of ${state.allRuns.length.toLocaleString()}` : ""}${esc(src)}Form dates ${m.date_min || "?"} → ${m.date_max || "?"}${esc(state.dataLabel)}
${filt.length ? `Filtered: ${esc(filt.join(", "))}` : ""}
${state.missing.length ? `Questions not found in this file: ${esc(state.missing.join(", "))}` : ""}`;
}
// ------------------------------------------------------------ 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 = `
The meadow Blue appeared in ${rateTxt(cb.overall)} of logged meadow visits, but that figure is inflated. 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.
`;
t += `
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.` : ""}
`;
} else {
t = `
The meadow Blue appeared in ${rateTxt(cb.overall)} of logged meadow visits in the current selection. Compare the data-source filter settings to see how much this depends on who logged the runs.
After adjusting for reporting bias, ${sig.length === 1 ? "one recorded choice was" : sig.length + " recorded choices were"} linked to the Blue appearing: ${sig.map((s) => `${esc(s.term)} (OR ${fmtOR(s.or)}, 95% CI ${fmtOR(s.lo)}–${fmtOR(s.hi)}, p = ${fmtP(s.p)})`).join("; ")}.
`
: `
No recorded route choice changed the chance of the Blue appearing once reporting bias is held fixed. 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).
`;
t += `
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.
Reaching the Blue is not enough. Only ${rateTxt(encBlue.overall)} of Blue attempts ended in a bond (${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.
`]);
}
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 = `
The tree shadow showed up in ${rateTxt(cs.overall)} of logged tree climbs.${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 += `
`;
if (encBlack && encBlack.overall.n) t += `
Once the Black appears it is the easiest dragon to bond: ${rateTxt(encBlack.overall)}.
`;
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 = `
Shadow leads to test, not established: ${sh.map((x) => `${esc(labelFactor(x.factor))}: ${esc(x.level)} had the shadow in ${rateTxt(x)} vs the rest (OR ${fmtOR(x.or)}, q = ${fmtP(x.q)})`).join("; ")}.
`;
const att = ms && ms.terms.find((tm) => tm.factor === "attempt" && tm.level === "First attempt");
if (att) t += `
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.
`;
t += `
The cheapest test is a bulk log that records every tree climb, including the dull ones, with these choices noted.
For the common colours, intent matters more than route. 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.
${hasSel ? `${shown.n} of ${bn.n} runs in your selection` : `${bn.n} runs`} ${esc(E.TARGETS[state.target].label)}: ${pct(shown.p)} (${shown.k}/${shown.n}) 95% CI ${ci(sn)} Click to ${isSel ? "remove from" : "add to"} the selection`;
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) => `${esc(E.STAGES.find((s) => s.key === k).label)}: ${esc(v)}`).join("")).join("")
: `Showing all runs. Click a box to follow only the runs through it.`;
$$("#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 = `
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.
${pct(wa.p)}${kn(wa)} runs that could reach it · 95% CI ${ci(wa)}
${cmp}`;
}
function renderLegend(pmax, tcol, low) {
$("#legend").innerHTML = `
${state.widthMode === "traffic" ? "Band width = number of runs" : "Line width = chance of the outcome"}0% ${pct(pmax, 0)}Grey = fewer than ${state.minN} runsGold headings = steps the game rolls, not you`;
}
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 = `
Top routes for "${esc(E.TARGETS[state.target].label)}" routes with ≥ ${state.minN} runs, ranked by the lower end of the 95% interval
${rows.length ? `Overall rate in the comparison group: ${rateTxt(rk.overall)}. ${sigN} of ${rk.n_routes_tested} routes are better than the rest after adjusting for reporting bias and multiple testing. ${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."}
${pct(v.p)} (${kn(v)}) 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 = `
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.
Meadow Blue, standard answers
Survived step
${blue.map(([a, b]) => `
${a}
${b}
`).join("")}
All eight steps (product)
${pct(prod, 0)}
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.
Black (after the shadow and the tree Blue)
PDF outcome
Turn to face the threat → hold its gaze
66% bonded · 33% incinerated
Turn to face the threat → lower your eyes → try to mount → meet its gaze
`;
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 = `
${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.
${parts.map(([, n, c]) => ``).join("")}
${parts.map(([l, n, c]) => { const w = E.wilson(n, g.green_encounters); return `
${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 `
${esc(s)}
${n}
${pct(b.p)} ${kn(b)}
${pct(t.p)} ${kn(t)}
`; }).join("")}
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.
Rows flagged for contradictions
${m.n_flagged} of ${r.n} rows (${pct(m.n_flagged / r.n)}). Flagged rows stay in unless you drop them above.
${flags.map(([f, n]) => `
${esc(f)}
${n}
`).join("") || `
None
`}
How runs ended
${outs.map(([f, n]) => `
${esc(f)}
${n}
${pct(n / r.n)}
`).join("")}
"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.
Independence
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.
What the form does not ask
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.
`;
}
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 = `The bundled data could not load (${esc(e.message)}). Use "Load a newer export" to load the responses file.`; console.error(e); });
})();