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

This commit is contained in:
coyotte508 2026-09-24 11:44:29 +02:00
commit 52e1fcbc16
9 changed files with 223 additions and 10 deletions

View file

@ -1,6 +1,6 @@
{
"name": "outpost-viewer",
"version": "0.1.3",
"version": "0.1.4",
"description": "Browser viewer for the Outpost game on boardgamers.space",
"license": "AGPL-3.0",
"files": [
@ -16,7 +16,7 @@
"preview": "vite preview"
},
"dependencies": {
"@boardgamers/protocol": "0.5.0",
"@boardgamers/protocol": "0.6.0",
"outpost-engine": "workspace:*"
},
"devDependencies": {

View file

@ -0,0 +1,144 @@
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

@ -113,7 +113,7 @@
></button>
{/if}
<div class="head">
<button class="identity" onclick={() => onNameClick?.(index)} title={player.name}>
<button data-bgs-player={index} class="identity" onclick={() => onNameClick?.(index)} title={player.name}>
{#if orderPos > 0}
<span
class="order"

View file

@ -36,6 +36,9 @@ export const mountTutorial: TutorialMount = async (target, { chapter, onProgress
return true;
},
openPlayer: () => false,
hoverPlayer: () => false,
leavePlayer: () => false,
openBoardgame: () => false,
updatePreference: () => false,
updateSetting: () => false,
fetchState: () => false,

View file

@ -1,3 +1,4 @@
import { installPlayerCards, createBoardThumbnail } from "./host-presentation";
import { mount, tick, unmount } from "svelte";
import { registerViewer } from "@boardgamers/protocol/viewer";
import type { GameState, Move } from "outpost-engine";
@ -16,8 +17,14 @@ registerViewer<GameState, Move>(
target: commands.target,
props: { store, onPlayerClick: commands.openPlayer },
});
const removeCards = installPlayerCards(commands.target, commands);
const thumbnail = createBoardThumbnail(commands.target);
return {
chat: store.chat,
async onThumbnail(size) {
await tick();
return thumbnail.render(commands.target.querySelector(".main"), size, "#0a1421", ".side");
},
async onState(state) {
sounds.onState(state);
store.setState(state);
@ -48,6 +55,8 @@ registerViewer<GameState, Move>(
store.endReplay();
},
destroy() {
removeCards();
thumbnail.destroy();
store.destroy();
sounds.destroy();
void unmount(app);

10
pnpm-lock.yaml generated
View file

@ -40,8 +40,8 @@ importers:
packages/viewer:
dependencies:
'@boardgamers/protocol':
specifier: 0.5.0
version: 0.5.0
specifier: 0.6.0
version: 0.6.0
outpost-engine:
specifier: workspace:*
version: link:../engine
@ -67,8 +67,8 @@ importers:
packages:
'@boardgamers/protocol@0.5.0':
resolution: {integrity: sha512-9SjU0cSktwxeMLItCW5VmUeSFl3Kg965JkKFf+BKZBxR2a2dyFoMKE3RYN2+ZwrI6GNS1mA6Fki9HOHQnD2WRw==}
'@boardgamers/protocol@0.6.0':
resolution: {integrity: sha512-byHV2eOOFpnQCnhLaM0LPUpT30ew1aAOuTIYxwztkVjg4NgeTyPwjU8Efmc/xi+DGCrfIjo2LTb7YlNUhmzy0g==}
'@jridgewell/gen-mapping@0.3.13':
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
@ -772,7 +772,7 @@ packages:
snapshots:
'@boardgamers/protocol@0.5.0':
'@boardgamers/protocol@0.6.0':
dependencies:
zod: 4.6.2

View file

@ -1,5 +1,4 @@
packages:
- "packages/*"
minimumReleaseAgeExclude:
- "@boardgamers/protocol@0.4.0 || 0.4.2 || 0.5.0"
- "@boardgamers/protocol@0.3.1 || 0.3.3"
- "@boardgamers/protocol@0.3.1 || 0.3.3 || 0.4.0 || 0.4.2 || 0.5.0 || 0.6.0"

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 { chromium } from "playwright";
import { initGame } from "../packages/engine/dist/index.js";
@ -216,6 +217,12 @@ try {
assert.equal(await page.getByText("Stale chat", { exact: true }).count(), 0);
assert.equal(await page.evaluate(() => oldEmitter.emit("state:updated")), false);
assert.deepEqual(errors, []);
await page.evaluate((state) => {
emitter.emit("player", {});
emitter.emit("state", state);
}, stripSecret(state));
await checkHostPresentation(page, "emitter", `/tmp/outpost-board-thumbnail-${width}.png`);
assert.deepEqual(errors, []);
await page.close();
}
console.log("Outpost protocol: mobile/desktop chat, mentions, reads, drafts, replay, refresh and relaunch passed.");