Support manual analyses and translated chat

This commit is contained in:
coyotte508 2026-09-21 20:32:10 +02:00
commit 4bf7a2aa90
10 changed files with 107 additions and 10 deletions

View file

@ -1,6 +1,6 @@
{
"name": "powergrid-engine",
"version": "2.0.8",
"version": "2.0.9",
"description": "An engine for Power Grid",
"main": "dist/index.js",
"types": "index.ts",

View file

@ -528,3 +528,22 @@ describe('wrapper (tentative turns)', () => {
expect(result.players[current[0]].availableMoves).to.not.be.null;
});
});
describe('analysis adapter', () => {
it('clears automation, preserves tentative turns and keeps every seat manual', async () => {
const source = setup(3, {}, 'analysis');
source.players[1].isDropped = true;
const original = json(source);
let copy = wrapper.createAnalysis(source, { to: source.log.length, sourceEnded: true });
expect(copy.players.every((p) => !p.isDropped)).to.equal(true);
expect(copy.automation).to.equal(undefined);
const actor = copy.currentPlayers[0];
const available = copy.players[actor].availableMoves!;
const name = Object.keys(available)[0] as MoveName;
const data = (available[name] as any[])[0];
copy = await wrapper.analysisMove(copy, { name, data } as Move, actor);
expect(copy.automation).to.equal(undefined);
expect(copy.log.length).to.be.greaterThan(original.log.length);
expect(json(source)).to.deep.equal(original);
});
});

View file

@ -304,3 +304,20 @@ export function logSlice(G: GameState, options?: { player?: number; start?: numb
.players.map((pl) => pl.availableMoves),
};
}
export function createAnalysis(data: GameState, { to }: { to: number; sourceEnded: boolean }): GameState {
if (!Number.isInteger(to) || to < 0 || to > data.log.length) throw new Error('Invalid history position');
const copy = replay(JSON.parse(JSON.stringify(data)), { to });
delete copy.automation;
for (const player of copy.players) player.isDropped = false;
copy.newTurn = true;
return copy;
}
export async function analysisMove(data: GameState, input: Move | Move[], player: number): Promise<GameState> {
if (isPremoveCommand(input)) throw new Error('Premoves are not available in an analysis');
delete data.automation;
const result = await move(data, input, player);
delete result.automation;
return result;
}

View file

@ -1,3 +1,6 @@
packages:
- 'viewer'
- 'engine'
minimumReleaseAgeExclude:
- '@boardgamers/protocol@0.4.0'

View file

@ -1,6 +1,6 @@
{
"name": "powergrid-viewer",
"version": "2.1.8",
"version": "2.1.9",
"repository": {
"type": "git",
"url": "git+https://github.com/boardgamers/powergrid.git",
@ -23,7 +23,7 @@
"tutorial:manifest": "node scripts/tutorial-manifest.cjs"
},
"dependencies": {
"@boardgamers/protocol": "0.3.3",
"@boardgamers/protocol": "0.4.0",
"core-js": "^3.6.5",
"lodash": "^4.17.19",
"powergrid-engine": "workspace:../engine",

8
viewer/pnpm-lock.yaml generated
View file

@ -1,7 +1,7 @@
lockfileVersion: 5.4
specifiers:
'@boardgamers/protocol': 0.3.3
'@boardgamers/protocol': 0.4.0
'@types/assert': ^1.4.7
'@types/chai': ^4.2.11
'@types/events': ^3.0.0
@ -34,7 +34,7 @@ specifiers:
zod: 4.6.4
dependencies:
'@boardgamers/protocol': 0.3.3
'@boardgamers/protocol': 0.4.0
core-js: 3.12.1
lodash: 4.17.21
powergrid-engine: link:../engine
@ -1464,10 +1464,10 @@ packages:
to-fast-properties: 2.0.0
dev: true
/@boardgamers/protocol/0.3.3:
/@boardgamers/protocol/0.4.0:
resolution:
{
integrity: sha512-AS+x84WHXRudW6xt/s/5I3xYmNTQFbZEBp3V+41w0I2RirSr2fWjYnYf0p11nwTbZ6G5upivKz/sjYLtk8HOYA==,
integrity: sha512-dqrU94QGPZAh7vWhHmu2AHY6bFo7NbNVytb3dyUidou8R6P0FfT3xm0qLR8LbrE4EHEYmm99LajdfTfKmgwEzQ==,
}
dependencies:
zod: 4.6.4

View file

@ -228,6 +228,48 @@ try {
1,
'tentative move state is rendered without fetching a committed state'
);
await page.evaluate(() => {
window.translationsRequested = [];
host.on('chat:translate', (request) => {
translationsRequested.push(request);
host.emit('chat:translation', { ...request, ok: true, text: 'Bonjour <img src=x>', language: 'en' });
});
host.emit('chat:state', {
canSend: true,
translationTarget: 'fr',
translationLabels: {
translate: 'Traduire',
translating: 'Traduction…',
translated: 'Traduit',
original: 'Voir l’original',
error: 'Indisponible',
retry: 'Réessayer',
},
});
host.emit('chat:messages', [
{ _id: '000000000000000000000070', type: 'text', text: 'Hello', language: 'en' },
]);
});
await page.locator('.chat-translate').click();
await page.getByRole('button', { name: 'Traduit · Voir l’original', exact: true }).waitFor();
assert.equal(await page.evaluate(() => translationsRequested.length), 1);
assert.equal(await page.locator('[data-message-id="000000000000000000000070"] img').count(), 0);
assert.match(
await page.locator('[data-message-id="000000000000000000000070"]').textContent(),
/Bonjour <img src=x>/
);
await page.locator('.chat-translate').click();
assert.match(await page.locator('[data-message-id="000000000000000000000070"]').textContent(), /Hello/);
assert.equal(
await page.evaluate(() => translationsRequested.length),
1,
'showing original needs no new request'
);
await page.evaluate(() => host.emit('preferences', { sound: false, analysis: true }));
await page.waitForFunction(() => !document.querySelector('.chat-translate')?.getBoundingClientRect().height);
await page.screenshot({ path: '/tmp/powergrid-analysis-' + width + '.png', fullPage: true });
await page.evaluate(() => host.emit('preferences', { sound: false, analysis: false }));
await page.screenshot({ path: `/tmp/${game}-protocol-${width}.png`, fullPage: true });
await page.evaluate(
({ state, incoming }) => {

View file

@ -1094,6 +1094,7 @@ export default class Game extends Vue {
get canPlanRound(): boolean {
return (
!this.preferences.analysis &&
!this.tutorialMove &&
!this.paused &&
!this.interactionDisabled &&
@ -1103,13 +1104,18 @@ export default class Game extends Vue {
);
}
get canPreparePremoves(): boolean {
return !!this.committedState && this.player != null && canQueuePhases(this.committedState, this.player, []);
return (
!this.preferences.analysis &&
!!this.committedState &&
this.player != null &&
canQueuePhases(this.committedState, this.player, [])
);
}
get hasPlanPanel(): boolean {
return !!(this.roundPlan || this.planningError || this.pendingPlanId);
}
get myPhaseQueue() {
return this.committedState?.automation?.plans[this.player!];
return this.preferences.analysis ? undefined : this.committedState?.automation?.plans[this.player!];
}
get queuedMoveCount(): number {
return (this.myPhaseQueue?.phases || []).reduce(

View file

@ -31,6 +31,7 @@ export function mountGameChat(emitter: ViewerEmitter<any, any>, host: Element):
.bgs-game-chat button:disabled{color:#788786;border-color:#b0bcb8;background:#dce3df;cursor:default}
.bgs-game-chat .chat-mention{height:auto;padding:0 2px;border:0;background:transparent;color:inherit;font:inherit;font-weight:bold;text-decoration:underline}
.bgs-game-chat article a{color:inherit;text-decoration:underline}
.bgs-game-chat .chat-translate{height:auto;min-height:24px;padding:2px 4px;margin-left:6px;border:0;background:transparent;color:inherit;font-size:.8em;text-decoration:underline}
.chat-suggestions{display:flex;flex-wrap:wrap;gap:4px;margin-top:4px}
.chat-suggestions:empty{display:none}
.chat-suggestions button[aria-pressed="true"]{outline:2px solid #527f89}
@ -56,6 +57,7 @@ export function mountGameChat(emitter: ViewerEmitter<any, any>, host: Element):
let players: { id: number; name: string; color?: string; faction?: string }[] = [];
let localPlayer: number | undefined;
let chatVisible = false;
let analysis = false;
const shortcut = document.createElement('button');
shortcut.type = 'button';
shortcut.className = 'chat-shortcut';
@ -137,7 +139,7 @@ export function mountGameChat(emitter: ViewerEmitter<any, any>, host: Element):
const count = chat.unread;
const label = count ? `Chat · ${count} unread` : 'Chat';
shortcutCount.textContent = String(count);
shortcut.hidden = chatVisible || !count;
shortcut.hidden = analysis || chatVisible || !count;
shortcut.setAttribute('aria-label', `Open ${label}`);
chatTab.textContent = label;
positionShortcut();
@ -148,6 +150,13 @@ export function mountGameChat(emitter: ViewerEmitter<any, any>, host: Element):
};
const dispose = [
detach,
emitter.on('preferences', (preferences) => {
analysis = preferences.analysis === true;
slot.hidden = analysis;
tabs.style.display = analysis ? 'none' : '';
if (analysis) selectFeed('journal');
updateShortcut();
}),
chat.subscribe(updateShortcut),
emitter.on('state', (state) => {
players = (state?.players || []).map((player: any, index: number) => ({ ...player, id: index }));

View file

@ -5,6 +5,7 @@ export interface UIData {
}
export type Preferences = {
analysis?: boolean;
sound: boolean;
disableHelp: boolean;
adjustPlayerOrder: boolean;