diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1a4f3df..9ed5bfb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -86,8 +86,8 @@ importers: viewer: dependencies: '@boardgamers/protocol': - specifier: 0.5.0 - version: 0.5.0 + specifier: 0.6.0 + version: 0.6.0 container-engine: specifier: workspace:../engine version: link:../engine @@ -1042,10 +1042,10 @@ packages: } engines: { node: '>=6.9.0' } - '@boardgamers/protocol@0.5.0': + '@boardgamers/protocol@0.6.0': resolution: { - integrity: sha512-9SjU0cSktwxeMLItCW5VmUeSFl3Kg965JkKFf+BKZBxR2a2dyFoMKE3RYN2+ZwrI6GNS1mA6Fki9HOHQnD2WRw==, + integrity: sha512-byHV2eOOFpnQCnhLaM0LPUpT30ew1aAOuTIYxwztkVjg4NgeTyPwjU8Efmc/xi+DGCrfIjo2LTb7YlNUhmzy0g==, } '@cspotcode/source-map-support@0.8.1': @@ -11586,7 +11586,7 @@ snapshots: '@babel/helper-string-parser': 7.29.7 '@babel/helper-validator-identifier': 7.29.7 - '@boardgamers/protocol@0.5.0': + '@boardgamers/protocol@0.6.0': dependencies: zod: 4.6.2 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index bd9986e..d40822b 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -18,8 +18,7 @@ allowBuilds: autoInstallPeers: false minimumReleaseAgeExclude: - - '@boardgamers/protocol@0.4.0 || 0.4.2 || 0.5.0' - - '@boardgamers/protocol@0.2.2 || 0.3.0 || 0.3.1 || 0.3.3' + - '@boardgamers/protocol@0.2.2 || 0.3.0 || 0.3.1 || 0.3.3 || 0.4.0 || 0.4.2 || 0.5.0 || 0.6.0' # The cli-plugin-typescript fork-ts-checker shim does a bare # require('@vue/compiler-sfc') expecting the vue-3 parse shape ({descriptor}). diff --git a/viewer/package.json b/viewer/package.json index ff24f02..da1c555 100644 --- a/viewer/package.json +++ b/viewer/package.json @@ -1,6 +1,6 @@ { "name": "container-viewer", - "version": "2.0.6", + "version": "2.0.7", "repository": { "type": "git", "url": "git+https://github.com/boardgamers/container.git", @@ -19,7 +19,7 @@ "preview:tutorial": "node scripts/tutorial-preview.mjs" }, "dependencies": { - "@boardgamers/protocol": "0.5.0", + "@boardgamers/protocol": "0.6.0", "container-engine": "workspace:../engine", "core-js": "^3.6.5", "lodash": "^4.17.19", diff --git a/viewer/scripts/host-presentation-smoke.mjs b/viewer/scripts/host-presentation-smoke.mjs new file mode 100644 index 0000000..9cb8acf --- /dev/null +++ b/viewer/scripts/host-presentation-smoke.mjs @@ -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); +} diff --git a/viewer/scripts/protocol-smoke.mjs b/viewer/scripts/protocol-smoke.mjs index 535ee78..56446f8 100644 --- a/viewer/scripts/protocol-smoke.mjs +++ b/viewer/scripts/protocol-smoke.mjs @@ -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'; @@ -326,12 +327,14 @@ try { await assertJournalAtEnd(); await page.reload(); await page.evaluate((state) => { - const host = window.container.launch('#app'); + window.host = window.container.launch('#app'); host.emit('preferences', { sound: false }); host.emit('state', state); }, state); await assertJournalAtEnd(); assert.deepEqual(errors, [], 'no browser errors'); + await checkHostPresentation(page, 'host', `/tmp/container-board-thumbnail-${width}.png`); + assert.deepEqual(errors, []); await page.close(); console.log(`${game} ${width}px: protocol/chat smoke passed`); } diff --git a/viewer/src/components/Game.vue b/viewer/src/components/Game.vue index 89ea3f4..0fca1e3 100644 --- a/viewer/src/components/Game.vue +++ b/viewer/src/components/Game.vue @@ -32,7 +32,7 @@ @click="viewPlayerBoard(i)" > {{ i === player ? 'You' : p.name }} + >{{ i === player ? 'You' : p.name }}
@@ -74,15 +74,27 @@ - - - + + + - {{ - getPlayerName() - }} + {{ getPlayerName() }} diff --git a/viewer/src/host-presentation.ts b/viewer/src/host-presentation.ts new file mode 100644 index 0000000..569eeac --- /dev/null +++ b/viewer/src/host-presentation.ts @@ -0,0 +1,119 @@ +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; + content.setAttribute('viewBox', `${box.x} ${box.y} ${box.width} ${box.height}`); + 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((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))); + return preview; + } + return { render, destroy }; +} diff --git a/viewer/src/launch.ts b/viewer/src/launch.ts index 72d7209..47864c0 100644 --- a/viewer/src/launch.ts +++ b/viewer/src/launch.ts @@ -4,6 +4,7 @@ import { EventEmitter } from 'events'; import Vue from 'vue'; import Game from './components/Game.vue'; import { mountGameChat } from './game-chat'; +import { createBoardThumbnail, installPlayerCards } from './host-presentation'; import { installActionSounds } from './sounds'; import type { Preferences } from './types/ui-data'; @@ -43,7 +44,12 @@ function launch(selector: string) { render: (h) => h(Game, { props: params }, []), }).$mount(mountPoint); + const thumbnail = createBoardThumbnail(app.$el); const viewer = createViewer({ + async onThumbnail(size) { + await app.$nextTick(); + return thumbnail.render(app.$el.querySelector('#scene'), size, '#c6deda', '[data-thumbnail-omit]'); + }, async onState(data) { params.state = data; app.$forceUpdate(); @@ -75,8 +81,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();