From 053c00fd17588735ca88d2147cdb8a2ad5a6eb9c Mon Sep 17 00:00:00 2001 From: coyotte508 Date: Thu, 19 Nov 2026 00:00:38 +0000 Subject: [PATCH] Style bank journal entries and automatically resolve forced payments --- docs/offshore-island.md | 2 + engine/OFFSHORE-CONTRACT.md | 2 +- engine/src/engine.ts | 11 +- engine/src/offshore.spec.ts | 138 +++++++++++++++++++-- engine/src/offshore.ts | 21 ++++ viewer/scripts/offshore-smoke.mjs | 58 +++++++-- viewer/src/components/Game.vue | 10 +- viewer/src/journal-pieces.ts | 6 + viewer/src/offshore-journal.ts | 77 ++++++++++-- viewer/tests/unit/offshore-journal.spec.ts | 128 +++++++++++++++++++ 10 files changed, 413 insertions(+), 40 deletions(-) create mode 100644 viewer/tests/unit/offshore-journal.spec.ts diff --git a/docs/offshore-island.md b/docs/offshore-island.md index 1ad11f3..73f0e0f 100644 --- a/docs/offshore-island.md +++ b/docs/offshore-island.md @@ -35,6 +35,8 @@ No physical-edition artwork is copied into the viewer. Outbid containers return to their original district, with owner repricing. - Bank payments start at lot I, cycling through the three lots and skipping frozen lots with active auctions. A container payer chooses the color order. + If only one color remains, the engine places those containers automatically; + the payment prompt appears only when different colors remain to choose from. - Interest, delivery self-buyouts, and seized containers replenish the bank. Building costs and loan repayments still go to the ordinary supply. - Won containers go into the winner's bank holding area, not directly onto their diff --git a/engine/OFFSHORE-CONTRACT.md b/engine/OFFSHORE-CONTRACT.md index 0d5b91d..3a48dac 100644 --- a/engine/OFFSHORE-CONTRACT.md +++ b/engine/OFFSHORE-CONTRACT.md @@ -13,7 +13,7 @@ Move enum names/values: - `SeizeBankContainer = 'seizeBankContainer'`: data ContainerPiece, no extraData. Right-hand player chooses among highest-priority source; repeat then choose distribution. - `LoadBankContainer = 'loadBankContainer'`: data ContainerPiece, no extraData, free repeat until capacity5. Other normal moves end arrival pickup window. -`Phase.BankDecision = 'bankDecision'`, `G.currentPlayers` is sole decision owner. `offshoreBank.decision` describes `kind:'return'|'distribute'|'seize'`, `player`, `resumePlayer`, returned `containers`, ordered-to-be-chosen `payment`, distribution `cursor`, optional `debtor`, `remaining`, `settlement`, `ending`. Use availableMoves keys to display controls. Each decision commits independently; resumePlayer's interrupted regular turn resumes after final choice. All choices are logged explicit moves. +`Phase.BankDecision = 'bankDecision'`, `G.currentPlayers` is sole decision owner. `offshoreBank.decision` describes `kind:'return'|'distribute'|'seize'`, `player`, `resumePlayer`, returned `containers`, ordered-to-be-chosen `payment`, distribution `cursor`, optional `debtor`, `remaining`, `settlement`, `ending`. Use availableMoves keys to display controls. Each decision commits independently; resumePlayer's interrupted regular turn resumes after final choice. Discretionary choices are logged explicit moves. After each engine move, distribution automatically drains when all remaining payment pieces have the same color (including a single piece), in persisted payment order into cyclic unfrozen destinations. These forced effects are not synthetic moves or viewer emissions; collection and any following settlement finish before legal moves are published. Multiple colors still require explicit choices. Return pricing, seizure and loading remain explicit. Legacy saved single-piece distribution decisions still accept their advertised move. Fake previews normalize distribution but never score secret point cards. Score breakdown remains same length: ship line includes bankHolding at $3 each. Other base scoring unchanged. diff --git a/engine/src/engine.ts b/engine/src/engine.ts index c727f25..ed855c5 100644 --- a/engine/src/engine.ts +++ b/engine/src/engine.ts @@ -17,7 +17,7 @@ import { } from './gamestate'; import { GameEventName, LogItem, LogMove } from './log'; import { Move, MoveName, Moves } from './move'; -import { applyBankMove, bankUpkeep, payBankCash, settleBank } from './offshore'; +import { applyBankMove, bankUpkeep, normalizeBankDistribution, payBankCash, settleBank } from './offshore'; import { asserts, shuffle } from './utils'; export const playerColors = ['dodgerblue', 'red', 'yellow', 'limegreen', 'mediumorchid']; @@ -704,6 +704,15 @@ export function move(G: GameState, move: Move, playerNumber: number, fake?: bool } } + // Normalize after every transition that can create a payment decision, before + // publishing legal moves. Forced placements are effects, not synthetic player moves. + const forcedBankResult = normalizeBankDistribution(G); + if (forcedBankResult.ending && !fake) { + G.phase = Phase.GameEnd; + G.currentPlayers = []; + calculateEndScore(G); + } + player.availableMoves = null; if (move.name != MoveName.GetLoan && move.name != MoveName.PayLoan) { diff --git a/engine/src/offshore.spec.ts b/engine/src/offshore.spec.ts index 1d8f8ff..197718f 100644 --- a/engine/src/offshore.spec.ts +++ b/engine/src/offshore.spec.ts @@ -110,10 +110,11 @@ describe('optional Off-Shore Bank', () => { expect(g.currentPlayers).deep.equal([resume]); expect(g.newTurn).equal(true); }); - it('allows payer distribution choices and frozen-lot skipping', () => { + it('automatically distributes a single payment and skips frozen lots', () => { const g = game(5); const first = g.players[g.currentPlayers[0]]; - containerBid(g, [first.containersOnFactoryStore[0].piece.id]); + const piece = first.containersOnFactoryStore[0].piece; + containerBid(g, [piece.id]); pass(g); cashBid(g, 2, 0); payBankCash(g, 3); @@ -122,9 +123,8 @@ describe('optional Off-Shore Bank', () => { pass(g); pass(g); pass(g); - expect(g.phase).equal(Phase.BankDecision); - const piece = g.offshoreBank!.decision!.payment[0]; - act(g, { name: MoveName.DistributeBankContainer, data: piece }); + expect(g.phase).equal(Phase.Move); + expect(g.offshoreBank!.decision).equal(undefined); expect(g.offshoreBank!.containerLots[1].some((c) => c.id === piece.id)).equal(true); expect(first.offshoreStats!.cashAuctionsWon).equal(1); expect(first.money).equal(23); @@ -148,6 +148,116 @@ describe('optional Off-Shore Bank', () => { expect(p.bankHolding!.length).equal(2); expect(p.loans.length).equal(2); }); + it('automatically drains same-color payments in persisted order and conserves cash and pieces', () => { + const g = game(); + const p = g.players[g.currentPlayers[0]]; + const color = p.containersOnFactoryStore[0].piece.color; + for (let n = 0; n < 4; n++) { + const i = g.containersLeft.findIndex((c) => c.color === color); + p.containersOnFactoryStore.push({ piece: g.containersLeft.splice(i, 1)[0], price: 2, moved: false }); + } + const payment = p.containersOnFactoryStore.map((c) => c.piece); + const inventory = () => + [ + ...g.containersLeft, + ...g.offshoreBank!.containerLots.reduce((all, lot) => all.concat(lot), [] as typeof g.containersLeft), + ...g.players.reduce( + (all, p) => + all.concat([ + ...p.bankHolding!, + ...p.ship.containers, + ...p.containersOnIsland, + ...p.containersOnFactoryStore.map((c) => c.piece), + ...p.containersOnWarehouseStore.map((c) => c.piece), + ]), + [] as typeof g.containersLeft + ), + ] + .map((c) => c.id) + .sort(); + const before = inventory(); + const cash = () => + g.players.reduce((n, p) => n + p.money, 0) + g.offshoreBank!.cashLots.reduce((a, b) => a + b, 0); + const money = cash(); + refresh(g); + containerBid( + g, + payment.map((c) => c.id) + ); + pass(g); + pass(g); + pass(g); + expect(g.phase).equal(Phase.Move); + expect(g.offshoreBank!.decision).equal(undefined); + payment.forEach((piece, i) => expect(g.offshoreBank!.containerLots[i % 3]).deep.include(piece)); + expect(inventory()).deep.equal(before); + expect(new Set(inventory()).size).equal(before.length); + expect(cash()).equal(money); + expect(g.log.some((e) => e.type === 'move' && e.move.name === MoveName.DistributeBankContainer)).equal(false); + }); + it('pauses for multiple colors, then automatically drains the final color after an explicit choice', () => { + let g = game(); + const p = g.players[g.currentPlayers[0]]; + const first = p.containersOnFactoryStore[0].piece; + const color = g.containersLeft.find((c) => c.color !== first.color)!.color; + for (let n = 0; n < 3; n++) { + const i = g.containersLeft.findIndex((c) => c.color === color); + p.containersOnFactoryStore.push({ piece: g.containersLeft.splice(i, 1)[0], price: 2, moved: false }); + } + refresh(g); + containerBid( + g, + p.containersOnFactoryStore.map((c) => c.piece.id) + ); + pass(g); + pass(g); + pass(g); + expect(g.phase).equal(Phase.BankDecision); + expect(g.offshoreBank!.decision!.payment.length).equal(4); + g = JSON.parse(JSON.stringify(g)); + act(g, { name: MoveName.DistributeBankContainer, data: first }); + expect(g.phase).equal(Phase.Move); + expect(g.offshoreBank!.decision).equal(undefined); + expect(g.players[p.id].offshoreStats!.cashAuctionsWon).equal(1); + expect(g.currentPlayers).deep.equal([p.id]); + }); + it('keeps seizure explicit but automatically distributes its final single payment', () => { + const g = game(); + const debtor = g.players[g.currentPlayers[0]]; + const piece = debtor.containersOnFactoryStore[0].piece; + debtor.money = 0; + debtor.loans.push(g.loansLeft.pop()!, g.loansLeft.pop()!); + pass(g); + pass(g); + pass(g); + expect(g.offshoreBank!.decision!.kind).equal('seize'); + act(g, { name: MoveName.SeizeBankContainer, data: piece }); + expect(g.offshoreBank!.decision).equal(undefined); + expect(g.offshoreBank!.containerLots[0]).deep.include(piece); + expect(g.phase).equal(Phase.Move); + expect(g.currentPlayers).deep.equal([debtor.id]); + expect(debtor.containersOnFactoryStore).deep.equal([]); + }); + it('accepts a legacy saved single-payment decision and resumes its interrupted player', () => { + let g = game(); + const id = g.currentPlayers[0]; + const piece = g.containersLeft.pop()!; + g.offshoreBank!.decision = { + kind: 'distribute', + player: id, + resumePlayer: (id + 1) % 3, + payment: [piece], + containers: [], + cursor: 2, + }; + g.phase = Phase.BankDecision; + refresh(g); + g = JSON.parse(JSON.stringify(g)); + act(g, { name: MoveName.DistributeBankContainer, data: piece }); + expect(g.offshoreBank!.containerLots[2]).deep.include(piece); + expect(g.phase).equal(Phase.Move); + expect(g.currentPlayers).deep.equal([(id + 1) % 3]); + }); it('loads only on arrival for free, obeys capacity and requires leaving/reentering next turn', () => { const g = game(); const p = g.players[g.currentPlayers[0]]; @@ -187,8 +297,6 @@ describe('optional Off-Shore Bank', () => { ); refresh(g); pass(g); - expect(g.phase).equal(Phase.BankDecision); - decisions(g); expect(g.phase).equal(Phase.GameEnd); expect(winner.offshoreStats!.cashAuctionsWon).equal(1); expect(g.offshoreBank!.auctions.length).equal(0); @@ -207,15 +315,15 @@ describe('optional Off-Shore Bank', () => { expect(analysis.players.map((p) => p.money)).deep.equal(g.players.map((p) => p.money)); expect(analysis.offshoreBank).deep.equal(g.offshoreBank); }); - it('logs and replays a complete container-payment decision and supports dropped decision owners', async () => { + it('replays automatic payments from JSON without synthetic distribution moves', async () => { const g = game(); const p = g.players[g.currentPlayers[0]]; containerBid(g, [p.containersOnFactoryStore[0].piece.id]); pass(g); pass(g); pass(g); - expect(g.phase).equal(Phase.BankDecision); - expect(wrapper.replay(g)).deep.equal(g); + expect(g.phase).equal(Phase.Move); + expect(wrapper.replay(JSON.parse(JSON.stringify(g)))).deep.equal(g); const copy = cloneDeep(g); await wrapper.dropPlayer(copy, p.id); expect(copy.phase).equal(Phase.Move); @@ -296,7 +404,7 @@ describe('optional Off-Shore Bank', () => { const piece = g.offshoreBank!.decision!.payment[0]; act(g, { name: MoveName.DistributeBankContainer, data: piece }); } - expect(count).equal(2); + expect(count).equal(1); expect(g.phase).equal(Phase.GameEnd); expect(g.offshoreBank!.auctions).deep.equal([]); expect(g.players[first.id].offshoreStats!.cashAuctionsWon).equal(1); @@ -306,7 +414,13 @@ describe('optional Off-Shore Bank', () => { it('optimistically completes final bank decisions without scoring secret point cards', () => { const g = game(); const p = g.players[g.currentPlayers[0]]; - containerBid(g, [p.containersOnFactoryStore[0].piece.id]); + const i = g.containersLeft.findIndex((c) => c.color !== p.containersOnFactoryStore[0].piece.color); + p.containersOnFactoryStore.push({ piece: g.containersLeft.splice(i, 1)[0], price: 2, moved: false }); + refresh(g); + containerBid( + g, + p.containersOnFactoryStore.map((c) => c.piece.id) + ); pass(g); g.players[g.currentPlayers[0]].containersOnIsland.push(g.containersLeft.pop()!); g.containersLeft = g.containersLeft.filter((c) => c.color === g.containersLeft[0].color); diff --git a/engine/src/offshore.ts b/engine/src/offshore.ts index fe2c024..dc3a077 100644 --- a/engine/src/offshore.ts +++ b/engine/src/offshore.ts @@ -263,6 +263,27 @@ export function applyBankMove(G: GameState, move: Move, p: Player): { handled: b return { handled: true }; } +/** Drain only color-equivalent payment choices, in persisted payment order. + * IDs distinguish physical pieces, not value; price/district no longer apply in bank lots. + * Reuse the normal transition so collection, default resumption and final settlements + * behave identically to an explicit choice (including legacy saved decisions). + */ +export function normalizeBankDistribution(G: GameState): { ending?: boolean } { + let ending: boolean | undefined; + while (G.phase === Phase.BankDecision) { + const d = G.offshoreBank?.decision; + if (!d || d.kind !== 'distribute' || !d.payment.length || d.payment.some((c) => c.color !== d.payment[0].color)) + break; + const result = applyBankMove( + G, + { name: MoveName.DistributeBankContainer, data: d.payment[0] }, + G.players[d.player] + ); + ending = result.ending || ending; + } + return { ending }; +} + /** Mandatory production must be finishable without triggering game end after Call Bank. */ export function bankProductionAllowed(G: GameState, p: Player, first: ContainerPiece['color']): boolean { if (!G.offshoreBank?.called) return true; diff --git a/viewer/scripts/offshore-smoke.mjs b/viewer/scripts/offshore-smoke.mjs index bfc9e63..ff194d1 100644 --- a/viewer/scripts/offshore-smoke.mjs +++ b/viewer/scripts/offshore-smoke.mjs @@ -284,6 +284,35 @@ try { 3 ); + // Public bank entries use the same badges and SVG/CB pieces as ordinary logs, + // even after the escrow has been outbid and returned to a store. + const cashEntries = page.locator('.journal-entry').filter({ hasText: 'calls bank for cash lot' }); + assert.ok(await cashEntries.count()); + assert.ok(await cashEntries.first().locator('svg[role="img"]').count()); + assert.ok(await cashEntries.first().locator('.color-mark').count()); + const journalBadge = cashEntries.first().locator('[data-localized-journal] > span').first(); + assert.equal(await journalBadge.textContent(), state.players[player].name); + assert.notEqual(await journalBadge.evaluate((el) => el.style.backgroundColor), ''); + // A temporary, legal ordinary loan gives a side-by-side styling reference. + const reference = engine.setup(3, {}, 'ordinary-journal'); + reference.players[player].name = state.players[player].name; + const loan = engine.move(reference, { name: engine.MoveName.GetLoan, data: true }, player).log.at(-1); + const comparison = copy(state); + comparison.log.push(loan); + await page.evaluate((state) => host.emit('state', state), engine.stripSecret(comparison, player)); + await page.locator('.journal-entry').filter({ hasText: 'takes a loan' }).waitFor({ state: 'attached' }); + const ordinaryBadge = page + .locator('.journal-entry') + .filter({ hasText: 'takes a loan' }) + .locator('[data-localized-journal] > span') + .first(); + assert.equal( + await ordinaryBadge.evaluate((el) => el.style.backgroundColor), + await journalBadge.evaluate((el) => el.style.backgroundColor) + ); + await page.locator('.inline-game-log').screenshot({ path: `/tmp/container-offshore-journal-${width}.png` }); + await push(); + // Existing journal localization works without a separate web-style panel. await page.evaluate(() => host.emit('preferences', { locale: 'fr' })); await page.waitForFunction(() => @@ -372,7 +401,7 @@ try { assert.equal(await page.locator('.offshore-lot.destination').getAttribute('data-lot'), String(lot)); assert.equal(await page.locator('.offshore-lot[role="button"]').count(), 0); assert.equal(await page.locator('.bank-decision > text').count(), 0); - assert.equal(await page.evaluate(() => moves.length), 0, 'never auto-pay'); + assert.equal(await page.evaluate(() => moves.length), 0, 'color choice waits for the player'); await page.waitForTimeout(1200); await page.screenshot({ path: `/tmp/container-offshore-payment-${stage}-${width}.png`, fullPage: true }); }; @@ -387,9 +416,8 @@ try { await page.evaluate((player) => host.emit('player', { index: player }), player); await push(); for (const [index, lot] of [ - [1, 0], - [0, 2], - [2, 0], + [0, 0], + [1, 2], ]) { await page.locator(`.bank-choice [data-piece-id="${payments[index].id}"]`).click(); const actions = await page.evaluate(() => moves.at(-1)); @@ -398,19 +426,27 @@ try { state = engine.move(state, actions[0], player); assert.ok(state.offshoreBank.containerLots[lot].some((piece) => piece.id === payments[index].id)); await push(); - if (index === 1) await checkPayment(2, 'skip'); - if (index === 0) await checkPayment(0, 'last'); + if (index === 0) await checkPayment(2, 'skip'); } + // The final orange container is placed automatically, skipping the frozen lot. + assert.ok(state.offshoreBank.containerLots[0].some((piece) => piece.id === payments[2].id)); assert.equal(await page.locator('.bank-decision, .offshore-lot.destination').count(), 0); - // Final cash settlement must remain clickable with opponents' point cards stripped. + // Final settlement: choose between colors, then finish automatically with stripped opponent cards. const payment = state.players[player].containersOnFactoryStore.pop(); + const finalOther = state.containersLeft.splice( + state.containersLeft.findIndex((piece) => piece.color !== payment.piece.color), + 1 + )[0]; const auction = { type: 'cash', lot: 0, bidder: player, cash: 0, - containers: [{ container: payment, district: 'factory' }], + containers: [ + { container: payment, district: 'factory' }, + { container: { piece: finalOther, price: 2, moved: false }, district: 'factory' }, + ], }; state.offshoreBank.auctions = [auction]; state.offshoreBank.decision = { @@ -418,7 +454,7 @@ try { player, resumePlayer: player, containers: [], - payment: [payment.piece], + payment: [payment.piece, finalOther], cursor: 0, settlement: copy(auction), ending: true, @@ -427,8 +463,8 @@ try { state.newTurn = true; state.currentPlayers = [player]; await push(); - assert.equal(await page.evaluate(() => moves.length), 0, 'single payment requires explicit click'); - await page.locator('.bank-choice [data-piece-id][role="button"]').click(); + assert.equal(await page.evaluate(() => moves.length), 0, 'different colors require a choice'); + await page.locator('.bank-choice [data-piece-id][role="button"]').first().click(); const distribution = await page.evaluate(() => moves.at(-1)); assert.equal(distribution.length, 1); state = engine.move(state, distribution[0], player); diff --git a/viewer/src/components/Game.vue b/viewer/src/components/Game.vue index a8f59e5..30d21af 100644 --- a/viewer/src/components/Game.vue +++ b/viewer/src/components/Game.vue @@ -832,7 +832,7 @@ import { colorBadgeHtml } from '../color-blind'; import { playerColors, playerTextColor, playerSymbol } from '../player-colors'; import { journalPieces } from '../journal-pieces'; import { journalOrder } from '../journal-order'; -import { offshoreJournal, escapeJournal } from '../offshore-journal'; +import { offshoreJournal } from '../offshore-journal'; import { Vue, Component, Prop, Watch, Provide, ProvideReactive } from 'vue-property-decorator'; import { bidRevision, MoveName, ended, isLoanReversal, move as engineMove } from 'container-engine'; import type { GameState, Move } from 'container-engine'; @@ -2149,13 +2149,9 @@ export default class Game extends Vue { logReversed.push('New event: ' + log.event.name); } } else if (log.type == 'move') { - const bankMessage = offshoreJournal(log, this.G!); + const bankMessage = offshoreJournal(log, this.G!, true, this.preferences.colorBlind); logReversed.push( - journalPieces( - bankMessage ? escapeJournal(bankMessage) : log.pretty, - this.preferences.colorBlind, - this.playerColors - ) + journalPieces(bankMessage || log.pretty, this.preferences.colorBlind, this.playerColors) ); } }); diff --git a/viewer/src/journal-pieces.ts b/viewer/src/journal-pieces.ts index 790122d..fa4a40b 100644 --- a/viewer/src/journal-pieces.ts +++ b/viewer/src/journal-pieces.ts @@ -1,4 +1,5 @@ import { playerColors as defaults } from 'container-engine/src/engine'; +import { ContainerColor, containerColors } from 'container-engine/src/gamestate'; import { colorMarkSvg } from './color-blind'; import { playerTextColor } from './player-colors'; function pieceIcon(kind: string, color = '', colorBlind = false): string { @@ -14,6 +15,11 @@ function pieceIcon(kind: string, color = '', colorBlind = false): string { }`; } +/** Only engine palette values may reach the SVG markup generator. */ +export function journalContainerIcon(color: ContainerColor, colorBlind = false): string { + return containerColors.includes(color) ? pieceIcon('container', color, colorBlind) : ''; +} + export function journalPieces(html: string, colorBlind = false, playerColors: string[] = []): string { const root = document.createElement('div'); root.innerHTML = html; diff --git a/viewer/src/offshore-journal.ts b/viewer/src/offshore-journal.ts index e9f76a1..8cf6835 100644 --- a/viewer/src/offshore-journal.ts +++ b/viewer/src/offshore-journal.ts @@ -1,17 +1,40 @@ -import { GameState, ShipPosition } from 'container-engine/src/gamestate'; +import { playerColors } from 'container-engine/src/engine'; +import { ContainerColor, containerColors, GameState, ShipPosition } from 'container-engine/src/gamestate'; import { LogMove } from 'container-engine/src/log'; import { MoveName } from 'container-engine/src/move'; +import { journalContainerIcon } from './journal-pieces'; /** Public bank moves carry enough information for useful prose without exposing secrets. */ -export function offshoreJournal(entry: LogMove, state: GameState): string | undefined { - const player = state.players?.[entry.player]?.name || String(entry.player + 1); +export function offshoreJournal( + entry: LogMove, + state: GameState, + rich = false, + colorBlind = false +): string | undefined { + const text = (value: unknown) => (rich ? escapeJournal(String(value)) : String(value)); + const name = state.players?.[entry.player]?.name || String(entry.player + 1); + // Match the ordinary engine badge; journalPieces applies the user's seat colors. + const badge = rich ? document.createElement('span') : undefined; + if (badge) { + badge.style.backgroundColor = playerColors[entry.player] || ''; + badge.style.fontWeight = 'bold'; + badge.style.padding = '0 3px'; + badge.textContent = name; + } + const player = badge?.outerHTML || name; + const container = (color: unknown) => + rich && containerColors.includes(color as ContainerColor) + ? journalContainerIcon(color as ContainerColor, colorBlind) + : text(color === 'darkslategray' ? 'dark green' : color); const move = entry.move; if (move.name === MoveName.CallBank) { return move.data.type === 'cash' - ? `${player} calls bank for cash lot ${move.data.lot + 1}: ${ - move.extraData.containers?.length || 0 + ? `${player} calls bank for cash lot ${text(move.data.lot + 1)}: ${ + rich ? escrowIcons(entry, state, colorBlind) : move.extraData.containers?.length || 0 } containers in escrow.` - : `${player} calls bank for container lot ${move.data.lot + 1}: $${move.extraData.cash} in escrow.`; + : `${player} calls bank for container lot ${text(move.data.lot + 1)}: $${text( + move.extraData.cash + )} in escrow.`; } if (move.name === MoveName.Sail && move.data === ShipPosition.OffshoreBank) return `${player} sails to the offshore bank.`; @@ -24,9 +47,9 @@ export function offshoreJournal(entry: LogMove, state: GameState): string | unde ].includes(move.name) ) { const action = move as import('container-engine/src/move').Moves.MoveBankContainer; - const color = action.data.color === 'darkslategray' ? 'dark green' : action.data.color; + const color = container(action.data.color || historicalColor(action.data.id, entry, state) || 'unknown'); if (action.name === MoveName.ReturnBankContainer) - return `${player} returns a ${color} container at $${action.extraData?.price}.`; + return `${player} returns a ${color} container at $${text(action.extraData?.price)}.`; if (action.name === MoveName.DistributeBankContainer) return `${player} distributes a ${color} container to the bank.`; if (action.name === MoveName.SeizeBankContainer) @@ -38,3 +61,41 @@ export function offshoreJournal(entry: LogMove, state: GameState): string | unde export function escapeJournal(text: string): string { return text.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); } + +/** Resolve immutable public piece identity, never a live escrow/decision (which may be gone). + * Historical payloads normally include color; ID-only wire payloads use setup's stable + * C color blocks, four containers per seat per color. No bids or secret state are read. + */ +function historicalColor(id: string, entry: LogMove, state: GameState): ContainerColor | undefined { + const history = state.log || []; + // If the entry is detached from this replay snapshot, use only the stable ID, + // rather than accidentally consulting later actions. + for (const item of history.slice(0, Math.max(0, history.indexOf(entry)))) { + if (item.type !== 'move') continue; + const data = item.move.data as { + id?: string; + color?: ContainerColor; + piece?: { id: string; color: ContainerColor }; + }; + const piece = data?.piece || data; + if (piece?.id === id && containerColors.includes(piece.color!)) return piece.color; + } + const match = /^C(0|[1-9]\d*)$/.exec(id); + const perColor = state.players.length * 4; + return match && perColor ? containerColors[Math.floor(Number(match[1]) / perColor)] : undefined; +} + +function escrowIcons(entry: LogMove, state: GameState, colorBlind: boolean): string { + if (entry.move.name !== MoveName.CallBank) return ''; + const ids = entry.move.extraData.containers || []; + if (!ids.length) return '0'; + // One opaque localization slot for the entire list, including unknown-ID fallback. + const list = document.createElement('span'); + ids.forEach((id, index) => { + if (index) list.append(document.createTextNode(' ')); + const color = historicalColor(id, entry, state); + if (color) list.insertAdjacentHTML('beforeend', journalContainerIcon(color, colorBlind)); + else list.append(document.createTextNode('?')); + }); + return list.outerHTML; +} diff --git a/viewer/tests/unit/offshore-journal.spec.ts b/viewer/tests/unit/offshore-journal.spec.ts new file mode 100644 index 0000000..17eae63 --- /dev/null +++ b/viewer/tests/unit/offshore-journal.spec.ts @@ -0,0 +1,128 @@ +import Game from '@/components/Game.vue'; +import { journalContainerIcon, journalPieces } from '@/journal-pieces'; +import fr from '@/localization/fr.json'; +import { mountLocalization } from '@/localization/runtime.js'; +import { offshoreJournal } from '@/offshore-journal'; +import { setup, stripSecret } from 'container-engine/src/engine'; +import { ContainerColor, ShipPosition } from 'container-engine/src/gamestate'; +import { LogMove } from 'container-engine/src/log'; +import { Move, MoveName } from 'container-engine/src/move'; +import { describe, expect, it } from 'vitest'; + +const entry = (move: Move): LogMove => ({ type: 'move', player: 0, move, pretty: '', simple: '' }); +const cashCall = () => + entry({ name: MoveName.CallBank, data: { type: 'cash', lot: 2 }, extraData: { containers: ['C12', 'C0', 'C36'] } }); +function fixture() { + const state = setup(3, { offshoreIsland: true }, 'journal'); + state.players[0].name = 'Draw & "Ada"'; + return state; +} +function render(log: LogMove, state = fixture(), blind = true) { + const root = document.createElement('div'); + root.innerHTML = journalPieces(offshoreJournal(log, state, true, blind)!, blind, ['#123456']); + return root; +} + +describe('Offshore rich journal', () => { + it('matches ordinary badges, applies custom colors, escapes names exactly once and lists escrow pictograms', () => { + const state = fixture(); + const root = render(cashCall(), state); + const badge = root.querySelector('[data-localized-journal] > span')! as HTMLElement; + expect(badge.textContent).toBe(state.players[0].name); + expect(badge.style.backgroundColor).toBe('rgb(18, 52, 86)'); + expect(badge.style.fontWeight).toBe('bold'); + expect(root.querySelector('img')).toBeNull(); + expect(root.querySelectorAll('svg[role="img"]')).toHaveLength(3); + expect(root.querySelectorAll('.color-mark')).toHaveLength(3); + expect([...root.querySelectorAll('svg[role="img"]')].map((el) => el.getAttribute('aria-label'))).toEqual([ + 'brown container', + 'orange container', + 'dark green container', + ]); + expect(render(cashCall(), state, false).querySelector('.color-mark')).toBeNull(); + const ordinary = journalPieces( + 'Ada produces a brown container', + true, + ['#123456'] + ); + const normal = document.createElement('div'); + normal.innerHTML = ordinary; + expect(root.querySelector('svg[role="img"]')!.outerHTML).toBe( + normal.querySelector('svg[role="img"]')!.outerHTML + ); + }); + + it('survives settled escrow, stripped states and replay without consulting current pieces', () => { + const state = fixture(); + const call = cashCall(); + state.log = [call]; + const before = render(call, state).innerHTML; + state.offshoreBank!.auctions = []; + state.containersLeft = []; + for (const p of state.players) { + p.containersOnFactoryStore = []; + p.containersOnWarehouseStore = []; + } + const publicState = stripSecret(JSON.parse(JSON.stringify(state)), 1); + expect(render(publicState.log[0] as LogMove, publicState).innerHTML).toBe(before); + const context = { G: publicState, preferences: { colorBlind: true }, playerColors: ['#123456'] }; + expect((Game as any).options.computed.logReversed.get.call(context)[0]).toBe(before); + }); + + it('uses public historical piece snapshots before the stable-ID fallback', () => { + const state = fixture(); + const call = cashCall(); + state.log = [ + entry({ name: MoveName.LoadBankContainer, data: { id: 'C12', color: ContainerColor.White } }), + call, + ]; + expect(render(call, state).querySelector('svg[role="img"]')!.getAttribute('aria-label')).toBe( + 'white container' + ); + }); + + it.each([ + MoveName.ReturnBankContainer, + MoveName.DistributeBankContainer, + MoveName.SeizeBankContainer, + MoveName.LoadBankContainer, + ] as const)('renders %s with a badge and pictogram', (name) => { + const log = entry({ name, data: { id: 'C36', color: ContainerColor.Black }, extraData: { price: 3 } }); + const root = render(log); + expect(root.querySelectorAll('svg[role="img"]')).toHaveLength(1); + expect(root.querySelector('.color-mark')).not.toBeNull(); + if (name === MoveName.ReturnBankContainer) expect(root.textContent).toContain('$3'); + delete (log.move.data as any).color; + expect(render(log).innerHTML).toBe(root.innerHTML); + }); + + it('preserves French prose and opaque player/icon slots across locale switches', () => { + const state = fixture(); + const root = render(cashCall(), state); + document.body.append(root); + const localization = mountLocalization(root, { fr }, 'fr'); + expect(root.textContent).toContain('appelle la banque'); + expect(root.textContent).toContain(state.players[0].name); + expect(root.querySelectorAll('.color-mark')).toHaveLength(3); + localization.setLocale('en'); + expect(root.textContent).toContain('calls bank'); + expect(root.textContent).toContain(state.players[0].name); + localization.destroy(); + }); + + it('keeps cash and plain text logs intact, badges sailing, and rejects injected metadata', () => { + const state = fixture(); + const call = entry({ name: MoveName.CallBank, data: { type: 'containers', lot: 0 }, extraData: { cash: 7 } }); + expect(render(call, state).textContent).toContain('$7 in escrow.'); + expect(offshoreJournal(cashCall(), state)).toContain('3 containers in escrow.'); + expect(render(entry({ name: MoveName.Sail, data: ShipPosition.OffshoreBank })).textContent).toContain( + 'sails to the offshore bank.' + ); + (call.move as any).extraData.cash = ''; + expect(render(call).querySelector('img')).toBeNull(); + expect(journalContainerIcon('" onload="alert(1)' as ContainerColor)).toBe(''); + expect( + offshoreJournal(entry({ name: MoveName.Bid, data: true, extraData: { price: 99 } }), state, true) + ).toBeUndefined(); + }); +});