diff --git a/README.md b/README.md index 0a76769..51bdf14 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ bun e2e/bots.e2e.ts # 컴퓨터 상대, 방 나가기, 게스트 bun e2e/replay.e2e.ts # 다시 보기 bun e2e/tutorial.e2e.ts # 처음 하는 사람용 규칙 요약 bun e2e/speed.e2e.ts # 게임 속도 배율: 판 애니메이션 재생 속도와 컴퓨터 응답 시간 +bun e2e/settings.e2e.ts # 설정 팝업: 게임 중에 열어도 방에서 나가지 않음, 바로 적용, 닫기·포커스 bun scripts/loadtest.ts --help # 부하·장애 주입 (docs/reports 참고) ``` diff --git a/apps/web/src/components/SettingsPopup.tsx b/apps/web/src/components/SettingsPopup.tsx new file mode 100644 index 0000000..3dab99d --- /dev/null +++ b/apps/web/src/components/SettingsPopup.tsx @@ -0,0 +1,67 @@ +/** 화면 설정 (font size, colours, sound, vibration, tap-to-place), shared by the 설정 page and the 설정 popup. */ +import { Link } from 'react-router'; +import { useSession } from '../store/session'; +import { Sheet } from './ui'; + +function Seg({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) { + return ( +
+ {label} +
+ {options.map(([k, l]) => ( + + ))} +
+
+ ); +} + +/** The setting rows only; the caller adds the heading and the box. Changes apply and save at once. */ +export function DisplaySettings() { + const settings = useSession((s) => s.settings); + const updateSettings = useSession((s) => s.updateSettings); + return ( + <> + updateSettings({ fontScale })} /> + updateSettings({ theme })} /> + updateSettings({ sound: v === 'on' })} /> + + updateSettings({ vibrate: v === 'on' })} /> + updateSettings({ tapConfirm: v === 'on' })} + /> + + ); +} + +/** + * 설정 팝업: opens over the current page so a room stays open underneath (no navigation, no leave). + * `account` adds a link to the full 설정 page (nickname, records, logout); rooms leave it out because following it leaves the room. + * Pass a stable `onClose`: Sheet re-focuses itself whenever it changes. + */ +export function SettingsPopup({ onClose, account }: { onClose: () => void; account?: boolean }) { + return ( + +

화면 설정

+ + {account && ( + + 👤 내 계정 · 기록 보기 + + )} + +
+ ); +} diff --git a/apps/web/src/components/SiteHeader.tsx b/apps/web/src/components/SiteHeader.tsx index 4fdf957..47247c5 100644 --- a/apps/web/src/components/SiteHeader.tsx +++ b/apps/web/src/components/SiteHeader.tsx @@ -1,10 +1,11 @@ /** PC top menu (docs/07-ui-ux.md §3.2): 로고·메뉴, 오른쪽에 소리 크기·테마 버튼과 로그인/계정 메뉴. */ -import { useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from 'react'; import { Link, NavLink, useNavigate } from 'react-router'; import { api } from '../net/api'; import { useSession } from '../store/session'; import { Avatar, ConfirmSheet } from './ui'; import { VolumeControl } from './VolumeControl'; +import { SettingsPopup } from './SettingsPopup'; export function SiteHeader() { const { me, siteName, role } = useSession(); @@ -60,14 +61,17 @@ function ThemeToggle() { ); } -/** 로그인한 뒤: 닉네임(디스코드 연결 시 디스코드 이름) → 누르면 [설정] ([관리자 메뉴]) [로그아웃] 메뉴. */ +/** 로그인한 뒤: 닉네임(디스코드 연결 시 디스코드 이름) → 누르면 [설정](팝업) ([관리자 메뉴]) [로그아웃] 메뉴. */ function AccountMenu() { const me = useSession((s) => s.me)!; const role = useSession((s) => s.role); const nav = useNavigate(); const [open, setOpen] = useState(false); const [confirm, setConfirm] = useState(false); + const [settings, setSettings] = useState(false); + const closeSettings = useCallback(() => setSettings(false), []); const ref = useRef(null); + const btn = useRef(null); useEffect(() => { if (!open) return; @@ -83,7 +87,7 @@ function AccountMenu() { return (
- {open && (
- {role !== 'user' && ( @@ -105,6 +110,7 @@ function AccountMenu() {
)} + {settings && } {confirm && ( ({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) { - return ( -
- {label} -
- {options.map(([k, l]) => ( - - ))} -
-
- ); -} - export default function MePage() { const nav = useNavigate(); - const { me, settings, discordEnabled, useAvatar, hasDiscordAvatar, updateSettings, role } = useSession(); + const { me, discordEnabled, useAvatar, hasDiscordAvatar, role } = useSession(); const [editing, setEditing] = useState(false); const [nick, setNick] = useState(me?.nickname ?? ''); const [error, setError] = useState(null); @@ -52,28 +38,6 @@ export default function MePage() { } }; - const display = ( -
-

화면 설정

- updateSettings({ fontScale })} /> - updateSettings({ theme })} /> - updateSettings({ sound: v === 'on' })} /> - - updateSettings({ vibrate: v === 'on' })} /> - updateSettings({ tapConfirm: v === 'on' })} - /> -
- ); - // 로그인 안 했으면 로그인 페이지로 (로그인 페이지에는 로그인만 있어요). if (!me) return ; @@ -149,7 +113,10 @@ export default function MePage() {
- {display} +
+

화면 설정

+ +

내 기록

diff --git a/apps/web/src/pages/RoomPage.tsx b/apps/web/src/pages/RoomPage.tsx index 07f75bc..b38af28 100644 --- a/apps/web/src/pages/RoomPage.tsx +++ b/apps/web/src/pages/RoomPage.tsx @@ -1,11 +1,12 @@ /** 방: 대기실 ↔ 게임 ↔ 결과를 한 주소에서 전환 (docs/06 §5–§9). */ -import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react'; +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import { Link, useNavigate, useParams } from 'react-router'; import { BOT_BANDS, BOT_PICKS, BOT_PICK_LABEL, bandOf, botChatRequired, botsAllowed, formatRoomCode, isBotId, luckLabel, type PublicUser, type RoomView } from '@bg/shared/lite'; import { Avatar, CodeLabel, ConfirmSheet, CopyButton, ShareButton, Sheet, TopBar } from '../components/ui'; import { GuestWarning, NicknameForm } from '../components/NicknameForm'; import { GameNotice, gameName } from '../components/GameNotice'; import { QrModal } from '../components/QrModal'; +import { SettingsPopup } from '../components/SettingsPopup'; import { api, type RoomPreview } from '../net/api'; import { socket, useRoom } from '../net/socket'; import { useSession } from '../store/session'; @@ -94,6 +95,9 @@ function Room({ code, me }: { code: string; me: PublicUser }) { const [ui, setUi] = useState(null); const [leaveAsk, setLeaveAsk] = useState(false); const [chatOpen, setChatOpen] = useState(false); + // 설정 opens as a popup over the room: going to /me would unmount the room and detach from it. + const [settingsOpen, setSettingsOpen] = useState(false); + const closeSettings = useCallback(() => setSettingsOpen(false), []); // [한 판 더] takes me back to this room's lobby after game N (kept per tab so a reload stays there). const lobbyKey = `bg:lobby:${code}`; const [lobbyAfter, setLobbyAfter] = useState(() => Number(sessionStorage.getItem(lobbyKey)) || null); @@ -217,7 +221,7 @@ function Room({ code, me }: { code: string; me: PublicUser }) { 📖 규칙 - @@ -242,6 +246,7 @@ function Room({ code, me }: { code: string; me: PublicUser }) { )} + {settingsOpen && } {leaveAsk && ( {}, + staticDir: join(import.meta.dir, '../apps/web/dist'), +}); + +const browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true }); +let failed = false; +const step = async (name: string, fn: () => Promise) => { + const t0 = performance.now(); + try { + await fn(); + console.log(`✓ ${name} (${Math.round(performance.now() - t0)}ms)`); + } catch (e) { + failed = true; + console.log(`✗ ${name}: ${(e as Error).message.split('\n')[0]}`); + throw e; + } +}; + +/** Every socket message the page sends, as text. */ +function recordSent(p: Page): string[] { + const sent: string[] = []; + p.on('websocket', (ws) => ws.on('framesent', (f) => sent.push(String(f.payload)))); + return sent; +} +const leftRoom = (sent: string[]) => sent.filter((m) => /"t":"(leave|detach)"/.test(m)); +const focusedLabel = (p: Page) => p.evaluate(() => document.activeElement?.getAttribute('aria-label') ?? document.activeElement?.tagName ?? ''); + +/** 오목 against the computer, game started; returns the room address. */ +async function practiceGame(p: Page, name: string): Promise { + await p.goto(`${ORIGIN}/g/omok`); + await p.getByRole('button', { name: '🤖 컴퓨터와 연습하기' }).click(); + await p.getByLabel('내 이름(닉네임)').fill(name); + await p.getByRole('button', { name: '이 이름으로 시작하기' }).click(); + await p.waitForURL(/\/r\/\d{6}$/); + await p.getByRole('button', { name: '▶ 게임 시작' }).click(); + await p.locator('svg[role="grid"]').waitFor(); + return p.url(); +} + +try { + const phone = await browser.newContext({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true, locale: 'ko-KR' }); + await phone.addInitScript(() => localStorage.setItem('bg:qs:omok', '1')); + const a = await phone.newPage(); + const errors: string[] = []; + a.on('pageerror', (e) => errors.push(e.message)); + const sent = recordSent(a); + + let roomUrl = ''; + await step('휴대폰: 컴퓨터와 오목을 시작', async () => { + roomUrl = await practiceGame(a, '설정맨'); + }); + + const opener = () => a.locator('.room-bar').getByRole('button', { name: '글자 크기 · 소리 설정' }); + const dialog = () => a.getByRole('dialog', { name: '설정' }); + + await step('게임 중 ⚙️ 설정 → 팝업, 주소 그대로, 나가기·떠나기 신호 없음, 바꾸면 바로 적용', async () => { + await opener().click(); + await dialog().waitFor(); + if (a.url() !== roomUrl) throw new Error(`navigated to ${a.url()}`); + if ((await dialog().getAttribute('aria-modal')) !== 'true') throw new Error('dialog is not aria-modal'); + if (!(await dialog().evaluate((el) => el.contains(document.activeElement)))) throw new Error('focus did not move into the popup'); + // The board is still mounted underneath (the room did not unmount). + if (!(await a.locator('svg[role="grid"]').count())) throw new Error('board went away'); + // No account link inside a room: following it would leave. + if (await dialog().getByRole('link', { name: /내 계정/ }).count()) throw new Error('account link shown inside a room'); + await dialog().getByRole('group', { name: '글자 크기' }).getByRole('button', { name: '크게', exact: true }).click(); + if ((await a.evaluate(() => document.documentElement.dataset.fontScale)) !== 'large') throw new Error('font size not applied at once'); + await a.screenshot({ path: join(SHOTS, 'settings-popup-phone.png') }); + }); + + await step('Escape로 닫으면 ⚙️로 초점이 돌아오고 판이 그대로', async () => { + await a.keyboard.press('Escape'); + await dialog().waitFor({ state: 'detached' }); + if ((await focusedLabel(a)) !== '글자 크기 · 소리 설정') throw new Error(`focus went to ${await focusedLabel(a)}`); + await a.locator('svg[role="grid"]').waitFor(); + }); + + await step('바깥(어두운 곳)을 누르거나 [닫기]를 눌러도 닫혀요', async () => { + await opener().click(); + await dialog().waitFor(); + await a.mouse.click(195, 30); // the backdrop above the bottom sheet + await dialog().waitFor({ state: 'detached' }); + await opener().click(); + await dialog().getByRole('button', { name: '닫기' }).click(); + await dialog().waitFor({ state: 'detached' }); + if (a.url() !== roomUrl) throw new Error(`navigated to ${a.url()}`); + }); + + await step('방에 그대로 있어요: 신호 없음, 다시 불러와도 같은 크기 글자', async () => { + const bad = leftRoom(sent); + if (bad.length) throw new Error(`sent ${bad.join(', ')}`); + if (!sent.some((m) => /"t":"join"/.test(m))) throw new Error('socket frames were not recorded'); + await a.locator('.turn-status').waitFor(); + await a.reload(); + await a.locator('svg[role="grid"]').waitFor(); + if ((await a.evaluate(() => document.documentElement.dataset.fontScale)) !== 'large') throw new Error('font size not saved'); + }); + + await step('PC 헤더 계정 메뉴 → ⚙️ 설정도 팝업, 계정 링크로 설정 페이지', async () => { + const pc = await browser.newContext({ viewport: { width: 1280, height: 800 }, locale: 'ko-KR' }); + await pc.addInitScript(() => localStorage.setItem('bg:qs:omok', '1')); + const b = await pc.newPage(); + b.on('pageerror', (e) => errors.push(e.message)); + await practiceGame(b, '헤더맨'); + await b.goto(`${ORIGIN}/games`); + await b.getByRole('button', { name: /^내 계정/ }).click(); + await b.getByRole('menuitem', { name: '⚙️ 설정' }).click(); + const d = b.getByRole('dialog', { name: '설정' }); + await d.waitFor(); + if (!b.url().endsWith('/games')) throw new Error(`navigated to ${b.url()}`); + await d.getByRole('group', { name: '화면 색' }).getByRole('button', { name: '어둡게' }).click(); + if ((await b.evaluate(() => document.documentElement.dataset.theme)) !== 'dark') throw new Error('theme not applied at once'); + await b.waitForTimeout(400); // let the colour transition finish for the screenshot + await b.screenshot({ path: join(SHOTS, 'settings-popup-pc.png') }); + await b.keyboard.press('Escape'); + await d.waitFor({ state: 'detached' }); + if (!/^내 계정/.test(await focusedLabel(b))) throw new Error(`focus went to ${await focusedLabel(b)}`); + await b.getByRole('button', { name: /^내 계정/ }).click(); + await b.getByRole('menuitem', { name: '⚙️ 설정' }).click(); + await d.getByRole('link', { name: /내 계정 · 기록 보기/ }).click(); + await b.waitForURL(`${ORIGIN}/me`); + await d.waitFor({ state: 'detached' }); + // The page keeps the same settings (still dark after the popup changed it). + await b.getByRole('heading', { name: '화면 설정' }).waitFor(); + if ((await b.getByRole('group', { name: '화면 색' }).getByRole('button', { name: '어둡게' }).getAttribute('aria-pressed')) !== 'true') throw new Error('page does not show the popup change'); + await pc.close(); + }); + + if (errors.length) throw new Error(`page errors: ${errors.join(' | ')}`); +} catch (e) { + failed = true; + console.error(e); +} finally { + await browser.close(); + await app.stop(); +} +console.log(failed ? 'E2E FAILED' : 'E2E PASSED'); +process.exit(failed ? 1 : 0);