게임 화면 공통 틀: 1600px 상한 없애고 창 폭 전체 사용, 판 크기 변수(--play-w/--play-h), 화면 채움 측정 스크립트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-17 15:01:46 +09:00
parent 0335a09eef
commit adc3b5337a
5 changed files with 176 additions and 7 deletions

View File

@@ -0,0 +1,27 @@
import { useLayoutEffect, type RefObject } from 'react';
/**
* Keeps `--play-w` / `--play-h` (px) on the game column (.game-main) so every game can size its table to the space
* the room actually leaves it: PC uses the measured width and height; under 1100px the page scrolls, so only the
* width is measured and the height keeps the CSS default (the visible window under the room bar, global.css).
*/
export function usePlayArea(ref: RefObject<HTMLElement | null>) {
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
const wide = matchMedia('(min-width: 1100px)');
const update = () => {
el.style.setProperty('--play-w', `${el.clientWidth}px`);
if (wide.matches) el.style.setProperty('--play-h', `${el.clientHeight}px`);
else el.style.removeProperty('--play-h');
};
update();
const ro = new ResizeObserver(update);
ro.observe(el);
wide.addEventListener('change', update);
return () => {
ro.disconnect();
wide.removeEventListener('change', update);
};
}, [ref]);
}

View File

@@ -12,6 +12,7 @@ import { useSession } from '../store/session';
import { loadGameUI } from '../games/registry';
import type { GameUI } from '../games/types';
import { useWide } from '../lib/media';
import { usePlayArea } from '../lib/play-area';
import { fxMs, useMotionScope } from '../lib/motion';
const STEP_MS = 1000;
@@ -109,6 +110,8 @@ function Player({ data, ui, onBack }: { data: ReplayData; ui: GameUI; onBack: ()
const at = useRef(0);
const layout = useRef<HTMLDivElement>(null);
useMotionScope(layout);
const playArea = useRef<HTMLDivElement>(null);
usePlayArea(playArea);
const go = (n: number, keepPlaying = false) => {
const t = Math.max(0, Math.min(last, n));
@@ -240,7 +243,7 @@ function Player({ data, ui, onBack }: { data: ReplayData; ui: GameUI; onBack: ()
</div>
</nav>
<div className={`game-layout${wide ? '' : ' replay-narrow'}`} ref={layout}>
<div className="game-main">
<div className="game-main" ref={playArea}>
{!wide && status}
<div {...readOnly}>
<ui.Board key={mount} {...props} />

View File

@@ -18,6 +18,7 @@ import { ChatPanel, EmoteBubbles, useChatSeen } from '../components/ChatPanel';
import { BotActivity } from '../components/BotActivity';
import { VolumeControl } from '../components/VolumeControl';
import { useWide } from '../lib/media';
import { usePlayArea } from '../lib/play-area';
import { GameHelp } from '../components/GameHelp';
import { PlayerName } from '../components/PlayerCard';
import { useMotionScope } from '../lib/motion';
@@ -664,6 +665,8 @@ function GameView({ room, ui, me, players, pending, slow }: { room: RoomView; ui
const wide = useWide();
const layout = useRef<HTMLDivElement>(null);
useMotionScope(layout);
const playArea = useRef<HTMLDivElement>(null);
usePlayArea(playArea);
const myTurn = ui.isMyTurn(game.view, me.id);
const isPlayer = room.seats.some((s) => s?.user.id === me.id) && game.active !== undefined;
const props = {
@@ -717,7 +720,7 @@ function GameView({ room, ui, me, players, pending, slow }: { room: RoomView; ui
);
return (
<div className="game-layout" ref={layout}>
<div className="game-main">
<div className="game-main" ref={playArea}>
{!wide && statusRow}
<ui.Board {...props} />
</div>

View File

@@ -835,7 +835,6 @@ button.header-user {
border-bottom: 1px solid var(--border);
}
.room-bar-inner {
max-width: 1600px;
height: 100%;
margin: 0 auto;
padding: 0 24px;
@@ -862,11 +861,10 @@ button.header-user {
}
}
/* Game screen: board + right panel, fits the viewport height on PC */
/* Game screen: board + right panel, fits the viewport height on PC and uses the whole window width
(no max width: the board column takes everything the side panel leaves). */
.game-layout {
max-width: 1600px;
margin: 0 auto;
padding: 16px 24px;
padding: 16px 20px;
display: grid;
grid-template-columns: minmax(0, 1fr) 380px;
gap: 20px;
@@ -876,6 +874,10 @@ button.header-user {
.game-main {
min-width: 0;
min-height: 0;
/* Play area size for games to fit their table to (px; kept up to date by usePlayArea in lib/play-area.ts).
Under 1100px the page scrolls, so the height is the visible window under the room bar. */
--play-w: calc(100vw - 24px);
--play-h: calc(100dvh - var(--site-h) - 52px - 24px);
display: flex;
flex-direction: column;
align-items: center;

134
e2e/layout-survey.ts Normal file
View File

@@ -0,0 +1,134 @@
/**
* Layout survey: opens every game as a practice room against computers on a wide PC screen and measures how much
* of the play area (.game-main) the game actually covers. Screenshots go to test-results/layout-<game>-<w>.png.
* Run: bun e2e/layout-survey.ts [gameId...] (needs apps/web/dist built)
* Games without computer players are opened as a friend room with extra human players (SURVEY_BOTS players in all).
* Env: SURVEY_SIZES="1920x1080,1440x900" SURVEY_BOTS=3 SURVEY_WAIT=3500 STATIC_DIR=<built web dist>
*/
import { chromium, type Page } from 'playwright-core';
import { mkdirSync, mkdtempSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
import { loadConfig } from '../apps/server/src/config';
import { startServer } from '../apps/server/src/server';
const PORT = Number(process.env.E2E_PORT ?? 4561);
const ORIGIN = `http://localhost:${PORT}`;
const SHOTS = process.env.E2E_SHOTS ?? join(import.meta.dir, '../test-results');
mkdirSync(SHOTS, { recursive: true });
const SIZES = (process.env.SURVEY_SIZES ?? '1920x1080').split(',').map((s) => s.split('x').map(Number) as [number, number]);
const BOTS = Number(process.env.SURVEY_BOTS ?? 3);
const all = readdirSync(join(import.meta.dir, '../apps/web/src/games'), { withFileTypes: true })
.filter((d) => d.isDirectory())
.map((d) => d.name);
const games = process.argv.slice(2).length ? process.argv.slice(2) : all;
const dbDir = mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'bg-survey-'));
const app = startServer({
config: loadConfig({ PORT: String(PORT), DB_PATH: join(dbDir, 'app.db'), PUBLIC_ORIGIN: ORIGIN, LOADTEST_NO_HTTP_LIMITS: '1' }),
log: () => {},
staticDir: process.env.STATIC_DIR ?? join(import.meta.dir, '../apps/web/dist'),
});
const browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true });
/** Union box of everything visible inside .game-main, plus the .game-main box itself. */
async function measure(p: Page) {
return p.evaluate(() => {
const main = document.querySelector('.game-main') as HTMLElement | null;
if (!main) return null;
const m = main.getBoundingClientRect();
let l = Infinity, t = Infinity, r = -Infinity, b = -Infinity;
for (const el of main.querySelectorAll('*')) {
const box = el.getBoundingClientRect();
if (box.width < 2 || box.height < 2) continue;
const cs = getComputedStyle(el);
if (cs.visibility === 'hidden' || cs.display === 'none') continue;
// Ignore transparent wrappers: only count boxes that paint something (background, border, text, media).
const paints =
(cs.backgroundColor !== 'rgba(0, 0, 0, 0)' && cs.backgroundColor !== 'transparent') ||
cs.backgroundImage !== 'none' ||
parseFloat(cs.borderTopWidth) > 0 ||
cs.boxShadow !== 'none' ||
['svg', 'canvas', 'img', 'button', 'input'].includes(el.tagName.toLowerCase()) ||
[...el.childNodes].some((n) => n.nodeType === 3 && n.textContent!.trim());
if (!paints) continue;
l = Math.min(l, Math.max(box.left, m.left));
t = Math.min(t, Math.max(box.top, m.top));
r = Math.max(r, Math.min(box.right, m.right));
b = Math.max(b, Math.min(box.bottom, m.bottom));
}
const side = document.querySelector('.game-side')?.getBoundingClientRect();
return {
main: [Math.round(m.width), Math.round(m.height)],
used: [Math.round(r - l), Math.round(b - t)],
left: Math.round(l - m.left),
right: Math.round(m.right - r),
bottom: Math.round(m.bottom - b),
side: side ? Math.round(side.width) : 0,
scroll: main.scrollHeight > main.clientHeight + 2 || document.documentElement.scrollHeight > innerHeight + 2,
};
});
}
let n = 0;
for (const g of games) {
for (const [w, h] of SIZES) {
const ctx = await browser.newContext({ viewport: { width: w, height: h }, locale: 'ko-KR' });
await ctx.addInitScript((ids) => {
for (const id of ids) localStorage.setItem(`bg:qs:${id}`, '1');
}, all);
const p = await ctx.newPage();
const extra: Awaited<ReturnType<typeof browser.newContext>>[] = [];
try {
await p.goto(`${ORIGIN}/g/${g}`);
const practice = p.getByRole('button', { name: '🤖 컴퓨터와 연습하기' });
await p.getByRole('button', { name: /친구랑 하기/ }).waitFor({ timeout: 5000 });
const bots = (await practice.count()) > 0;
await (bots ? practice : p.getByRole('button', { name: /친구랑 하기/ })).click();
await p.getByLabel('내 이름(닉네임)').fill(`측정${n++}`);
await p.getByRole('button', { name: '이 이름으로 시작하기' }).click();
await p.waitForURL(/\/r\/\d{6}$/);
if (bots) {
const add = p.getByLabel('자리').getByRole('button', { name: '🤖 컴퓨터 넣기' });
for (let i = 1; i < BOTS; i++) {
if (!(await add.count()) || !(await add.isEnabled().catch(() => false))) break;
await add.click();
await p.getByLabel('자리').getByText(`컴퓨터 ${i + 1}`).waitFor({ timeout: 3000 });
}
} else {
const code = p.url().slice(-6);
for (let i = 1; i < BOTS; i++) {
const c = await browser.newContext({ viewport: { width: 1280, height: 800 }, locale: 'ko-KR' });
extra.push(c);
const q = await c.newPage();
await q.goto(`${ORIGIN}/r/${code}`);
const nick = `친구${n++}`;
await q.getByLabel('내 이름(닉네임)').fill(nick);
await q.getByRole('button', { name: '이 이름으로 입장하기' }).click();
const joined = await p.getByLabel('자리').getByText(nick, { exact: true }).waitFor({ timeout: 4000 }).then(() => true, () => false);
if (!joined) break; // room full
}
}
await p.getByRole('button', { name: '▶ 게임 시작' }).click();
const confirm = p.getByRole('button', { name: '시작하기' });
if (await confirm.waitFor({ timeout: 1500 }).then(() => true, () => false)) await confirm.click();
await p.locator('.game-main').waitFor({ timeout: 8000 });
await p.waitForTimeout(Number(process.env.SURVEY_WAIT ?? 3500));
const r = await measure(p);
await p.screenshot({ path: join(SHOTS, `layout-${g}-${w}.png`) });
if (!r) throw new Error('no .game-main');
const fw = r.used[0] / r.main[0];
const fh = r.used[1] / r.main[1];
console.log(
`${g.padEnd(20)} ${w}x${h} main ${r.main.join('x')} used ${r.used.join('x')} (${Math.round(fw * 100)}% x ${Math.round(fh * 100)}%) gap L${r.left} R${r.right} B${r.bottom} side ${r.side}${r.scroll ? ' SCROLL' : ''}`,
);
} catch (e) {
console.log(`${g.padEnd(20)} ${w}x${h} ERROR ${(e as Error).message.split('\n')[0]}`);
await p.screenshot({ path: join(SHOTS, `layout-${g}-${w}-error.png`) }).catch(() => {});
}
await ctx.close();
for (const c of extra) await c.close();
}
}
await browser.close();
app.stop?.();
process.exit(0);