// The explorer's page logic: the seven-step walkthrough, the test cases, the honesty chart and the glossary, all
// filled from data/site.json, which was computed by Mat2Bot when this site was built.
import { Beaker, CrystalView, reducedMotion, webglOK } from "./viewer.js";
const $ = (s, el = document) => el.querySelector(s);
const $$ = (s, el = document) => [...el.querySelectorAll(s)];
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
const KEY = { strong: "k-strong", partial: "k-partial", hypo: "k-hypo", blocked: "k-blocked", none: "k-none" };
const MARK = { eliminated: "✓", open: "?", sustained: "!" };
const WHO = { robot: "Robot", person: "A person", outside: "Outside lab", missing: "Missing equipment" };
const ICON = {
robot: ' ',
person: ' ',
outside: ' ',
missing: ' ',
};
const AUDIT = {
crate: "Files intact, nothing added", documents: "Records well formed", safety: "Safety verdict anchored", evidence: "Sources read again",
sources: "Every source accounted for", parameters: "Conditions match their sources", science: "Chemistry recomputed",
categories: "Certainty worked out again", execution: "Lab verdicts worked out again", rules: "Every rule on the list",
explanations: "Every sentence backed by the record", report: "Report matches the record", amounts: "Amounts recomputed",
procedures: "Recipe values checked", ledger: "Tamper-evident log unbroken", summary: "Summary matches", outcome: "Open doubts left open",
authorization: "Nothing started without a person",
};
let site;
try {
site = await (await fetch("data/site.json")).json();
} catch (err) {
document.body.insertAdjacentHTML("afterbegin", '
The explorer could not load its data. Please reload the page.
');
throw err;
}
const gl = webglOK();
function fallback(canvas, crystal, text) {
const h = canvas.clientHeight;
const div = document.createElement("div");
div.className = "fallback";
div.style.minHeight = `${Math.max(h, 220)}px`;
div.innerHTML = crystal ? ` ` : `${esc(text)}
`;
canvas.replaceWith(div);
}
function view(canvas, crystal, opts) {
if (!gl) { fallback(canvas, crystal); return null; }
try {
const v = new CrystalView(canvas, opts);
v.show(crystal);
return v;
} catch {
fallback(canvas, crystal);
return null;
}
}
// ---------------------------------------------------------------- the hero
view($("#hero-canvas"), "zincite", { speed: 0.16, zoom: 1.08 });
// ---------------------------------------------------------------- the seven steps
const caseById = Object.fromEntries(site.cases.map((c) => [c.id, c]));
const calcite = caseById.b2_caco3_calcite;
const order = { eliminated: 0, open: 1, sustained: 2 };
const shown = [...calcite.doubts].sort((a, b) => order[a.status] - order[b.status]);
const pick = [...shown.filter((d) => d.status === "eliminated").slice(0, 3), ...shown.filter((d) => d.status !== "eliminated").slice(0, 3)];
$("#stage-doubts").innerHTML = pick.map((d, i) =>
`${MARK[d.status]} ${esc(d.text)}${esc(d.words)} `).join("");
const robotLab = (caseById.b1c_kcl_antisolvent_vcw001.labs || []).find((l) => l.id === "vialbot");
$("#stage-recipe").innerHTML = (robotLab?.steps || []).slice(0, 8).map((s, i) =>
`${ICON[s.who]} ${esc(s.step)}${WHO[s.who]} `).join("");
const seen = new Map();
for (const c of calcite.audit.checks) {
const prev = seen.get(c.name);
if (!prev || (prev === "PASS" && c.verdict !== "PASS")) seen.set(c.name, c.verdict);
}
$("#stage-audit").innerHTML = [...seen].filter(([n]) => AUDIT[n]).slice(0, 10).map(([n, v], i) =>
`${esc(AUDIT[n])}${v === "PASS" ? "" : v === "NOT_RUN" ? " (not applicable here)" : " (not re-run here)"} `).join("");
const ANGLE = { blocked: -67.5, hypo: -22.5, partial: 22.5, strong: 67.5 };
function needle() {
const n = $("#stage-gauge .needle");
n.style.transform = "rotate(-90deg)";
requestAnimationFrame(() => requestAnimationFrame(() => { n.style.transform = `rotate(${ANGLE[calcite.verdict.key] ?? 0}deg)`; }));
$("#gauge-verdict").innerHTML = `Test case 4, calcite: ${esc(calcite.verdict.words)} . ${esc(calcite.verdict.why)}`;
}
let stageCrystal = null;
let beaker = null;
let stepNow = -1;
const steps = $$(".step");
const layers = $$(".layer");
function setStep(i) {
if (i === stepNow) return;
stepNow = i;
steps.forEach((s, k) => s.classList.toggle("on", k === i));
layers.forEach((l, k) => l.classList.toggle("on", k === i));
if (i === 0) {
stageCrystal ||= view($("#stage-crystal"), "zincite", { speed: 0.3 });
stageCrystal?.play();
} else stageCrystal?.pause();
if (i === 2) {
if (!beaker && gl) {
try { beaker = new Beaker($("#stage-beaker"), { onTemperature: thermo }); } catch { fallback($("#stage-beaker"), null, "This browser cannot show the 3D beaker."); }
} else if (!gl && $("#stage-beaker")) fallback($("#stage-beaker"), null, "This browser cannot show the 3D beaker.");
beaker?.play();
} else beaker?.pause();
if (i === 4) needle();
}
const watch = new IntersectionObserver((es) => {
for (const e of es) if (e.isIntersecting) setStep(Number(e.target.dataset.step));
}, { rootMargin: "-42% 0px -42% 0px" });
steps.forEach((s) => watch.observe(s));
setStep(0);
const NOTE = {
zincite: "Wurtzite: each zinc atom sits among four oxygen atoms.",
"zno-rocksalt": "Rock salt: each zinc atom sits among six oxygen atoms, about 20 % denser.",
};
$$("[data-crystal]").forEach((b) => b.addEventListener("click", () => {
$$("[data-crystal]").forEach((x) => x.setAttribute("aria-pressed", String(x === b)));
stageCrystal?.show(b.dataset.crystal);
$("#stage-crystal-caption").textContent = NOTE[b.dataset.crystal];
}));
$("#stage-crystal-caption").textContent = NOTE.zincite;
function thermo(T) {
$("#thermo-value").textContent = `${Math.round(T)} °C`;
$("#thermo-fill").style.width = `${Math.max(0, Math.min(100, ((T - 15) / 50) * 100))}%`;
$("#beaker-cool").disabled = T < 21;
$("#beaker-heat").disabled = T > 59;
}
$("#beaker-cool").addEventListener("click", () => beaker?.cool());
$("#beaker-heat").addEventListener("click", () => beaker?.heat());
thermo(60);
// ---------------------------------------------------------------- the test cases
$("#case-grid").innerHTML = site.cases.map((c, i) => `
Test case ${i + 1}${c.family ? ` · ${esc(c.family)}` : ""}
${esc(c.title)} ${esc(c.what)}
${esc(c.verdict.words)}
`).join("");
$$(".tile").forEach((t) => t.addEventListener("click", () => openCase(t.dataset.case)));
const dialog = $("#case-dialog");
let caseView = null;
function plural(n, one, many) { return `${n} ${n === 1 ? one : many}`; }
function caseHTML(c, n) {
const doubts = c.doubts || [];
const notOut = doubts.filter((d) => d.status !== "eliminated");
const out = doubts.filter((d) => d.status === "eliminated");
const li = (d) => `${MARK[d.status]} ${esc(d.text)} (${esc(d.words)}) `;
const labs = (c.labs || []).map((l) => `
${esc(l.lab)} ${esc(l.words)} ${esc(l.why)}
Who does each step ${l.steps.map((s) =>
`${ICON[s.who]} ${esc(s.step)}${WHO[s.who]} `).join("")}
`).join("");
return `
Test case ${n}${c.family ? ` · ${esc(c.family)}` : ""}
${esc(c.title)}
${esc(c.what)}
The question ${esc(c.question)}
What Mat2Bot found ${esc(c.story)}
How sure it is ${esc(c.verdict.words)} ${esc(c.verdict.why)}
${c.safety && !c.family ? `Handling it ${esc(c.safety)}
` : ""}
${doubts.length ? `Doubts it checked
${plural(c.counts.eliminated, "ruled out", "ruled out")}
${plural(c.counts.open, "still open", "still open")}
${plural(c.counts.sustained, "confirmed", "confirmed")}
${notOut.map(li).join("")}
${out.length ? `The ${out.length} doubts it ruled out ` : ""}` : ""}
${(c.steps || []).length ? `The recipe, in short ${c.steps.map((s) => `${esc(s)} `).join("")} ` : ""}
${labs ? `Who could make it ${labs}
` : ""}
${(c.sources || []).length ? `Where the evidence comes from ${c.sources.map((s) => `${esc(s)} `).join("")} ` : ""}
${c.links.trace ? `How Mat2Bot got there
Each box is a stage Mat2Bot ran, from its own records. Open the full trail to click through every route, doubt, number and source.
` : ""}
Checked by the independent auditor
${{ PASS: "consistent", UNKNOWN: "partly re-checked", FAIL: "inconsistent" }[c.audit.verdict] || esc(c.audit.verdict)}
${plural(c.audit.passed, "check passed", "checks passed")}${c.audit.unknown ? `, ${c.audit.unknown} could not be checked here` : ""}${c.audit.not_applicable ? `, ${c.audit.not_applicable} not applicable` : ""}.
The audit re-derives the package from its own files; it does not check that the material's form is right or that the recipe works.
`;
}
function crystalCaption(name) {
const k = site.crystals[name];
const dots = Object.values(k.style).map((s) => ` ${esc(s.name)}`).join(" ");
const src = String(k.cod).startsWith("file:") ? "a generated cell, not a measured structure" : `measured structure, Crystallography Open Database ${esc(k.cod)}`;
return `${dots} ${esc(k.label)}: ${src} · drag to turn`;
}
const STAGE_WORDS = { M01: "Target", M02: "Evidence", M04: "Routes", M03: "By analogy", M05: "Science", M07: "The case", M08: "Recipe", LAB: "Labs", AUDIT: "Audit" };
const EXEC_WORDS = { completed: ["ran", "ok"], skipped: ["skipped", "off"], refused: ["stopped", "warn"], failed: ["failed", "bad"], not_run: ["see below", "off"] };
function fillTrail(box) {
fetch(box.dataset.trace).then((r) => (r.ok ? r.json() : null)).then((t) => {
if (!t) { box.innerHTML = 'The trail could not be loaded.
'; return; }
const stages = t.nodes.filter((n) => n.kind === "stage");
box.innerHTML = `${stages.map((s) => {
const w = EXEC_WORDS[s.execution] || [s.execution, "off"];
const kids = s.children.length;
return `${esc(STAGE_WORDS[s.stage] || s.stage)} ${esc(w[0])}${kids ? ` · ${kids}` : ""} `;
}).join("")} `;
}).catch(() => { box.innerHTML = 'The trail could not be loaded.
'; });
}
function openCase(id) {
const i = site.cases.findIndex((c) => c.id === id);
if (i < 0) return;
const c = site.cases[i];
$("#case-body").innerHTML = caseHTML(c, i + 1);
const trail = $("#case-body .trail");
if (trail) fillTrail(trail);
$("#case-crystal").innerHTML = crystalCaption(c.crystal);
if (!dialog.open) dialog.showModal();
$("#case-body").scrollTop = 0;
if (gl) {
if (!caseView) {
try { caseView = new CrystalView($("#case-canvas"), { speed: 0.22 }); } catch { fallback($("#case-canvas"), c.crystal); }
}
caseView?.show(c.crystal);
caseView?.play();
}
history.replaceState(null, "", `#case-${id}`);
}
dialog.addEventListener("close", () => {
caseView?.pause();
if (location.hash.startsWith("#case-")) history.replaceState(null, "", "#cases");
});
dialog.addEventListener("click", (e) => { if (e.target === dialog) dialog.close(); });
if (location.hash.startsWith("#case-")) openCase(location.hash.slice(6));
window.addEventListener("hashchange", () => { if (location.hash.startsWith("#case-")) openCase(location.hash.slice(6)); });
// ---------------------------------------------------------------- honesty
const COLORS = [["met", "Met", "#16a34a"], ["met (otherwise)", "Met by the stated fallback", "#4ade80"], ["partial", "Partly met", "#f59e0b"],
["deviation", "Missed, and explained", "#ef4444"], ["not run", "Not run (no data access)", "#64748b"]];
const counts = site.evaluation.counts;
$("#eval-total").textContent = site.evaluation.total;
$("#review-total").textContent = site.review_rounds.reduce((a, b) => a + b, 0);
$("#eval-legend").innerHTML = COLORS.filter(([k]) => counts[k]).map(([k, w, c]) => `${counts[k]} ${esc(w)} `).join("");
const cells = COLORS.flatMap(([k, , c]) => Array(counts[k] || 0).fill(c));
const waffle = $("#eval-waffle");
waffle.setAttribute("aria-label", COLORS.filter(([k]) => counts[k]).map(([k, w]) => `${counts[k]} ${w.toLowerCase()}`).join(", "));
waffle.innerHTML = cells.map((c, i) => ` `).join("");
new IntersectionObserver((es, o) => { if (es.some((e) => e.isIntersecting)) { waffle.classList.add("on"); o.disconnect(); } }, { threshold: 0.3 }).observe(waffle);
if (reducedMotion) waffle.classList.add("on");
// ---------------------------------------------------------------- glossary and footer
$("#glossary").innerHTML = site.glossary.map((g) => `
${esc(g.term)} ${esc(g.text)} `).join("");
$("#foot-build").textContent = `Results computed by Mat2Bot ${site.version} (build ${site.commit}, ${site.built}).`;