feat(viewer): add player hover cards and board thumbnails

This commit is contained in:
coyotte508 2026-09-24 11:44:12 +02:00
commit 09de708a47
8 changed files with 202 additions and 8 deletions

View file

@ -3,4 +3,4 @@ packages:
- 'engine'
minimumReleaseAgeExclude:
- '@boardgamers/protocol@0.4.0'
- '@boardgamers/protocol@0.4.0 || 0.4.2 || 0.5.0 || 0.6.0'

View file

@ -1,6 +1,6 @@
{
"name": "powergrid-viewer",
"version": "2.1.11",
"version": "2.1.12",
"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.5.0",
"@boardgamers/protocol": "0.6.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.5.0
'@boardgamers/protocol': 0.6.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.5.0
'@boardgamers/protocol': 0.6.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.5.0:
/@boardgamers/protocol/0.6.0:
resolution:
{
integrity: sha512-9SjU0cSktwxeMLItCW5VmUeSFl3Kg965JkKFf+BKZBxR2a2dyFoMKE3RYN2+ZwrI6GNS1mA6Fki9HOHQnD2WRw==,
integrity: sha512-byHV2eOOFpnQCnhLaM0LPUpT30ew1aAOuTIYxwztkVjg4NgeTyPwjU8Efmc/xi+DGCrfIjo2LTb7YlNUhmzy0g==,
}
dependencies:
zod: 4.6.4

View file

@ -0,0 +1,51 @@
import assert from 'node:assert/strict';
export async function checkHostPresentation(page, hostName, screenshot) {
await page.evaluate((key) => {
window.presentationEvents = [];
for (const name of ['player:hovered', 'thumbnail:ready', 'move']) {
window[key].on(name, (data) => presentationEvents.push({ name, data }));
}
}, hostName);
const name = page.locator('[data-bgs-player]:visible').first();
await name.hover();
const index = Number(await name.getAttribute('data-bgs-player'));
await page.waitForFunction(() => presentationEvents.some((e) => e.name === 'player:hovered' && e.data));
const hover = await page.evaluate(() => presentationEvents.findLast((e) => e.name === 'player:hovered').data);
assert.equal(hover.index, index);
assert.ok(hover.anchor.width > 0 && hover.anchor.height > 0);
await name.dispatchEvent('mouseout', { relatedTarget: null });
assert.equal(await page.evaluate(() => presentationEvents.findLast((e) => e.name === 'player:hovered').data), null);
const focusable = page.locator('button[data-bgs-player]:visible, [data-bgs-player][tabindex]:visible').first();
await focusable.focus();
assert.ok(await page.evaluate(() => presentationEvents.findLast((e) => e.name === 'player:hovered').data));
await focusable.blur();
assert.equal(await page.evaluate(() => presentationEvents.findLast((e) => e.name === 'player:hovered').data), null);
await page.setViewportSize({ width: 1200, height: 900 });
await page.evaluate((key) => {
window[key].emit('preferences', { sound: false, thumbnail: true });
window[key].emit('player', {});
window[key].emit('thumbnail:render', { width: 1200, height: 630 });
}, hostName);
await page.waitForFunction(() => presentationEvents.some((e) => e.name === 'thumbnail:ready'), null, {
timeout: 5000,
});
const result = await page.evaluate(() => presentationEvents.findLast((e) => e.name === 'thumbnail:ready').data);
assert.equal(result.supported, true);
assert.deepEqual(result.bounds, { x: 0, y: 0, width: 1200, height: 630 });
assert.equal(await page.locator('.bgs-board-thumbnail').count(), 1);
assert.ok(
await page.locator('.bgs-board-thumbnail').evaluate((preview) =>
[...preview.querySelectorAll('path, rect, circle, text, image, button')].some((node) => {
const bounds = node.getBoundingClientRect();
return bounds.width > 20 && bounds.height > 10;
})
),
'the preview contains visible board content'
);
await page.locator('.bgs-board-thumbnail').screenshot({ path: screenshot });
await page.evaluate((key) => window[key].emit('thumbnail:render', { width: 1200, height: 630 }), hostName);
await page.waitForFunction(() => presentationEvents.filter((e) => e.name === 'thumbnail:ready').length === 2);
assert.equal(await page.locator('.bgs-board-thumbnail').count(), 1, 'a repeated capture replaces the previous one');
assert.equal(await page.evaluate(() => presentationEvents.filter((e) => e.name === 'move').length), 0);
}

View file

@ -1,3 +1,4 @@
import { checkHostPresentation } from './host-presentation-smoke.mjs';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { createServer } from 'node:http';
@ -286,6 +287,8 @@ try {
assert.equal(await page.locator('.bgs-game-chat').count(), 1);
assert.equal(await page.locator('.chat-messages article').count(), 0, 'relaunch detaches old chat');
assert.deepEqual(errors, [], 'no browser errors');
await checkHostPresentation(page, 'host', `/tmp/powergrid-board-thumbnail-${width}.png`);
assert.deepEqual(errors, []);
await page.close();
console.log(`${game} ${width}px: protocol/chat smoke passed`);
}

View file

@ -10,7 +10,15 @@
style="border-radius: 50%"
/>
</foreignObject>
<text x="5" y="13" font-weight="600" fill="black">
<text
:data-bgs-player="owner"
style="pointer-events: all"
tabindex="0"
x="5"
y="13"
font-weight="600"
fill="black"
>
{{ getPlayerName() }}
</text>
<text v-if="showMoney" x="250" y="13" font-weight="600" fill="black">Money: ${{ player.money }}</text>

View file

@ -0,0 +1,123 @@
type PlayerCommands = {
hoverPlayer(index: number, anchor: DOMRect): boolean;
leavePlayer(): boolean;
};
export function installPlayerCards(root: Element, commands: PlayerCommands) {
let active: Element | null = null;
function show(event: Event) {
const name = event.target instanceof Element ? event.target.closest('[data-bgs-player]') : null;
if (!name || !root.contains(name) || name === active) return;
const index = Number(name.getAttribute('data-bgs-player'));
if (!Number.isInteger(index) || index < 0) return;
active = name;
commands.hoverPlayer(index, name.getBoundingClientRect());
}
function hide(event: Event) {
if (!active) return;
const related = (event as MouseEvent | FocusEvent).relatedTarget;
if (related instanceof Node && active.contains(related)) return;
active = null;
commands.leavePlayer();
}
root.addEventListener('mouseover', show);
root.addEventListener('focusin', show);
root.addEventListener('mouseout', hide);
root.addEventListener('focusout', hide);
return () => {
root.removeEventListener('mouseover', show);
root.removeEventListener('focusin', show);
root.removeEventListener('mouseout', hide);
root.removeEventListener('focusout', hide);
if (active) commands.leavePlayer();
};
}
export function createBoardThumbnail(root: Element) {
let preview: HTMLDivElement | undefined;
function destroy() {
preview?.remove();
preview = undefined;
}
async function render(
source: Element | null,
size: { width: number; height: number },
background: string,
omit?: string
) {
destroy();
if (!source?.isConnected || !root.contains(source)) return null;
await document.fonts.ready;
preview = document.createElement('div');
preview.className = 'bgs-board-thumbnail';
preview.setAttribute('aria-hidden', 'true');
preview.style.cssText = `position:fixed;inset:0 auto auto 0;width:${size.width}px;height:${size.height}px;z-index:2147483647;overflow:hidden;pointer-events:none;background:${background};`;
const freeze = document.createElement('style');
freeze.textContent =
'.bgs-board-thumbnail *{animation:none!important;transition:none!important;caret-color:transparent!important}';
preview.append(freeze);
let content: HTMLElement | SVGSVGElement;
if (source instanceof SVGElement) {
const svg = source instanceof SVGSVGElement ? source : source.ownerSVGElement;
if (!svg) return null;
content = svg.cloneNode(false) as SVGSVGElement;
content.removeAttribute('id');
const box =
source instanceof SVGSVGElement ? source.viewBox.baseVal : (source as SVGGraphicsElement).getBBox();
if (!box.width || !box.height) return null;
const padding = source === svg ? 0 : Math.max(box.width, box.height) * 0.02;
content.setAttribute(
'viewBox',
`${box.x - padding} ${box.y - padding} ${box.width + padding * 2} ${box.height + padding * 2}`
);
if (source === svg) {
for (const child of Array.from(source.childNodes)) content.append(child.cloneNode(true));
} else {
for (const defs of Array.from(svg.querySelectorAll('defs'))) content.append(defs.cloneNode(true));
const copy = source.cloneNode(true) as SVGElement;
copy.removeAttribute('transform');
content.append(copy);
}
content.setAttribute('preserveAspectRatio', 'xMidYMid meet');
content.style.cssText =
'display:block;position:static;width:100%;height:100%;max-width:none;max-height:none;min-width:0;margin:0;transform:none';
} else {
content = source.cloneNode(true) as HTMLElement;
content.style.cssText = `display:flex;flex-direction:column;gap:14px;position:relative;width:${size.width}px;max-width:none;margin:0;transform-origin:top left;`;
}
if (omit) for (const element of Array.from(content.querySelectorAll(omit))) element.remove();
// Keep ancestor-dependent styles without their clipping or stacking contexts.
let parent: Element = preview;
const ancestors: Element[] = [];
for (
let ancestor = source.parentElement;
ancestor && ancestor !== document.body;
ancestor = ancestor.parentElement
) {
if (!(ancestor instanceof SVGElement)) {
ancestors.unshift(ancestor);
}
}
for (const ancestor of ancestors) {
const context = ancestor.cloneNode(false) as HTMLElement;
context.removeAttribute('id');
context.style.cssText =
'display:contents!important;transform:none!important;filter:none!important;contain:none!important';
parent.append(context);
parent = context;
}
parent.append(content);
document.body.append(preview);
if (!(content instanceof SVGSVGElement)) {
const box = content.getBoundingClientRect();
const scale = Math.min(1, size.width / box.width, size.height / box.height);
content.style.transform = `translate(${(size.width - box.width * scale) / 2}px, ${
(size.height - box.height * scale) / 2
}px) scale(${scale})`;
}
await Promise.all(Array.from(preview.querySelectorAll('img')).map((img) => img.decode().catch(() => {})));
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
return preview;
}
return { render, destroy };
}

View file

@ -1,3 +1,4 @@
import { installPlayerCards, createBoardThumbnail } from './host-presentation';
import { createViewer } from '@boardgamers/protocol/viewer';
import { EventEmitter } from 'events';
import type { GameState, Move } from 'powergrid-engine';
@ -51,8 +52,13 @@ function launch(selector: string) {
render: (h) => h(Game, { props: params }, []),
}).$mount(mountPoint);
const thumbnail = createBoardThumbnail(app.$el);
let replaying = false;
const viewer = createViewer<GameState, Move[] | PremoveCommand>({
async onThumbnail(size) {
await app.$nextTick();
return thumbnail.render(app.$el.querySelector('[data-tutorial="map"]'), size, '#e7e6df');
},
async onState(data) {
params.state = data;
app.$forceUpdate();
@ -105,8 +111,11 @@ function launch(selector: string) {
params.emitter.on('replay:info', (info) => viewer.setReplayInfo(info));
params.emitter.on('update:preference', ({ name, value }) => viewer.updatePreference(name, value));
installActionSounds(item);
const removeCards = installPlayerCards(app.$el, viewer);
const removeChat = mountGameChat(item, app.$el);
app.$once('hook:beforeDestroy', () => {
removeCards();
thumbnail.destroy();
removeChat();
viewer.destroy();
params.emitter.removeAllListeners();