build-before-after.mjs
Build entry point for pairs or the existing screen Pass/Fix mode.
#!/usr/bin/env node
// Before/after comparison page for a guided setup flow (docs/design/guided-setup-flows/PLAYBOOK.md,
// step 12). Generalised from clients/photo-booth-app/design-review/staff-setup-2026-09-24/
// build-looks-page.mjs, which made the page the founder called "beautiful" on 2026-09-25.
//
// node build-before-after.mjs --manifest <path/to/looks.manifest.json> [--out <path/to/index.html>]
//
// Reads a manifest (see example.manifest.json and README.md), pairs <set>/<view>-<screen>.png across
// the sets by FILE NAME, and writes one self-contained HTML page (images referenced relatively) with
// a width filter, a Pass / Fix verdict and a note per pair, and "Copy review JSON" for REVIEW.md.
// No dependencies. Open the result from disk.
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
import { pathToFileURL } from "node:url";
const argv = process.argv.slice(2);
const arg = (name) => {
const eq = argv.find((a) => a.startsWith(`--${name}=`));
if (eq) return eq.slice(name.length + 3);
const i = argv.indexOf(`--${name}`);
return i >= 0 ? argv[i + 1] : undefined;
};
if (argv.includes("--help") || !arg("manifest")) {
console.log("usage: node build-before-after.mjs --manifest <looks.manifest.json> [--out <index.html>]");
process.exit(arg("manifest") ? 0 : 2);
}
const manifestPath = resolve(arg("manifest"));
const m = JSON.parse(readFileSync(manifestPath, "utf8"));
// Brand/output comparisons use the same front door, with the calibrated SceneBench review controls.
if (Array.isArray(m.pairs)) {
const {buildComparisonBench} = await import('./comparison-bench.mjs');
console.log(JSON.stringify(buildComparisonBench(m, manifestPath, arg('out'))));
process.exit(0);
}
const fail = (msg) => {
console.error(`build-before-after: ${msg}`);
process.exit(1);
};
for (const key of ["title", "sets", "views", "screens"]) if (!m[key]) fail(`manifest is missing "${key}"`);
if (!Array.isArray(m.sets) || m.sets.length < 2) fail(`"sets" needs at least two entries (before and after)`);
const root = resolve(dirname(manifestPath), m.root ?? "looks");
const out = resolve(arg("out") ?? join(root, "index.html"));
const outDir = dirname(out);
// A src the page can load from wherever it was written.
const srcOf = (abs) => {
const rel = relative(outDir, abs);
if (!rel || isAbsolute(rel)) return pathToFileURL(abs).href; // another drive
return rel.split("\\").join("/").split("/").map(encodeURIComponent).join("/");
};
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
// Plain text with `code` spans and *emphasis*, nothing else.
const inline = (s) => esc(s).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*([^*]+)\*/g, "<em>$1</em>");
const standIn = new Set(m.standInCamera ?? []);
const views = new Map(m.views.map((v) => [v.id, v]));
let missingAfter = 0;
let pairs = 0;
function cell(set, file) {
const abs = join(root, set.dir, file);
if (existsSync(abs)) {
const src = srcOf(abs);
return `<a href="${src}" target="_blank"><img loading="lazy" src="${src}" alt="${esc(set.label)}: ${esc(file)}"></a><code>${esc(set.dir)}/${esc(file)}</code>`;
}
const isFirst = set === m.sets[0];
if (!isFirst) missingAfter += 1;
return `<div class="none">${isFirst ? "Did not exist before" : "Not shot"}</div>`;
}
function section({ key, view, caption, sub, file, screenId }) {
pairs += 1;
const cam = screenId && standIn.has(screenId) ? ` <span class="tag">stand-in camera</span>` : "";
const figs = m.sets.map((s) => `<figure><figcaption>${esc(s.label)}</figcaption>${cell(s, file)}</figure>`).join("");
return `<section data-view="${esc(view)}" data-key="${esc(key)}">
<h2>${inline(caption)}${cam} <small>${esc(sub)}</small></h2>
<div class="pair" style="--cols:${m.sets.length}">${figs}</div>
<div class="verdict"><button type="button" data-v="pass">Pass</button><button type="button" data-v="fix">Fix</button><input type="text" placeholder="What is wrong, and the rubric item (R1-R20)" aria-label="Note for ${esc(caption)}, ${esc(sub)}"></div>
</section>`;
}
let rows = "";
for (const s of m.screens) {
for (const v of m.views) {
if (s.views && !s.views.includes(v.id)) continue;
const file = `${v.id}-${s.id}.png`;
if (!m.sets.some((set) => existsSync(join(root, set.dir, file)))) continue;
rows += section({ key: `${v.id}/${s.id}`, view: v.id, caption: s.caption, sub: v.label, file, screenId: s.id }) + "\n";
}
}
for (const x of m.extras ?? []) {
if (!views.has(x.view)) views.set(x.view, { id: x.view, label: x.filter ?? x.view });
rows += section({ key: `${x.view}/${x.file}`, view: x.view, caption: x.caption, sub: x.label ?? "", file: x.file, screenId: x.screen }) + "\n";
}
if (!pairs) fail(`no shots found under ${root} for any screen x view; check "root", the set dirs and the file names`);
// Optional: the printable twin's page count, from the shoot's shots.json.
let pagesLine = "";
if (m.pages?.from) {
try {
const shots = JSON.parse(readFileSync(join(root, m.pages.from), "utf8")).shots ?? [];
const n = shots.find((s) => s.name === (m.pages.shot ?? "print-pages"))?.pages;
pagesLine = n === 1 ? " The printed page lays out on one sheet of Letter." : ` <strong>The printed page laid out on ${n ?? "an unknown number of"} pages.</strong>`;
} catch {
pagesLine = " The printed page's page count was not recorded.";
}
}
const t = {
paper: "#f6f3ed", ink: "#183b30", muted: "#526356", line: "#d4d8cd", accent: "#f3b18b", deep: "#a74625",
paperDark: "#12291f", inkDark: "#f6f3ed", mutedDark: "#b9c4bb", lineDark: "#2c4f43",
...(m.theme ?? {}),
};
const storeKey = `before-after:${m.title}:${m.sets.map((s) => s.ref ?? s.dir).join("..")}`;
const filters = [["all", "All"], ...[...views.values()].map((v) => [v.id, v.filter ?? v.label.split(/\s\d/)[0]])];
const narrow = [...views.values()].filter((v) => v.maxWidth).map((v) => `section[data-view="${v.id}"] img { max-width:${Number(v.maxWidth)}px; }`).join("\n");
const html = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${esc(m.pageTitle ?? m.title.replace(/[,.]\s*$/, "") + ", before and after")}</title>
<style>
:root { --paper:${t.paper}; --ink:${t.ink}; --muted:${t.muted}; --line:${t.line}; --accent:${t.accent}; --deep:${t.deep}; }
@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { --paper:${t.paperDark}; --ink:${t.inkDark}; --muted:${t.mutedDark}; --line:${t.lineDark}; } }
:root[data-theme="dark"] { --paper:${t.paperDark}; --ink:${t.inkDark}; --muted:${t.mutedDark}; --line:${t.lineDark}; }
* { box-sizing: border-box; }
body { margin:0; background:var(--paper); color:var(--ink); font:16px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }
header { padding:28px 16px 12px; max-width:1500px; margin:0 auto; }
h1 { font-family:Georgia, serif; font-weight:400; letter-spacing:-0.04em; font-size:clamp(28px,4vw,44px); margin:0 0 8px; }
h1 em, h2 em { font-style:italic; }
header p { color:var(--muted); max-width:72ch; margin:0 0 12px; }
header p code { display:inline; }
nav { display:flex; gap:8px; flex-wrap:wrap; margin:12px 0 0; align-items:center; }
nav button, .verdict button, .tools button { font:inherit; font-size:14px; padding:7px 14px; border:1px solid var(--line); background:transparent; color:var(--ink); border-radius:3px; cursor:pointer; }
nav button[aria-pressed="true"] { background:var(--ink); color:var(--paper); border-color:var(--ink); }
button:focus-visible, input:focus-visible { outline:3px solid var(--deep); outline-offset:2px; }
.tools { display:flex; gap:10px; flex-wrap:wrap; align-items:center; margin:14px 0 0; font-size:14px; color:var(--muted); }
main { max-width:1500px; margin:0 auto; padding:0 16px 60px; }
section { border-top:1px solid var(--line); padding:22px 0; }
section[hidden] { display:none; }
h2 { font-family:Georgia, serif; font-weight:400; font-size:22px; letter-spacing:-0.02em; margin:0 0 12px; }
h2 small { font-family:ui-sans-serif, system-ui, sans-serif; font-size:13px; color:var(--muted); letter-spacing:0; margin-left:8px; }
.tag { font:600 11px/1 ui-sans-serif, system-ui, sans-serif; letter-spacing:.12em; text-transform:uppercase; color:var(--deep); border:1px solid var(--deep); border-radius:3px; padding:4px 6px; vertical-align:middle; margin-left:8px; }
.pair { display:grid; grid-template-columns:repeat(var(--cols), minmax(0,1fr)); gap:20px; align-items:start; }
@media (max-width:700px) { .pair { grid-template-columns:1fr; } }
figure { margin:0; min-width:0; }
figcaption { font-size:12px; font-weight:600; letter-spacing:.14em; text-transform:uppercase; color:var(--muted); margin:0 0 6px; }
img { display:block; width:100%; height:auto; max-height:1400px; object-fit:contain; object-position:top left; border:1px solid var(--line); background:#fff; }
${narrow}
code { display:block; font-size:12px; color:var(--muted); margin-top:4px; word-break:break-all; }
.none { border:1px dashed var(--line); color:var(--muted); padding:40px 16px; text-align:center; font-size:14px; }
.verdict { display:flex; gap:8px; margin-top:12px; flex-wrap:wrap; }
.verdict input { flex:1 1 260px; min-width:0; font:inherit; font-size:14px; padding:7px 10px; border:1px solid var(--line); border-radius:3px; background:transparent; color:var(--ink); }
.verdict button[aria-pressed="true"][data-v="pass"] { background:var(--ink); color:var(--paper); border-color:var(--ink); }
.verdict button[aria-pressed="true"][data-v="fix"] { background:var(--deep); color:#fff; border-color:var(--deep); }
footer { color:var(--muted); font-size:13px; text-align:center; padding:0 16px 30px; }
</style>
</head>
<body>
<header>
<h1>${inline(m.title)} <em>${inline(m.titleEm ?? "before and after")}</em></h1>
<p>${inline(m.intro ?? "")} ${m.sets.map((s) => `${esc(s.label)} is ${s.ref ? `<code>${esc(s.ref)}</code>` : `<code>${esc(s.dir)}/</code>`}`).join("; ")}.${pagesLine}</p>
<nav aria-label="Filter by width">${filters.map(([f, l], i) => `<button type="button" data-f="${esc(f)}" aria-pressed="${i === 0}">${esc(l)}</button>`).join("")}
<button type="button" data-f="unscored" aria-pressed="false">Not scored yet</button><button type="button" data-f="fix" aria-pressed="false">Marked Fix</button></nav>
<div class="tools"><span id="tally" aria-live="polite"></span><button type="button" id="copy">Copy review JSON</button><button type="button" id="clear">Clear verdicts</button></div>
</header>
<main>
${rows}</main>
<footer>${inline(m.footer ?? "Shot by the flow's shoot-looks.mjs; page by build-before-after.mjs (client-factory docs/design/guided-setup-flows).")} <span aria-hidden="true" title="one step at a time">✳</span></footer>
<script>
(() => {
const KEY = ${JSON.stringify(storeKey)};
let state = {};
try { state = JSON.parse(localStorage.getItem(KEY) || "{}"); } catch { state = {}; }
const save = () => { try { localStorage.setItem(KEY, JSON.stringify(state)); } catch {} };
const secs = [...document.querySelectorAll("main section")];
const tally = document.getElementById("tally");
const paint = () => {
let p = 0, f = 0;
for (const s of secs) {
const v = state[s.dataset.key]?.verdict;
s.dataset.verdict = v || "";
s.querySelectorAll(".verdict button").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.v === v)));
if (v === "pass") p++; else if (v === "fix") f++;
}
tally.textContent = p + " pass, " + f + " fix, " + (secs.length - p - f) + " not scored, of " + secs.length;
};
for (const s of secs) {
const key = s.dataset.key;
const input = s.querySelector(".verdict input");
input.value = state[key]?.note || "";
s.querySelectorAll(".verdict button").forEach((b) => b.addEventListener("click", () => {
const cur = state[key]?.verdict;
state[key] = { ...(state[key] || {}), verdict: cur === b.dataset.v ? undefined : b.dataset.v };
save(); paint();
}));
input.addEventListener("input", () => { state[key] = { ...(state[key] || {}), note: input.value }; save(); });
}
const bs = [...document.querySelectorAll("nav button")];
bs.forEach((b) => b.addEventListener("click", () => {
bs.forEach((x) => x.setAttribute("aria-pressed", String(x === b)));
const f = b.dataset.f;
for (const s of secs) {
const v = s.dataset.verdict;
s.hidden = !(f === "all" || s.dataset.view === f || (f === "unscored" && !v) || (f === "fix" && v === "fix"));
}
}));
document.getElementById("copy").addEventListener("click", async (e) => {
const scores = secs.map((s) => ({ key: s.dataset.key, verdict: state[s.dataset.key]?.verdict || null, note: state[s.dataset.key]?.note || "" }));
const text = JSON.stringify({ page: document.title, at: new Date().toISOString(), pass: scores.filter((x) => x.verdict === "pass").length, fix: scores.filter((x) => x.verdict === "fix").map((x) => x.key + (x.note ? ": " + x.note : "")), unscored: scores.filter((x) => !x.verdict).length, scores }, null, 2);
try { await navigator.clipboard.writeText(text); e.target.textContent = "Copied"; } catch { window.prompt("Copy this:", text); }
setTimeout(() => { e.target.textContent = "Copy review JSON"; }, 1500);
});
document.getElementById("clear").addEventListener("click", () => { if (confirm("Clear every verdict and note on this page?")) { state = {}; save(); secs.forEach((s) => (s.querySelector(".verdict input").value = "")); paint(); } });
paint();
})();
</script>
</body>
</html>
`;
writeFileSync(out, html);
console.log(JSON.stringify({ ok: true, out, pairs, missingAfter, sets: m.sets.map((s) => s.dir) }));
if (missingAfter) console.error(`note: ${missingAfter} pair(s) have no shot in a later set ("Not shot"). Reshoot before scoring.`);