feat(viewer): add player hover cards and board thumbnails
This commit is contained in:
parent
9f5f12333d
commit
6cc284cfa3
8 changed files with 269 additions and 9 deletions
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@boardgamers/primordial-soup",
|
||||
"version": "0.2.16",
|
||||
"version": "0.2.17",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist/engine.js",
|
||||
|
|
@ -14,7 +14,7 @@
|
|||
"test:browser": "pnpm build && node test/analysis-chat-browser.mjs && node test/preferences-browser.mjs && node test/new-genes-browser.mjs && node test/turn-controls-browser.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@boardgamers/protocol": "0.5.0",
|
||||
"@boardgamers/protocol": "0.6.0",
|
||||
"@noble/hashes": "2.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
|
|||
10
pnpm-lock.yaml
generated
10
pnpm-lock.yaml
generated
|
|
@ -9,8 +9,8 @@ importers:
|
|||
.:
|
||||
dependencies:
|
||||
'@boardgamers/protocol':
|
||||
specifier: 0.5.0
|
||||
version: 0.5.0
|
||||
specifier: 0.6.0
|
||||
version: 0.6.0
|
||||
'@noble/hashes':
|
||||
specifier: 2.0.1
|
||||
version: 2.0.1
|
||||
|
|
@ -27,8 +27,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==}
|
||||
|
||||
'@esbuild/aix-ppc64@0.25.12':
|
||||
resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==}
|
||||
|
|
@ -220,7 +220,7 @@ packages:
|
|||
|
||||
snapshots:
|
||||
|
||||
'@boardgamers/protocol@0.5.0':
|
||||
'@boardgamers/protocol@0.6.0':
|
||||
dependencies:
|
||||
zod: 4.6.5
|
||||
|
||||
|
|
|
|||
|
|
@ -2,4 +2,4 @@ allowBuilds:
|
|||
esbuild: true
|
||||
|
||||
minimumReleaseAgeExclude:
|
||||
- "@boardgamers/protocol@0.4.0 || 0.4.2 || 0.5.0"
|
||||
- '@boardgamers/protocol@0.4.0 || 0.4.2 || 0.5.0 || 0.6.0'
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import { checkHostPresentation } from "./host-presentation-smoke.mjs";
|
||||
import { prepared } from "../viewer/tutorials.js";
|
||||
import assert from "node:assert/strict";
|
||||
import { chromium } from "playwright";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
|
@ -107,6 +109,19 @@ try {
|
|||
});
|
||||
assert.deepEqual(errors, []);
|
||||
console.log(`${game} ${width}: translation/original/analysis passed`);
|
||||
await page.evaluate(
|
||||
(state) => {
|
||||
e.emit("player", {});
|
||||
e.emit("state", state);
|
||||
},
|
||||
engine.stripSecret(prepared({ genes: ["armor", "holding"] })),
|
||||
);
|
||||
await checkHostPresentation(
|
||||
page,
|
||||
"e",
|
||||
`/tmp/soup-board-thumbnail-${width}.png`,
|
||||
);
|
||||
assert.deepEqual(errors, []);
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
98
test/host-presentation-smoke.mjs
Normal file
98
test/host-presentation-smoke.mjs
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
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,
|
||||
);
|
||||
}
|
||||
131
viewer/host-presentation.js
Normal file
131
viewer/host-presentation.js
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
function installPlayerCards(root, commands) {
|
||||
let active = null;
|
||||
function show(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) {
|
||||
if (!active) return;
|
||||
const related = event.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();
|
||||
};
|
||||
}
|
||||
function createBoardThumbnail(root) {
|
||||
let preview;
|
||||
function destroy() {
|
||||
preview?.remove();
|
||||
preview = void 0;
|
||||
}
|
||||
async function render(source, size, background, omit) {
|
||||
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;
|
||||
if (source instanceof SVGElement) {
|
||||
const svg =
|
||||
source instanceof SVGSVGElement ? source : source.ownerSVGElement;
|
||||
if (!svg) return null;
|
||||
content = svg.cloneNode(false);
|
||||
content.removeAttribute("id");
|
||||
const box =
|
||||
source instanceof SVGSVGElement
|
||||
? source.viewBox.baseVal
|
||||
: source.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);
|
||||
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);
|
||||
content.style.cssText = `display:flex;flex-direction:column;gap:14px;position:relative;width:${source.getBoundingClientRect().width}px;height:${source.getBoundingClientRect().height}px;max-width:none;margin:0;transform-origin:top left;`;
|
||||
}
|
||||
if (omit)
|
||||
for (const element of Array.from(content.querySelectorAll(omit)))
|
||||
element.remove();
|
||||
let parent = preview;
|
||||
const ancestors = [];
|
||||
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);
|
||||
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((resolve) =>
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
|
||||
);
|
||||
return preview;
|
||||
}
|
||||
return { render, destroy };
|
||||
}
|
||||
export { createBoardThumbnail, installPlayerCards };
|
||||
|
|
@ -1,3 +1,7 @@
|
|||
import {
|
||||
createBoardThumbnail,
|
||||
installPlayerCards,
|
||||
} from "./host-presentation.js";
|
||||
import "./style.css";
|
||||
import { registerViewer } from "@boardgamers/protocol/viewer";
|
||||
import { ChatController } from "@boardgamers/protocol/chat";
|
||||
|
|
@ -75,8 +79,18 @@ registerViewer(
|
|||
ctx.move(m);
|
||||
}),
|
||||
});
|
||||
const thumbnail = createBoardThumbnail(ctx.target);
|
||||
const removeCards = installPlayerCards(ctx.target, ctx);
|
||||
return {
|
||||
chat,
|
||||
onThumbnail(size) {
|
||||
return thumbnail.render(
|
||||
ctx.target.querySelector(".board"),
|
||||
size,
|
||||
"#eef1e5",
|
||||
".pond-tools, .board-actions",
|
||||
);
|
||||
},
|
||||
onPreferences(preferences) {
|
||||
ui.setAnalysisMode(preferences.analysis === true);
|
||||
ui.setColorBlind(preferences[COLOR_BLIND_PREFERENCE.name] === true);
|
||||
|
|
@ -100,6 +114,8 @@ registerViewer(
|
|||
}
|
||||
},
|
||||
destroy() {
|
||||
removeCards();
|
||||
thumbnail.destroy();
|
||||
clearTimeout(timeout);
|
||||
pending?.resolve();
|
||||
ui.destroy();
|
||||
|
|
|
|||
|
|
@ -316,7 +316,7 @@ export function mountGame(
|
|||
$(".players").innerHTML = state.players
|
||||
.map(
|
||||
(p, i) =>
|
||||
`<button class="player ${i === actor ? "active" : ""}" data-player="${i}" style="--player:${colors[p.color].shade}"><span class="player-color"></span><span class="player-portrait">${amoeba(p.color, i, colonyTraits(p.genes))}</span><span class="player-info"><span class="player-name">${esc(p.name)}${i === seat && p.name !== "You" ? '<span class="you-tag">You</span>' : ""}</span><span class="player-stat"><span class="resource-amount player-population" role="img" aria-label="${colony(state, i).length} living amoebas" title="Living amoebas">${amoeba(p.color)}<span>${colony(state, i).length}</span></span><span aria-hidden="true">·</span><span class="resource-amount" role="img" aria-label="${geneCount(state, i)} genes" title="Genes">${icon("gene")}${geneCount(state, i)}</span></span></span><span class="player-balances"><span class="player-bp">${bp(p.bp)}</span><span class="player-sensitivity ${mutation(state, i) < 0 ? "protective" : ""}" role="img" aria-label="Total sensitivity ${mutation(state, i)}" title="${SENSITIVITY_HELP}">${icon("sun")}<b>${mutation(state, i)}</b></span><span class="player-score-group"><span class="player-score" title="Evolution points">${icon("spark")}${p.score}</span>${state.closed ? "" : `<span class="player-income" role="img" aria-label="${evolution(state, i)} evolution points per round with the current colony" title="Projected evolution points per round with the current amoebas and genes. Occupied score spaces are skipped in addition."><b>+${evolution(state, i)}</b><span class="income-unit"> / round</span></span>`}</span></span></button>`,
|
||||
`<button class="player ${i === actor ? "active" : ""}" data-player="${i}" data-bgs-player="${i}" style="--player:${colors[p.color].shade}"><span class="player-color"></span><span class="player-portrait">${amoeba(p.color, i, colonyTraits(p.genes))}</span><span class="player-info"><span class="player-name">${esc(p.name)}${i === seat && p.name !== "You" ? '<span class="you-tag">You</span>' : ""}</span><span class="player-stat"><span class="resource-amount player-population" role="img" aria-label="${colony(state, i).length} living amoebas" title="Living amoebas">${amoeba(p.color)}<span>${colony(state, i).length}</span></span><span aria-hidden="true">·</span><span class="resource-amount" role="img" aria-label="${geneCount(state, i)} genes" title="Genes">${icon("gene")}${geneCount(state, i)}</span></span></span><span class="player-balances"><span class="player-bp">${bp(p.bp)}</span><span class="player-sensitivity ${mutation(state, i) < 0 ? "protective" : ""}" role="img" aria-label="Total sensitivity ${mutation(state, i)}" title="${SENSITIVITY_HELP}">${icon("sun")}<b>${mutation(state, i)}</b></span><span class="player-score-group"><span class="player-score" title="Evolution points">${icon("spark")}${p.score}</span>${state.closed ? "" : `<span class="player-income" role="img" aria-label="${evolution(state, i)} evolution points per round with the current colony" title="Projected evolution points per round with the current amoebas and genes. Occupied score spaces are skipped in addition."><b>+${evolution(state, i)}</b><span class="income-unit"> / round</span></span>`}</span></span></button>`,
|
||||
)
|
||||
.join("");
|
||||
const positions = actions().filter((m) =>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue