Files
station-master/src/web/panels.ts
T
Jesse.MarkowitzandClaude Opus 5 e62ea54259 Four things the game counted and never said, and two it said wrong
Stays in the unshipped v0.7.9. Prompted by Jesse asking the general
question after two v0.7.9 fixes turned out to be the same shape:
actingPlayer existed and the Frame threw it away, and collisionsToday /
collisionsTotal rode the Frame for three releases with nothing drawing
them. So what else is computed, serialised and sent to nobody?

THE AUDIT, done rather than guessed. Every one of Frame's 59 top-level
fields grepped for a read across the seven renderers, then the same for
Tally's 26 members. 55 of 59 are read. Four are not.

tally.unloadsBegun was visible rather than merely unused. §9.1 makes
loading and unloading the same shape — begun, then carried through —
and the results screen printed "Loads still in the pipeline" for one
side and nothing for the other, reporting half of a symmetric
mechanism. tally.cardsDiscarded was counted by the engine and listed
beside "Cards drawn" and "Cards played" without it, though Gitea#9 made
throwing a Timetabled train away a deliberate move — a player CHOICE
the game counted and never reported. Both are reported now.

viewerSeat and overHandLimit are deferred by Jesse. The second is the
fullest version of the shape: engine computes it, view.ts puts it on
the Frame, session.ts declares it on the Session interface AND
implements it twice, and the only caller in the repo is its own test.
Four layers of plumbing, no consumer. The decision when it comes is
delete-or-document, not a patch.

Fixing the two turned up a third thing: resultsHtml draws
tallyHtml(report?.tally ?? f.tally), and report is f.official, so a
finished game reports the tally frozen at the official ending rather
than the live one. The first attempt at a test overrode f.tally alone,
changed nothing on screen, and failed for a reason unrelated to the
fix.

A SHOUTED KEYWORD IS NOT A SENTENCE. `EXTRA X18 started…` attributed to
a player rendered as `Player Solitaire eXTRA X18 started…`, and the
same happened to TRAIN 1 MADE UP and COLLISION. `record` folds a
narration's opening word into the middle of a sentence and did it with
a flat charAt(0).toLowerCase(). It now folds only a sentence-cased word
— ^[A-Z][a-z], a capital followed by a lower-case letter — which also
leaves X22 Pee-Dee alone, where a naive uppercase test gets it wrong
because '2'.toUpperCase() is '2'. It had been filed under Play Balance,
where it has no business being, which is how it survived a session that
had ruled balance work out of scope.

A REPLAYED SAVE NOW NARRATES WHAT THE LIVE GAME NARRATED. fromSave's
loop called record(game, result.events) with no actor, so every
restored save, every undo (which rebuilds through fromSave) and the
replay viewer stripped the "Player X" prefix off every attributed line.
submit attributes and fromMultiplayerSave attributes; this was the one
path of three that did not. One argument, with actor already computed
on the line above.

Why it survived: nothing ever compared a fromSave-built log against a
LIVE-played one. The single log-comparing test compares undo's rebuilt
log against another fromSave-built log — and undo itself rebuilds
through fromSave — so the gap cancelled out on both sides. The suite
was green with the bug in and green with it out. The new test plays a
game, saves it, restores it and asserts the two logs are identical:
the missing direction, not a new requirement.

All three fixes were confirmed to go RED with the fix reverted before
being called done.

884 tests pass, seventeen new.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YTaNBL1jVxNqgFdjHkHoo3
2026-08-30 19:44:25 -04:00

785 lines
40 KiB
TypeScript

/**
* The side panels a game is read from — cards, yards, blockers, facilities.
*
* SHARED between the playable page and the site's replay viewer, for the same reason the board
* renderers are: a replay is the game being WATCHED rather than played, so it should look like the
* game. The viewer had three panels against the play page's eight — no facilities, no blockers, no
* cards, no yards — which meant a replay could not answer "why is nothing moving?", the question a
* replay mostly exists to answer.
*
* Each function returns HTML rather than writing to the DOM, so the two pages can keep their own
* element ids and their own layout while drawing the same contents.
*/
import type { Frame } from '../sim/view.ts';
const esc = (s: string): string =>
String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c] ?? c);
/**
* A card, drawn as a card.
*
* `playable === false` crosshatches it: "not yet playable" had to be read, where a hatch is seen.
* The tooltip still explains WHY, which a hatch cannot. A replay passes null throughout — nothing
* there is playable, because nothing there is being played.
*/
export function cardRow(name: string, why: string, playable: boolean | null): string {
return (
`<div class="handcard${playable === false ? ' unplayable' : ''}"${why ? ` data-tip="${esc(why)}"` : ''} tabindex="0">` +
`<b>${esc(name)}</b></div>`
);
}
export function handHtml(f: Frame, canPlay: (boolean | null)[] = []): string {
// §6.2 — say so on the card itself. A player who cannot discard a train needs to read that on the
// train, not deduce it from a button that is not there. The sentence comes off the Frame
// (`handKeepWhy`) rather than being written here, because since Gitea#9 there are two of them and
// which one applies depends on the card AND the game's rules.
return f.hand.length
? f.hand
.map((h, i) => {
const what = f.handWhat[i] ?? '';
const held = f.handKeepWhy[i];
return cardRow(h, held ? [what, held].filter(Boolean).join(' · ') : what, canPlay[i] ?? null);
})
.join('')
: '<span class="dim">empty</span>';
}
/**
* The three Department piles and the Salvage Yard, each with its top card and its depth.
*
* Only the top card may ever be drawn, so the depth is a count and not a hint: everything below it
* is out of reach, and choosing where to discard is choosing what to put there.
*/
export function pilesHtml(f: Frame): string {
const pile = (label: string, top: string, depth: number, why: string, extra = '', slot = -1): string => {
const tip = [why, extra].filter(Boolean).join(' · ');
// A Department is a DROP TARGET for a discard. The attribute is always emitted; only the play
// page binds a click to it, and only while a card is waiting to be discarded — so the replay
// viewer draws exactly the same markup and nothing there is clickable.
const target = slot >= 0 ? ` data-dept="${slot}"` : '';
return (
`<div class="handcard"${target}${tip ? ` data-tip="${esc(tip)}"` : ''} tabindex="0">` +
`<div class="pilehd"><span>${esc(label)}</span><span class="depth">${depth}</span></div>` +
`<b>${esc(top)}</b></div>`
);
};
return (
f.departments
.map((d, i) => {
const depth = f.departmentDepth[i] ?? 0;
const under = depth - 1;
return pile(
`Dept ${i + 1}`,
d,
depth,
f.departmentsWhat[i] ?? '',
under > 0 ? `${under} card${under === 1 ? '' : 's'} buried beneath it and out of reach` : '',
i,
);
})
.join('') +
pile(
'Salvage',
f.salvage.top,
f.salvage.depth,
'',
'Played cards that did not stay on the board. Swept back into the Home Office deck, with the Departments, when the deck runs out.',
)
);
}
/** One yard, by car type. Loaded and empty are separate numbers because they do different jobs. */
export function yardHtml(rows: { type: string; loaded: number; empty: number }[]): string {
return rows.length === 0
? '<span class="dim">empty</span>'
: rows
.map(
(r) =>
`<span class="stock" data-tip="${esc(r.type)} — ${r.loaded} loaded, ${r.empty} empty">` +
`<b>${esc(r.type)}</b> ` +
// Each count is its own target: making up a train is choosing a car OF A TYPE AND A LOAD
// STATE, which is exactly what these two numbers already distinguish.
`<span class="ld" data-car="${esc(r.type)}" data-loaded="1">${r.loaded}</span>/` +
`<span class="mt" data-car="${esc(r.type)}" data-loaded="0">${r.empty}</span></span>`,
)
.join('');
}
/**
* THE TIMETABLE: twelve Stages of a Day, and which train is due out at each.
*
* Playing a train card rolls 1D12 for a slot, and the roll landed nowhere a player could see — the
* card was gone and the answer to "so when does it run?" was one line of history. The Frame has
* carried the twelve slots all along and only the standalone replay ever drew them.
*
* `justSet` is the slot filled by the roll being reported this frame, so it can be flashed. It marks
* the moment rather than the state: the highlight is gone by the next render, which is what makes it
* read as "that just happened" rather than "this is special".
*/
export function timetableHtml(f: Frame, justSet: number | null): string {
const slots = f.timetable
.map((t, k) => {
const stage = k + 1;
const cls = [
t !== null ? 'due' : '',
stage === f.stage ? 'now' : '',
stage < f.stage ? 'past' : '',
k === justSet ? 'fresh' : '',
]
.filter(Boolean)
.join(' ');
/**
* THE CARD ITSELF, not just the number.
*
* A train card is played once and then lives only as a number in a Timetable slot — but what
* it prints is what decides whether the train can be switched, worked by Porters, or loaded at
* all. Reported from play: "once a train card's been played, how would I see that particular
* train card again?" This is where the player already looks for that train.
*/
const tip =
t !== null
? `Train ${t} departs at Stage ${stage}. A train's NUMBER is its seniority and direction — odd runs west, even runs east — and the Stage it leaves is set by the 1D12 roll made when its card was played, so Train 8 at Stage 6 is normal.` +
(f.timetableWhat[k] ? `\n\nITS CARD — ${f.timetableWhat[k]}` : '')
: `Stage ${stage} — no train due out.`;
return (
`<div class="tt-slot ${cls}" data-tip="${esc(tip)}" tabindex="0">` +
`<span class="tt-s">${stage}</span>` +
`<span class="tt-t">${t !== null ? `T${t}` : '·'}</span></div>`
);
})
.join('');
return `<div class="tt">${slots}</div>`;
}
/**
* THE DAY THAT JUST ENDED — the body of the dialog `main.ts` puts up at every Day rollover.
*
* Reported as Gitea#10: "as the game rolls off the end of the day, you get a dialog saying such.
* Hard to keep track of time." The clock was on screen the whole time, but a Day turns over inside
* the automatic phases — between one click and the next — and neither the phase banner (2.6s) nor
* the announcement flash (4.2s) survives long enough to be noticed by someone reading the board.
* A modal is the point: it stops, and it waits to be dismissed.
*
* It is written from the FRAME AFTER the rollover, so `f.day` is the Day about to start and the one
* that ended is the Day before it. Standings are in Revenue order rather than seat order: the
* question at the end of a Day is who is ahead.
*/
export function dayEndHtml(f: Frame): string {
const ended = f.day - 1;
const left = f.days + f.extraDays - ended;
const ahead =
left <= 0
? '<p>That was the last Day on the timetable.</p>'
: `<p><b>Day ${f.day} of ${f.days + f.extraDays}</b> begins now — ${left} ${left === 1 ? 'Day' : 'Days'} left to run.</p>`;
return (
`<h3 class="dayend-h">Day ${ended} has ended</h3>` +
ahead +
standingsHtml(f) +
targetHtml(f) +
collisionsHtml(f)
);
}
// ---------------------------------------------------------------------------
// Shared between the Day-end dialog and the end-of-game results screen.
//
// Gitea#16 asked for the results screen and Gitea#10's dialog had already assembled most of it. The
// three blocks below are the overlap, factored out rather than written twice: the two screens report
// the same numbers about the same game, and the one thing they must never do is disagree.
// ---------------------------------------------------------------------------
/**
* Every player in Revenue order, the viewer marked.
*
* `winner` rings the player the OFFICIAL result named, which is not always the player at the top:
* in an extended game the standings keep moving after the result is settled, and showing the leader
* without saying who actually won would be the screen contradicting itself.
*/
function standingsHtml(f: Frame, winner: number | null = null): string {
const rows = [...f.players]
.sort((a, b) => b.revenue - a.revenue || a.seat - b.seat)
.map((p) => {
const marks =
(p.index === f.viewer ? ' <span class="dim">(you)</span>' : '') +
(p.index === winner ? ' <span class="wins">— winner</span>' : '');
return (
`<tr${p.index === f.viewer ? ' class="you"' : ''}><td>${esc(p.name)}${marks}</td>` +
`<td class="num">${p.revenue}</td></tr>`
);
})
.join('');
return `<table class="dayend-t"><tbody>${rows}</tbody></table>`;
}
/**
* The target is a COMBINED floor in every mode that sets one, so it is reported against the whole
* table's Revenue rather than the viewer's — showing one player's score against a four-player
* target reads as a hopeless position when the table may be comfortably ahead.
*/
function targetHtml(f: Frame): string {
if (f.minCombinedRevenue <= 0) return '';
const combined = f.players.reduce((n, p) => n + p.revenue, 0);
const met = combined >= f.minCombinedRevenue;
return (
`<p>Combined Revenue <b>${combined}</b> against a target of <b>${f.minCombinedRevenue}</b>` +
`${met ? ' — cleared.' : ' — short.'}</p>`
);
}
/**
* Only when the game is actually scored on collisions.
*
* Two conditions, both of them `advance.ts`'s own: `0` on a dial turns that check off, and the
* checks run in COMPETITIVE AND CO-OP ONLY (§3.4). A solitaire game carries the default dials on
* its config and enforces neither, so reporting a collision budget there would put a rule on
* screen that this game does not have.
*/
function collisionsHtml(f: Frame): string {
const scoredOnCollisions =
(f.mode === 'competitive' || f.mode === 'coop') &&
(f.maxCollisionsTotal > 0 || f.maxCollisionsPerDay > 0);
return scoredOnCollisions
? `<p>Collisions: <b>${f.collisionsToday}</b> today, <b>${f.collisionsTotal}</b> in all.</p>`
: '';
}
/**
* WHY THE GAME ENDED, as a sentence (Gitea#16).
*
* The page used to interpolate `outcome.reason` straight into the DOM, so a player who finished a
* game read the words `GAME OVER — revenueFloor`: an internal enum value, printed at the one moment
* the game has the player's whole attention. Each reason gets a sentence that says what actually
* happened, with this game's own numbers in it.
*
* EXPORTED for the developer replay recorder (`sim/replay.ts`), which was still printing
* `loss — revenueFloor` into its own heading a release after this was written — the same defect the
* issue was filed about, surviving in the one place nobody had looked (`TODO.md` #34). One
* implementation, so the two cannot say the game ended for different reasons.
*/
export function reasonSentence(f: Frame, o: NonNullable<Frame['outcome']>, day: number): string {
const combined = f.players.reduce((n, p) => n + p.revenue, 0);
switch (o.reason) {
case 'daysElapsed':
return `Day ${day} was the last on the timetable, and it ran out.`;
case 'revenueFloor':
return (
`The Division closed short: <b>${combined}</b> Revenue between everyone, against a floor of ` +
`<b>${f.minCombinedRevenue}</b>. §3.3 — miss the floor and the whole table loses, whoever ` +
`earned the most.`
);
case 'collisionFloor':
return (
`Too many collisions — <b>${f.collisionsToday}</b> in one Day and <b>${f.collisionsTotal}</b> ` +
`in all, against limits of ${f.maxCollisionsPerDay || '—'} and ${f.maxCollisionsTotal || '—'}. ` +
`§3.4 — the railroad was declared unsafe and the game was stopped.`
);
}
}
/** The rules this game was actually dealt under — Gitea#16's "what the rules of the game were". */
function rulesHtml(f: Frame): string {
const mode =
f.mode === 'coop' ? 'Co-op — the table scores together' :
f.mode === 'competitive' ? 'Competitive — highest Revenue wins' :
'Solitaire';
const optional = [
f.optionalRules.employeeRotation ? 'Employee Rotation' : null,
f.optionalRules.reducedVisibility ? 'Reduced Visibility' : null,
f.optionalRules.emergencyToolbox ? 'Emergency Toolbox' : null,
].filter((x): x is string => x !== null);
const r = f.houseRules.revenue;
const rows: [string, string][] = [
['Scoring', mode],
['Timetable', f.extraDays > 0
? `${f.days} Days, extended by ${f.extraDays} more`
: `${f.days} Day${f.days === 1 ? '' : 's'}`],
['Revenue floor', f.minCombinedRevenue > 0 ? `${f.minCombinedRevenue} combined` : 'none'],
['Collision limits', f.maxCollisionsPerDay > 0 || f.maxCollisionsTotal > 0
? `${f.maxCollisionsPerDay || '—'} per Day, ${f.maxCollisionsTotal || '—'} in all`
: 'not scored'],
['Pay rates', `${r.freightPerLoad} per load, ${r.passengerPerCoach} per coach, ${r.trainPerTransit} per transit`],
['Extras start', f.houseRules.extraStart === 'divisionPointsOnly' ? 'Division Points and the Interchange'
: f.houseRules.extraStart === 'ownOffice' ? 'those, plus your own Control Point'
: 'those, plus any Control Point'],
['Timetabled trains', f.houseRules.discardTimetabled ? 'may be discarded' : 'are never discarded'],
['Optional rules', optional.length ? optional.join(', ') : 'none'],
];
return `<h4 class="res-h">The rules in play</h4>${factTable(rows)}`;
}
/**
* A two-column table of plain-text facts.
*
* BOTH HALVES ESCAPED, exactly once, which is the only reason this is a shared helper rather than a
* template repeated twice. The rows it is given today are numbers and fixed phrases, but they are
* assembled from the Frame — and the day somebody adds a row carrying a player's name, or a facility
* label, the escaping has to already be here rather than be remembered.
*/
function factTable(rows: [string, string][]): string {
return (
'<table class="res-t"><tbody>' +
rows.map(([k, v]) => `<tr><td>${esc(k)}</td><td>${esc(v)}</td></tr>`).join('') +
'</tbody></table>'
);
}
/**
* THE RAILROAD — what actually happened out there, from `GameState.tally` (Gitea#16).
*
* Rows that would read zero for a reason (no passenger work in a game that had none, no collisions
* in a clean one) are dropped rather than printed as `0`: a screen of zeroes reads as a bug, and the
* absence of a line is the same information more quietly. A zero that is genuinely interesting —
* trains through the Division — stays.
*/
function tallyHtml(t: Frame['tally']): string {
const rows: [string, string][] = [['Trains through the Division', String(t.trainsCompleted)]];
if (t.trainsCompleted > 0) {
rows.push([
'Of those, worked en route',
`${t.trainsCompletedWithWork} of ${t.trainsCompleted}` +
(t.trainsCompletedWithWork === t.trainsCompleted ? ' — every one' : ''),
]);
}
const push = (label: string, n: number, detail = ''): void => {
if (n > 0) rows.push([label, `${n}${detail}`]);
};
push('Loads made up', t.loadsCompleted);
push('Loads broken', t.unloadsCompleted);
/**
* BOTH HALVES OF THE MEN | AT | WORK PIPELINE, not just the loading one.
*
* §9.1 makes loading and unloading the same shape — begun, then carried through — and the Tally
* has counted both since it was written. The screen reported only the loading side, so a player
* with three unloads part-finished at the final whistle was told nothing about them while the
* equivalent loads were listed. Found 2026-08-30 auditing which Frame fields nothing reads:
* `unloadsBegun` was one of four, and the only one whose absence was visible on screen.
*/
push('Loads still in the pipeline', t.loadsStarted - t.loadsCompleted);
push('Unloads still in the pipeline', t.unloadsBegun - t.unloadsCompleted);
push('Passengers boarded', t.passengersBoarded);
push('Passengers detrained', t.passengersDetrained);
push('Cars coupled', t.carsCoupled);
push('Cars set out', t.carsDropped);
push('Extras run', t.extrasStarted);
push('Second sections ordered', t.secondSections);
push('Flying switches', t.flyingSwitches);
push('Offices upgraded', t.officeUpgrades);
push('Facilities unjammed', t.facilitiesUnjammed);
push('Trains held', t.trainsHeld);
push('Trains diverted', t.trainsDiverted);
push('Expedite faults', t.expediteFaults);
push('Dispatch bonuses used', t.dispatchBonusesUsed);
if (t.clearancesRequested > 0) {
rows.push(['Clearances', `${t.clearancesAllowed} allowed of ${t.clearancesRequested} asked`]);
}
if (t.trainsDestroyed > 0) {
rows.push([
'Trains destroyed',
`${t.trainsDestroyed}, taking ${t.carsDestroyed} car${t.carsDestroyed === 1 ? '' : 's'} with them`,
]);
}
// §X18 only — the one card in the deck that pays a train for standing still. Reported as what it
// is rather than as "the longest an engine sat on a siding", which the engine cannot answer (see
// `Tally.circusStops`).
if (t.circusStops.length > 0) {
rows.push([
'Circus set-ups',
t.circusStops.map((c) => `Train ${c.trainNumber} at ${c.where}`).join(', '),
]);
}
push('Cards drawn', t.cardsDrawn);
push('Cards played', t.cardsPlayed);
// Gitea#9 made throwing a Timetabled train away a legal and deliberate move, so a discard is a
// CHOICE the player made rather than an accident of the hand limit — and the engine has counted
// it all along while the screen listed only draws and plays beside it.
push('Cards discarded', t.cardsDiscarded);
return `<h4 class="res-h">The railroad</h4>${factTable(rows)}`;
}
/** Per-player work, for a table that wants to know who did what rather than only who won. */
function perPlayerHtml(f: Frame): string {
const t = f.tally;
if (f.players.length < 2) return '';
const head =
'<tr><th></th><th class="num">Rev</th><th class="num">Loads</th><th class="num">Unloads</th>' +
'<th class="num">Pass.</th><th class="num">Cards</th><th class="num">Crashes</th></tr>';
const rows = [...f.players]
.sort((a, b) => b.revenue - a.revenue || a.seat - b.seat)
.map((p) => {
const q = t.byPlayer[p.index];
if (!q) return '';
return (
`<tr${p.index === f.viewer ? ' class="you"' : ''}><td>${esc(p.name)}</td>` +
`<td class="num">${p.revenue}</td><td class="num">${q.loads}</td>` +
`<td class="num">${q.unloads}</td>` +
`<td class="num">${q.passengersBoarded + q.passengersDetrained}</td>` +
`<td class="num">${q.cardsPlayed}</td><td class="num">${q.collisions}</td></tr>`
);
})
.join('');
return `<h4 class="res-h">Who did what</h4><table class="res-t res-wide"><tbody>${head}${rows}</tbody></table>`;
}
/**
* THE END-OF-GAME RESULTS SCREEN — Gitea#16, first pass.
*
* Everything the Frame already knew plus everything the event tally counted, in the order a player
* asks for it: what happened, who won, by how much, under what rules, and then what the railroad
* actually did all game. Badges and the "what would make this exciting" brainstorm are the second
* pass the issue asks for and are deliberately not here.
*
* THE OFFICIAL RESULT IS THE ONE AT THE TOP, always. In an extended game (Gitea#11) the standings go
* on moving after the winner is settled, so this screen reports the frozen result first and puts
* everything that happened afterwards in its own section, marked as informational. "In a five-day
* game, even if it's extended to eight or nine days, the winner and the official answer is the
* winner at the end of five days" (Jesse, 2026-08-28).
*/
export function resultsHtml(f: Frame): string {
// `official` is written by the engine the moment any game ends, so it is present on every finished
// game. The fallback keeps this rendering something sane for a Frame that predates it — a replay
// of a save recorded before this release, which the replay viewer will happily hand us.
const report = f.official;
const o = report?.outcome ?? f.outcome;
if (!o) return '<p class="dim">This game has not ended.</p>';
const officialDay = report?.day ?? f.days;
const winnerName =
o.winner === null ? null : (f.players.find((p) => p.index === o.winner)?.name ?? null);
const headline =
o.result === 'loss'
? 'The Division failed'
: winnerName === null
? 'The Division ran'
: `${esc(winnerName)} takes the Division`;
/**
* The result is reported against the standings AS THEY WERE at the official ending, not as they
* are now — in an extended game those are different numbers, and the winner has to be shown
* winning. `revenues` is frozen alongside the outcome for exactly this.
*/
const frozen = report
? { ...f, players: f.players.map((p) => ({ ...p, revenue: report.revenues[p.index] ?? p.revenue })) }
: f;
const result =
o.result === 'loss'
? '<p>Nobody wins this one.</p>'
: o.winner === null
? '<p>The table clears it together — a Co-op game has no individual winner.</p>'
: `<p><b>${esc(winnerName ?? '')}</b> finishes ahead on Revenue.</p>`;
const extended =
f.extraDays > 0
? '<h4 class="res-h">After the timetable</h4>' +
`<p>The table played on for ${f.extraDays} more Day${f.extraDays === 1 ? '' : 's'}, ` +
`through Day ${f.days + f.extraDays}. None of it changed the result above — it is recorded ` +
'here because it happened.</p>' +
standingsHtml(f) +
targetHtml(f) +
collisionsHtml(f) +
tallyHtml(f.tally)
: '';
return (
`<h3 class="dayend-h res-${o.result}">${headline}</h3>` +
`<p>${reasonSentence(frozen, o, officialDay)}</p>` +
result +
standingsHtml(frozen, o.winner) +
targetHtml(frozen) +
collisionsHtml(frozen) +
perPlayerHtml(frozen) +
rulesHtml(f) +
tallyHtml(report?.tally ?? f.tally) +
extended
);
}
export function blockedHtml(f: Frame): string {
return f.blocked.length === 0
? '<li class="dim">nothing blocked</li>'
: f.blocked
.map((b) => `<li class="sev-${b.severity}"><b>${esc(b.where)}</b> — ${esc(b.why)}</li>`)
.join('');
}
/** The load pipeline at each industry: green → MEN | AT | WORK → red, and the cars spotted here. */
export function facilitiesHtml(f: Frame): string {
/**
* One number, with what the card printed and what a Modifier added.
*
* `laborers` arrives as "left/total" and the rest as plain totals, so the total is taken from the
* end either way and compared with the base.
*/
const stat = (label: string, shown: string, base: number, why: string): string => {
const total = Number(shown.split('/').pop() ?? shown);
const added = Number.isFinite(total) ? total - base : 0;
const delta = added > 0 ? `<span class="added">+${added}</span>` : '';
return (
`<span class="cap" data-tip="${esc(why)}${added > 0 ? ` The card prints ${base}; Modifiers beside it add ${added}.` : ''}">` +
`<span class="dim">${esc(label)}</span> <b>${esc(shown)}</b>${delta}</span>`
);
};
/**
* GREEN IS OUTBOUND AND RED IS INBOUND — the caller says which, because this helper cannot know.
*
* It used to paint every filled box with one class, so the inbound row rendered GREEN while the
* board SVG on the same page drew it red. The two disagreed on screen at the same time, which is
* the one thing a colour code must never do. Reported from playtesting.
*/
const boxes = (filled: string[], cap: number, cls: 'g' | 'r' | 's'): string => {
let h = '';
for (let i = 0; i < Math.max(cap, filled.length); i++) {
h += `<span class="box ${i < filled.length ? cls : 'empty'}">${i < filled.length ? esc(filled[i] ?? '') : '·'}</span>`;
}
return h || '<span class="dim">—</span>';
};
return f.facilities.length === 0
? '<div class="dim">no facilities yet</div>'
: f.facilities
.map(
(x) =>
`<div class="fac" data-tip="${esc(x.name)} — ${esc(x.flow)} ${esc(x.commodity)}" tabindex="0">` +
`<div class="nm">${esc(x.name)} <span class="dim">${esc(x.commodity)}</span></div>` +
/**
* THE WORKERS AND THE CAPACITIES, ON THE PANEL RATHER THAN IN A TOOLTIP.
*
* Laborers were only ever in the hover text, so "how many actions can I take here this
* Stage?" — the question that decides every Cargo phase — had to be hunted for. And a
* Modifier's whole effect is one of these numbers going up, so showing the number alone
* made an Ice House look like it had done nothing. Each now says what the card prints
* and what the Modifiers beside it added.
*/
`<div class="caps">` +
/**
* PORTERS TOO, NOT JUST LABORERS.
*
* `porters` has been on the view-model all along and no renderer ever printed it — so a
* Waiting Area, Restaurant or Hotel beside the Office, whose whole effect is +1 porter
* and +1 passenger slot, showed exactly half of what it did. Reported: "it gave me an
* extra porter that I see no indication of anywhere."
*
* A facility has one kind of worker or the other: Laborers work freight, Porters work
* passengers. Showing the row that is always 0/0 would be noise, so each shows its own.
*/
(Number(x.laborers.split('/').pop()) > 0 || x.base.laborers > 0
? stat('laborers', x.laborers, x.base.laborers, 'Actions this facility can take each Stage — one Laborer moves one load one square. Left of the slash is how many are still free this Stage.')
: '') +
(Number(x.porters.split('/').pop()) > 0 || x.base.porters > 0
? stat('porters', x.porters, x.base.porters, 'Passenger work, one action each per Stage: a Porter boards or detrains passengers, and earns the Revenue in a single action. Left of the slash is how many are still free this Stage.')
: '') +
(x.allowsOut ? stat('out', String(x.greenCap), x.base.out, 'Green boxes: loads waiting to be worked onto a car.') : '') +
(x.allowsIn ? stat('in', String(x.redCap), x.base.in, 'Red boxes: loads cleared off an arriving car.') : '') +
(x.modifiers.length
? `<span class="mods" data-tip="Modifier cards standing beside this industry, each raising one of the numbers above.">+ ${esc(x.modifiers.join(', '))}</span>`
: '') +
/**
* A GRANT THIS FACILITY CANNOT USE, SAID OUT LOUD.
*
* An industry's printed flow is absolute, so an Ice House beside a Grocer's Warehouse
* gives its Laborer and nothing else. Showing only the numbers made that read as a bug —
* reported from playtesting as "it added the laborer but not the outbound slot". The
* number genuinely does not move; what was missing was the reason.
*/
(x.suppressed.length
? `<span class="dead" data-tip="${esc(x.suppressed.join(' · '))}">` +
`${esc(String(x.suppressed.length))} printed bonus${x.suppressed.length === 1 ? '' : 'es'} unused</span>`
: '') +
`</div>` +
/**
* IN THE ORDER THE LOAD TRAVELS. §9.3 loads Green → MEN → AT → WORK → the spotted car,
* and unloads the other way: car → WORK → AT → MEN → red. Labelling the rows by colour
* alone left a player to work out which direction their industry ran; naming the step
* says it outright, and an industry that only receives has no green row to puzzle over.
*/
(x.allowsOut
? `<div class="boxes"><span class="dim" data-tip="${
x.kind === 'passenger'
? 'Passengers waiting to board. A Porter puts them onto a coach in a single action.'
: 'Loads waiting to be worked out onto a car. They travel green → MEN → AT → WORK, then onto a spotted empty car.'
}">${x.kind === 'passenger' ? 'waiting to board' : 'waiting to load'}</span>${boxes(x.green, x.greenCap, 'g')}</div>`
: '') +
/**
* A PASSENGER FACILITY HAS NO SIGN, so the row is not drawn for one.
*
* `maw` comes back empty for a Depot, Station or Terminal — the pipeline is a Freight
* Facility fitting (§9.2 is Porters, with no MEN | AT | WORK step). The row LABEL printed
* ahead of the loop regardless, so a Depot showed the caption and three empty boxes it
* has no Laborer to work.
*/
(x.maw.length > 0
? `<div class="boxes"><span class="dim" data-tip="One physical sign, worked in whichever direction this industry runs. Only one load may sit on each of the three boxes.">MEN AT WORK</span>` +
x.maw.map((m) => `<span class="box ${m ? 'm' : 'empty'}">${m ? esc(m) : '·'}</span>`).join('') +
`</div>`
: '') +
(x.allowsIn
? `<div class="boxes"><span class="dim" data-tip="${
x.kind === 'passenger'
? 'Passengers who have arrived and been detrained by a Porter.'
: 'Loads that have come off an arriving car and been cleared. They travel car → WORK → AT → MEN, then into a red box — the opposite direction to loading.'
}">${x.kind === 'passenger' ? 'arrived' : 'cleared inbound'}</span>${boxes(x.red, x.redCap, 'r')}</div>`
: '') +
/**
* THE CARS THAT ARE HERE — NOT A SIDING OF A FIXED LENGTH.
*
* This drew one empty box per unit of the industry's capacity and labelled the row
* "siding", which said two untrue things: that the card prints a siding, and that its
* length is the box count. It is neither. An industry track is ordinary Operating Rail
* and holds four cars like every other card, so there is no printed length worth
* drawing — only what is actually standing there. Passing cap 0 renders the cars alone.
*/
(x.track.length > 0
? `<div class="boxes"><span class="dim" data-tip="Cars standing on this industry's track. A load leaves the sign onto one of these, or an arriving load starts from one. Up to four cars fit here, the same as any Operating track card.">spotted</span>${boxes(x.track, 0, 's')}</div>`
: '') +
`<div class="fstat ${x.jammed ? 'bad' : x.canFinish ? 'good' : 'idle'}" data-tip="${
x.jammed
? 'A load is sitting on MEN|AT|WORK with no spotted car to receive it. That locks the industry track, which blocks the very car that would clear it.'
: x.canFinish
? 'A matching empty car is spotted on this industry\'s track, so a load worked here can come off onto it.'
: 'No matching car is spotted. Starting a load here would park it on WORK and jam the facility.'
}">` +
(x.jammed ? 'JAMMED' : x.canFinish ? 'ready' : 'no car spotted') +
`</div></div>`,
)
.join('');
}
/** Styling for all of the above, so the two pages cannot drift apart visually. */
export const PANEL_CSS = `
h3{font-size:11px;text-transform:uppercase;letter-spacing:.07em;color:#8b94a3;margin:9px 0 4px}
.cardrow{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 2px}
.handcard{background:#242c36;border:1px solid #2c333d;border-radius:5px;
padding:5px 8px;font-size:11px;min-width:96px;position:relative}
.handcard:focus{outline:2px solid #4d6fa8;outline-offset:1px}
.cardrow.ref .handcard{background:#1c2129;border-style:dashed;border-color:#39424e;color:#b6bec9}
.handcard.unplayable{color:#7d8794;border-color:#39424e}
.handcard.unplayable::after{content:"";position:absolute;inset:0;border-radius:5px;pointer-events:none;
background:repeating-linear-gradient(45deg,transparent 0 5px,rgba(150,160,175,.20) 5px 6px)}
/* THE CARD JUST DRAWN. It sits first in the row, and this says which one that is — three cards that
look alike otherwise, with nothing to distinguish the one you turned over. Green is the page's
"a good thing just happened" colour, as on the timetable. A static badge rather than a flash: the
hand is rebuilt by innerHTML on every render, which would restart a keyframe each time, and the
question being answered is "which of these is new" rather than "did something happen". */
.handcard.fresh{border-color:#8fd6a0;box-shadow:0 0 0 2px rgba(143,214,160,.18)}
.handcard.fresh::before{content:"NEW";display:block;font-size:9px;letter-spacing:.09em;
color:#8fd6a0;font-weight:700;margin-bottom:2px}
/* A pile shows two things: which card is face up on top, and how many are under it. */
.pilehd{display:flex;justify-content:space-between;align-items:baseline;gap:8px;margin-bottom:2px;
font-size:10px;text-transform:uppercase;letter-spacing:.07em;color:#8b94a3}
.pilehd .depth{font-variant-numeric:tabular-nums;background:#2a3038;border-radius:8px;
padding:0 6px;color:#cfe0f5}
/* Rolling stock is finite and the Classification Yard only returns it when the Division Yard is
bare, so watching the Division Yard run down is real information. */
.yard{display:flex;flex-wrap:wrap;gap:5px;margin:0 0 6px}
.stock{background:#1c2129;border:1px solid #39424e;border-radius:4px;padding:2px 7px;font-size:11px}
.stock b{color:#e6e9ee}
.stock .ld{color:#8fd6a0}
.stock .mt{color:#9fb6d8}
.stock.none{opacity:.4}
/* A PILE THAT IS WAITING TO BE PICKED, drawn like the board's ghost squares because it is the same
question: you have chosen a card, now choose where it goes. It was a 2px outline on a small tile
in a panel the player might not be looking at, and was reported as "a very tiny highlight". Now it
grows, brightens, says DISCARD HERE outright, and pulses once so the eye finds it. */
.handcard.target{border:2px dashed #5aa9e6;background:#233246;cursor:pointer;color:#e6e9ee;
box-shadow:0 0 0 4px rgba(90,169,230,.22);transform:translateY(-2px);
animation:pick 1.1s ease-out 2}
.handcard.target:hover{background:#31485f;border-style:solid;box-shadow:0 0 0 6px rgba(90,169,230,.30)}
.handcard.target::before{content:"DISCARD HERE";display:block;font-size:9px;letter-spacing:.09em;
color:#8fc4ee;font-weight:700;margin-bottom:2px}
@keyframes pick{0%{box-shadow:0 0 0 4px rgba(90,169,230,.22)}
50%{box-shadow:0 0 0 9px rgba(90,169,230,.10)}
100%{box-shadow:0 0 0 4px rgba(90,169,230,.22)}}
@media(prefers-reduced-motion:reduce){.handcard.target{animation:none}}
/* And the piles that are NOT targets step back while a discard is being aimed, so the three that
are stand out from the Salvage Yard beside them. */
.cardrow.aiming .handcard:not(.target){opacity:.4}
.stock .ld.addable,.stock .mt.addable{cursor:pointer;border-radius:3px;padding:0 4px;
outline:1px solid #5aa9e6;background:rgba(90,169,230,.16)}
.stock .ld.addable:hover,.stock .mt.addable:hover{background:rgba(90,169,230,.34)}
/* Twelve Stages across, so a Day is one glance. The current Stage is lit, Stages already gone are
dimmed, and a slot the die has just filled flashes once. */
.tt{display:flex;gap:3px;flex-wrap:wrap}
.tt-slot{flex:1 1 0;min-width:26px;text-align:center;border:1px solid #2c333d;border-radius:4px;
padding:2px 0;background:#1a1f26;font-size:10px;cursor:help;line-height:1.25}
.tt-slot .tt-s{display:block;color:#5f6b7a;font-size:9px}
.tt-slot .tt-t{display:block;color:#5f6b7a;font-variant-numeric:tabular-nums}
.tt-slot.due{background:#222c38;border-color:#4d6fa8}
.tt-slot.due .tt-t{color:#cfe0f5;font-weight:700}
.tt-slot.past{opacity:.45}
.tt-slot.now{border-color:#b98cf0;box-shadow:0 0 0 2px rgba(150,110,230,.20)}
.tt-slot.now .tt-s{color:#b98cf0;font-weight:700}
.tt-slot.fresh{animation:ttflash 1.5s ease-out 1}
@keyframes ttflash{0%{background:#2f6b47;border-color:#8fd6a0;transform:scale(1.18)}
100%{background:#222c38;border-color:#4d6fa8;transform:scale(1)}}
@media(prefers-reduced-motion:reduce){.tt-slot.fresh{animation:none;outline:2px solid #8fd6a0}}
/* THE KEY TO THE FOUR STATES ABOVE. A slot can be lit blue, ringed violet, dimmed, or flashing
green, and nothing said which was which — reported as "what do the colours mean?" The green one
in particular is a MOMENT, not a state: it marks the slot the die just filled and is gone by the
next render, so without a key it reads as a category of train. */
.tt-key{display:flex;gap:10px;flex-wrap:wrap;margin-top:6px;font-size:10px;color:#8b94a3}
.tt-key span{display:inline-flex;align-items:center;gap:4px}
.tt-key span::before{content:"";width:9px;height:9px;border-radius:2px;border:1px solid #2c333d;
background:#1a1f26}
.tt-key .k-due::before{background:#222c38;border-color:#4d6fa8}
.tt-key .k-now::before{border-color:#b98cf0;box-shadow:0 0 0 1px rgba(150,110,230,.35)}
.tt-key .k-past::before{opacity:.45}
.tt-key .k-fresh::before{background:#2f6b47;border-color:#8fd6a0}
ul.blocked{margin:0;padding-left:18px}
.sev-waiting{color:#8b94a3}.sev-risk{color:#e0b060}.sev-stuck{color:#e58080}
.fac{border-top:1px solid #2c333d;padding:7px 0}
.fac:first-child{border-top:0}
.fac .nm{font-size:12px;font-weight:600}
.caps{display:flex;flex-wrap:wrap;gap:9px;margin-top:3px;font-size:10px;align-items:baseline}
.cap b{color:#e6e9ee;font-variant-numeric:tabular-nums}
.cap .added{color:#8fd6a0;margin-left:2px;font-weight:700}
.caps .mods{color:#c8a04a}
/* Amber-grey: a fact about the card, not a fault the player caused. */
.caps .dead{color:#8b94a3;border-bottom:1px dotted #6c7480}
.boxes{display:flex;gap:3px;align-items:center;margin-top:3px;flex-wrap:wrap}
.box{display:inline-block;min-width:22px;text-align:center;border-radius:3px;padding:1px 4px;font-size:10px}
.box.empty{background:#242a32;color:#5a6472}
/* Green OUT, red IN, matching the board SVG's palette exactly — the panel and the map are the same
card seen twice, so they may not disagree about which colour means which way. Grey for spotted cars,
which is a place rather than a direction. */
.box.g{background:#2f6b3d}
.box.r{background:#8a4a4a}
.box.s{background:#3a4450}
.box.m{background:#8a6d1f}
.fstat{margin-top:3px;font-size:10px;padding:1px 6px;border-radius:3px;display:inline-block}
.fstat.good{background:rgba(40,140,60,.28)}
.fstat.bad{background:rgba(190,50,50,.38);font-weight:700}
.fstat.idle{opacity:.6}
/* THE DAY-END DIALOG (Gitea#10). The dialog chrome is play.html's; these are its contents, here
because dayEndHtml is here — a panel and its styling stay together. */
.dayend-h{font-size:15px;text-transform:none;letter-spacing:0;color:#e6e9ee;margin:0 0 8px}
.dayend-t{border-collapse:collapse;margin:9px 0;min-width:210px}
.dayend-t td{padding:3px 12px 3px 0;border-top:1px solid #2c333d}
.dayend-t tr:first-child td{border-top:0}
.dayend-t .num{text-align:right;font-variant-numeric:tabular-nums;font-weight:700;padding-right:0}
.dayend-t .you td{color:#8fd6a0}
.dayend-t .wins{color:#e8c56a;font-weight:700}
/* END-OF-GAME RESULTS (Gitea#16). Same family as the Day-end dialog above, which is the point —
the two screens share their standings/target/collision blocks and should look like each other. */
.res-h{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:#8b95a3;
margin:16px 0 6px;border-top:1px solid #2c333d;padding-top:10px}
.res-win{color:#8fd6a0}
.res-loss{color:#d98f8f}
.res-t{border-collapse:collapse;margin:4px 0;width:100%}
.res-t td,.res-t th{padding:3px 12px 3px 0;border-top:1px solid #232a33;vertical-align:top}
.res-t tr:first-child td{border-top:0}
.res-t td:first-child{color:#8b95a3;white-space:nowrap}
.res-t th{color:#6d7783;font-weight:600;font-size:11px;text-transform:uppercase;letter-spacing:.05em}
.res-t .num{text-align:right;font-variant-numeric:tabular-nums}
.res-wide td:first-child{color:#e6e9ee}
.res-t .you td{color:#8fd6a0}
`;