게임 속도 배율: 1배도 애니메이션·연출·컴퓨터 생각 시간을 예전의 1.5배로 늦추고, 관리자 사이트 설정 "게임 속도 배율"(1/16~16배, 기본 1)로 나눠 조절. 저장하면 열린 방에도 바로 적용(RoomView.gameSpeed 재전송)

- 서버: SiteSettings.gameSpeed, /api/config에 노출, 컴퓨터 생각 시간(defaultBotDelay)과 마피아·라이어 컴퓨터가 살펴보는 간격에 BOT_SLOWDOWN(1.5)/배율. 게임이 정한 반응 시각(원카드 외치기)은 그대로
- 웹: lib/motion.ts — .game-layout 안 CSS 애니메이션·트랜지션은 useMotionScope가 playbackRate로, Web Animations는 fxAnim, 연출 타이머(배너 유지·다음 단계·복사본 정리·숫자 세기·다시 보기 한 칸)는 fxMs. 채팅·role="timer"·규칙 시간·꾹 눌러 보기는 제외
- 관리자 사이트 탭에 배율 버튼(1/16~16)과 직접 입력
- 테스트: 배율 검증(API 400/200, 열린 방 즉시 반영), 컴퓨터 생각 시간 배율, motion 단위 테스트, e2e/speed.e2e.ts(돌 애니메이션 재생 배율·컴퓨터 응답 시간), 관리자 e2e에 배율 저장
- 문서: 14-admin §5, 07-ui-ux, 06-lobby-rooms, 13-decisions, README

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-14 01:24:25 +09:00
parent 5e8f5b821f
commit 18ef402a6a
54 changed files with 536 additions and 134 deletions

View File

@@ -9,6 +9,7 @@ import { socket } from '../../net/socket';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxMs } from '../../lib/motion';
/** Canonical board: 10 rows × 17 columns (phones show it turned: 17 rows × 10 columns). */
const ROWS = 10;
@@ -231,7 +232,7 @@ function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
}, [v.cells]);
useEffect(() => {
if (!intro) return;
const t = setTimeout(() => setIntro(false), 900);
const t = setTimeout(() => setIntro(false), fxMs(900));
return () => clearTimeout(t);
}, [intro]);
useEffect(() => {
@@ -259,12 +260,12 @@ function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
}, [canPlay]);
useEffect(() => {
if (!pops.length) return;
const t = setTimeout(() => setPops((p) => p.slice(1)), 450);
const t = setTimeout(() => setPops((p) => p.slice(1)), fxMs(450));
return () => clearTimeout(t);
}, [pops]);
useEffect(() => {
if (!flash) return;
const t = setTimeout(() => setFlash(null), 900);
const t = setTimeout(() => setFlash(null), fxMs(900));
return () => clearTimeout(t);
}, [flash]);

View File

@@ -10,6 +10,7 @@ import { reducedMotion, useBanner } from '../card-fx';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxMs } from '../../lib/motion';
type Color = 'black' | 'white';
const COLOR_KO: Record<Color, string> = { black: '흑', white: '백' };
@@ -78,8 +79,9 @@ function CountUp({ to, live }: { to: number; live: boolean }) {
if (!animate) return setShown(null);
let raf = 0;
const t0 = performance.now();
const len = fxMs(1000);
const step = (t: number) => {
const k = Math.min(1, (t - t0) / 1000);
const k = Math.min(1, (t - t0) / len);
setShown(k < 1 ? Math.floor(to * (1 - (1 - k) ** 3)) : null);
if (k < 1) raf = requestAnimationFrame(step);
};
@@ -184,13 +186,13 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
if (diff.size === 0) return;
sfx.click();
setChanged(diff);
const t = setTimeout(() => setChanged(new Set()), 2500);
const t = setTimeout(() => setChanged(new Set()), fxMs(2500));
return () => clearTimeout(t);
}, [dead]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (!bubble) return;
const t = setTimeout(() => setBubble(null), 2500);
const t = setTimeout(() => setBubble(null), fxMs(2500));
return () => clearTimeout(t);
}, [bubble]);

View File

@@ -9,6 +9,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxAnim, fxMs } from '../../lib/motion';
// ---------------------------------------------------------------- names (display names live only here, docs §12)
@@ -243,13 +244,13 @@ const bangSfx = {
/** 판정 card / role badge turning face up (Web Animations, no layout change). */
function flip(el: Element | null | undefined, delay = 0): void {
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
(el as HTMLElement).animate([{ transform: 'perspective(500px) rotateX(90deg)', opacity: 0.3 }, { transform: 'perspective(500px) rotateX(0deg)', opacity: 1 }], {
fxAnim((el as HTMLElement).animate([{ transform: 'perspective(500px) rotateX(90deg)', opacity: 0.3 }, { transform: 'perspective(500px) rotateX(0deg)', opacity: 1 }], {
duration: 380,
delay,
easing: 'ease-out',
fill: 'backwards',
composite: 'add',
});
}));
}
const sameFace = (a: CardFace, b: CardFace) => a.kind === b.kind && a.suit === b.suit && a.rank === b.rank;
@@ -1153,7 +1154,7 @@ function useBangFx(v: BangView, me: string | null, players: Record<string, Publi
const deck = fxEl('bang-deck');
const pile = fxEl('bang-discard') ?? deck;
const piles = fxEl('bang-piles');
const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, ms) : f());
const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, fxMs(ms)) : f());
const toPile = (from: Element | DOMRect | null, f: CardFace | null, delay: number) => flyGhost(from, pile, { delay, ms: 420, ...(f ? faceGhost(f) : BACK_GHOST) });
const toMe = (from: Element | null, at: number) => (handSrc.current = { from, at });
const others = (p: string) => v.players.filter((x) => x.alive && x.id !== p).map((x) => x.id);

View File

@@ -3,12 +3,14 @@
*
* - Everything reacts to *view changes*, so the other players' moves animate and sound too, and skips the first
* render: joining, reloading or a replay jump (the replay page remounts the board) never replays old moves.
* - Web Animations only (no layout change, `composite: 'add'` keeps the element's own transform), short (≤ 0.6 s),
* and flying copies ("ghosts") never take clicks, so nothing waits for an animation.
* - Web Animations only (no layout change, `composite: 'add'` keeps the element's own transform), short (≤ 0.6 s at
* the written lengths; the game speed scales them, lib/motion), and flying copies ("ghosts") never take clicks, so
* nothing waits for an animation.
* - Respects `prefers-reduced-motion` (Web Animations are not covered by the global CSS rule, so it is checked here).
* - Sounds stay in `lib/feedback` (`sfx`, `tone`, `noise`); game-specific ones live in each game folder.
*/
import { useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { fxAnim, fxMs } from '../lib/motion';
export const reducedMotion = (): boolean => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
@@ -48,12 +50,14 @@ export function flyFrom(el: Element | null | undefined, from: Where, o: FlyOpts
const dx = p.x - q.x;
const dy = p.y - q.y;
if (Math.abs(dx) + Math.abs(dy) < 4) return;
(el as HTMLElement).animate(
[
{ transform: `translate(${dx}px, ${dy}px) scale(${o.scale ?? 0.6}) rotate(${o.rotate ?? -10}deg)`, opacity: 0.35 },
{ transform: 'translate(0px, 0px) scale(1) rotate(0deg)', opacity: 1 },
],
{ duration: o.ms ?? 380, delay: o.delay ?? 0, easing: 'cubic-bezier(.2,.8,.3,1)', fill: 'backwards', composite: 'add' },
fxAnim(
(el as HTMLElement).animate(
[
{ transform: `translate(${dx}px, ${dy}px) scale(${o.scale ?? 0.6}) rotate(${o.rotate ?? -10}deg)`, opacity: 0.35 },
{ transform: 'translate(0px, 0px) scale(1) rotate(0deg)', opacity: 1 },
],
{ duration: o.ms ?? 380, delay: o.delay ?? 0, easing: 'cubic-bezier(.2,.8,.3,1)', fill: 'backwards', composite: 'add' },
),
);
}
@@ -97,20 +101,22 @@ export function flyGhost(from: Where, to: Where, o: GhostOpts = {}): void {
g.style.top = `${p.y - h / 2}px`;
document.body.appendChild(g);
const jitter = n > 1 ? (i - (n - 1) / 2) * 6 : 0;
const anim = g.animate(
[
{ transform: 'translate(0px, 0px) scale(.85) rotate(-8deg)', opacity: 0 },
{ opacity: 1, offset: 0.15 },
{ transform: `translate(${q.x - p.x + jitter}px, ${q.y - p.y}px) scale(1) rotate(0deg)`, opacity: 1, offset: 0.85 },
{ transform: `translate(${q.x - p.x + jitter}px, ${q.y - p.y}px) scale(.9) rotate(0deg)`, opacity: 0 },
],
{ duration: o.ms ?? 480, delay: (o.delay ?? 0) + i * (o.gap ?? 70), easing: 'cubic-bezier(.3,.7,.3,1)', fill: 'both' },
const anim = fxAnim(
g.animate(
[
{ transform: 'translate(0px, 0px) scale(.85) rotate(-8deg)', opacity: 0 },
{ opacity: 1, offset: 0.15 },
{ transform: `translate(${q.x - p.x + jitter}px, ${q.y - p.y}px) scale(1) rotate(0deg)`, opacity: 1, offset: 0.85 },
{ transform: `translate(${q.x - p.x + jitter}px, ${q.y - p.y}px) scale(.9) rotate(0deg)`, opacity: 0 },
],
{ duration: o.ms ?? 480, delay: (o.delay ?? 0) + i * (o.gap ?? 70), easing: 'cubic-bezier(.3,.7,.3,1)', fill: 'both' },
),
);
const done = () => g.remove();
anim.onfinish = done;
anim.oncancel = done;
// Safety net (a background tab may never finish the animation).
setTimeout(done, (o.ms ?? 480) + (o.delay ?? 0) + i * (o.gap ?? 70) + 1500);
setTimeout(done, fxMs((o.ms ?? 480) + (o.delay ?? 0) + i * (o.gap ?? 70)) + 1500);
}
}
@@ -127,7 +133,7 @@ export function bump(el: Element | null | undefined, kind: 'pop' | 'shake' = 'po
{ transform: 'translateX(-4px) rotate(-1deg)', offset: 0.75 },
{ transform: 'translateX(0px)' },
];
(el as HTMLElement).animate(frames, { duration: kind === 'pop' ? 320 : 420, easing: 'ease-out', composite: 'add' });
fxAnim((el as HTMLElement).animate(frames, { duration: kind === 'pop' ? 320 : 420, easing: 'ease-out', composite: 'add' }));
}
// ---------------------------------------------------------------- hooks
@@ -177,7 +183,7 @@ export function useBanner(): [ReactNode, (text: string, tone?: BannerTone, sub?:
ensureCss();
if (timer.current) clearTimeout(timer.current);
setB((old) => ({ id: (old?.id ?? 0) + 1, text, tone, sub }));
timer.current = setTimeout(() => setB(null), 1700);
timer.current = setTimeout(() => setB(null), fxMs(1700));
};
useLayoutEffect(() => () => {
if (timer.current) clearTimeout(timer.current);

View File

@@ -11,6 +11,7 @@ import { socket } from '../../net/socket';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxMs } from '../../lib/motion';
// ---------------------------------------------------------------- constants (mirror packages/games/src/catchmind/types.ts)
@@ -682,7 +683,7 @@ function Overlay({ v, me, act, players, onSave }: { v: CatchmindView; me: string
sounds.ding();
haptic(60);
if (popTimer.current) clearTimeout(popTimer.current);
popTimer.current = setTimeout(() => setPop(null), 1600);
popTimer.current = setTimeout(() => setPop(null), fxMs(1600));
}
prevRole.current = v.role;
prevTurn.current = v.turnNo;
@@ -945,7 +946,7 @@ function GuessPanel({ v, me, players, act, pending }: { v: CatchmindView; me: st
if (mine) {
setClose(true);
if (closeTimer.current) clearTimeout(closeTimer.current);
closeTimer.current = setTimeout(() => setClose(false), 2200);
closeTimer.current = setTimeout(() => setClose(false), fxMs(2200));
}
}, [lastId, v.chat, me]);
useEffect(() => () => void (closeTimer.current && clearTimeout(closeTimer.current)), []);

View File

@@ -28,6 +28,7 @@ import { cssEsc, flyGhost, reducedMotion } from '../card-fx';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxAnim, fxMs } from '../../lib/motion';
export const SUSPECT_COLOR: Record<Suspect, string> = {
scarlet: '#dc2626',
@@ -213,14 +214,14 @@ function slideFrom(el: HTMLElement | null, dx: number, dy: number, delay: number
el.getAnimations().forEach((a) => a.cancel());
el.style.zIndex = '4';
const lift = Math.min(36, 10 + d * 0.15);
const anim = el.animate(
const anim = fxAnim(el.animate(
[
{ transform: `translate(${dx}px, ${dy}px)` },
{ transform: `translate(${dx / 2}px, ${dy / 2 - lift}px) scale(1.2)`, offset: 0.5 },
{ transform: 'translate(0px, 0px)' },
],
{ duration: Math.min(720, 300 + d * 0.8), delay, easing: 'ease-in-out', fill: 'backwards' },
);
));
const done = () => (el.style.zIndex = '');
anim.onfinish = done;
anim.oncancel = done;
@@ -368,12 +369,12 @@ function ClueBoard({ view: v, me, players, act, pending }: BoardProps<ClueView>)
useEffect(() => {
if (!banner) return;
const t = setTimeout(() => setBanner(null), 1700);
const t = setTimeout(() => setBanner(null), fxMs(1700));
return () => clearTimeout(t);
}, [banner]);
useEffect(() => {
if (!landed) return;
const t = setTimeout(() => setLanded(null), 800);
const t = setTimeout(() => setLanded(null), fxMs(800));
return () => clearTimeout(t);
}, [landed]);

View File

@@ -9,6 +9,7 @@ import { bump, flyGhost, seatEl, useBanner } from '../card-fx';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxMs } from '../../lib/motion';
// Kept local (type-only import above) so the screen chunk does not pull in the rules module + zod.
const KINDS: Kind[] = ['cockroach', 'bat', 'fly', 'toad', 'rat', 'scorpion', 'spider', 'stinkbug'];
@@ -786,7 +787,7 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
if (flip) {
const rv = v.lastReveal!;
sfx.cardFlip();
setTimeout(() => (rv.correct ? sfx.good() : cpSfx.wrong()), 260);
setTimeout(() => (rv.correct ? sfx.good() : cpSfx.wrong()), fxMs(260));
showBanner(rv.call === 'true' ? '진짜!' : '거짓말!', rv.correct ? 'green' : 'red', `${rv.caller === me ? '내가' : `${nick(players, rv.caller)}님이`} ${rv.correct ? '맞혔어요' : '틀렸어요'}`);
flyGhost(document.querySelector('.cp-table'), seatEl(rv.takenBy), { delay: 380, ms: 480, className: 'cp-ghost' });
setTimeout(() => {
@@ -794,7 +795,7 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
const n = v.fronts[rv.takenBy]?.counts[rv.kind] ?? 0;
if (!over && n >= v.loseCount - 1) cpSfx.danger();
else cpSfx.splat();
}, 820);
}, fxMs(820));
}
if (over && !p.over && v.final) {
const f = v.final;
@@ -802,7 +803,7 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
showBanner(`${f.loser === me ? '내가' : `${nick(players, f.loser)}님`} 패배!`, 'dark', f.losingKind ? `${KIND_KO[f.losingKind]}${hasBatchim(KIND_KO[f.losingKind]) ? '이' : '가'} 너무 많아요` : undefined);
cpSfx.danger();
bump(seatEl(f.loser), 'shake');
}, flip ? 1300 : 0);
}, flip ? fxMs(1300) : 0);
}
if (flip) {
const rv = v.lastReveal!;
@@ -822,12 +823,12 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
for (const s of v.said) if (s.seq > p.said) add[s.player] = PHRASE_KO[s.phrase];
sfx.pop();
setBubbles((b) => ({ ...b, ...add }));
setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in add)))), 3500);
setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in add)))), fxMs(3500));
}
prev.current = { claims: claimsKey, reveal: revealKey, said: lastSaid, waiting: w, peek: peekKey, over };
if (slide || flip) {
setFresh({ slide, flip });
const t = setTimeout(() => setFresh({ slide: false, flip: false }), 700);
const t = setTimeout(() => setFresh({ slide: false, flip: false }), fxMs(700));
return () => clearTimeout(t);
}
return undefined;

View File

@@ -9,6 +9,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxAnim, fxMs } from '../../lib/motion';
const JESTER = 13;
/** Same names as the rules module (kept here so the screen chunk does not pull in the rules code). */
@@ -95,7 +96,7 @@ const rememberPlay = (rank: number) => {
/** Brief dim of a seat (pass). */
function dim(el: Element | null): void {
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
(el as HTMLElement).animate([{ opacity: 1 }, { opacity: 0.4, offset: 0.35 }, { opacity: 1 }], { duration: 650, easing: 'ease-out' });
fxAnim((el as HTMLElement).animate([{ opacity: 1 }, { opacity: 0.4, offset: 0.35 }, { opacity: 1 }], { duration: 650, easing: 'ease-out' }));
}
const CSS = `
@@ -776,7 +777,7 @@ const logKey = (e: LogEntry) => `${e.seq}-${e.t}-${'p' in e ? e.p : 'from' in e
/** Sounds + motion for every change of the table, mine or anyone else's (log entries since the last view). */
function useDalmutiFx(v: DalmutiView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, ms) : f());
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, fxMs(ms)) : f());
const who = (id: string) => (id === me ? '나' : `${nick(players, id)}님`);
// A new round (or the very first deal): cards go from the middle to everyone.
const deal = (delay = 0) => {

View File

@@ -8,6 +8,7 @@ import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxMs } from '../../lib/motion';
const COLOR_KO: Record<TColor, string> = { black: '검은색', white: '흰색' };
const COLOR_SHORT: Record<TColor, string> = { black: '검정', white: '흰색' };
@@ -54,7 +55,7 @@ function useTimed<T>(): [T | null, (v: T, ms: number) => void] {
const set = useCallback((v: T, ms: number) => {
clearTimeout(timer.current);
setVal(v);
timer.current = setTimeout(() => setVal(null), ms);
timer.current = setTimeout(() => setVal(null), fxMs(ms));
}, []);
return [val, set];
}

View File

@@ -11,6 +11,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { ICON_NAMES, SymbolArt } from './art';
import { fxMs } from '../../lib/motion';
/** Taps this soon after one of the two cards changed are dropped as late (they were aimed at the previous card). */
const TAP_GRACE_MS = 250;
@@ -391,17 +392,17 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps<DobbleVi
useEffect(() => {
if (!bubble) return;
const t = setTimeout(() => setBubble(null), bubble.kind === 'late' ? 1300 : 1700);
const t = setTimeout(() => setBubble(null), fxMs(bubble.kind === 'late' ? 1300 : 1700));
return () => clearTimeout(t);
}, [bubble]);
useEffect(() => {
if (!shake) return;
const t = setTimeout(() => setShake(false), 450);
const t = setTimeout(() => setShake(false), fxMs(450));
return () => clearTimeout(t);
}, [shake]);
useEffect(() => {
if (hitArt === null) return;
const t = setTimeout(() => setHitArt(null), 500);
const t = setTimeout(() => setHitArt(null), fxMs(500));
return () => clearTimeout(t);
}, [hitArt]);

View File

@@ -11,6 +11,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxAnim, fxMs } from '../../lib/motion';
const nick = (players: Record<string, PublicUser>, id: string | null | undefined) => (id ? (players[id]?.nickname ?? '알 수 없음') : '');
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
@@ -843,7 +844,7 @@ function rememberPlay(card: number | 'dummy'): void {
myPlayRect = card === 'dummy' ? null : (document.querySelector(`.gs-hcard[data-gs-hand$="c${card}"]`)?.getBoundingClientRect() ?? null);
}
const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, ms) : f());
const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, fxMs(ms)) : f());
const byAttr = (attr: string, key: string | number): Element | null => document.querySelector(`[${attr}="${cssEsc(String(key))}"]`);
const slotEl = (month: number) => (month > 0 ? byAttr('data-gs-month', month) : null);
const capEl = (id: string) => byAttr('data-fx-cap', id) ?? seatEl(id);
@@ -852,10 +853,10 @@ const CAP_KINDS = ['gwang', 'yeol', 'tti', 'pi'] as const;
/** A card turned face up (Web Animations, composite add, so it can run together with a fly-in). */
function flipIn(el: Element | null | undefined, delay = 0): void {
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
(el as HTMLElement).animate(
fxAnim((el as HTMLElement).animate(
[{ transform: 'perspective(600px) rotateY(90deg)' }, { transform: 'perspective(600px) rotateY(-12deg)', offset: 0.6 }, { transform: 'perspective(600px) rotateY(0deg)' }],
{ duration: 380, delay, easing: 'ease', fill: 'backwards', composite: 'add' },
);
));
}
function capOwners(v: GostopView): Map<string, string> {

View File

@@ -9,6 +9,7 @@ import { socket, useRoom } from '../../net/socket';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxMs } from '../../lib/motion';
const FRUITS: Fruit[] = ['strawberry', 'banana', 'lime', 'plum'];
const FRUIT_KO: Record<Fruit, string> = { strawberry: '딸기', banana: '바나나', lime: '라임', plum: '자두' };
@@ -536,19 +537,19 @@ function HalliGalliBoard({ view: v, me, players, act, pending }: BoardProps<Hall
useEffect(() => {
if (!ghosts.length) return;
const t = setTimeout(() => setGhosts([]), 1000);
const t = setTimeout(() => setGhosts([]), fxMs(1000));
return () => clearTimeout(t);
}, [ghosts]);
useEffect(() => {
if (!shake) return;
const t = setTimeout(() => setShake(null), 500);
const t = setTimeout(() => setShake(null), fxMs(500));
return () => clearTimeout(t);
}, [shake]);
useEffect(() => {
if (!bubble) return;
const t = setTimeout(() => setBubble(null), bubble.kind === 'late' ? 1300 : 1900);
const t = setTimeout(() => setBubble(null), fxMs(bubble.kind === 'late' ? 1300 : 1900));
return () => clearTimeout(t);
}, [bubble]);

View File

@@ -11,6 +11,7 @@ import { addedPieces, janggiCues, janggiMotion } from './fx';
import { helpNow } from './help';
import { nopeSound, pickSound, playJanggi, setupSound } from './sound';
import { quickStart } from './quick';
import { fxMs } from '../../lib/motion';
const SIDE_KO: Record<Side, string> = { cho: '초', han: '한' };
const INK: Record<Side, string> = { cho: '#1d4ed8', han: '#c0262d' };
@@ -246,7 +247,7 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps<JanggiVie
useEffect(() => {
if (!bubble) return;
const t = setTimeout(() => setBubble(null), 1600);
const t = setTimeout(() => setBubble(null), fxMs(1600));
return () => clearTimeout(t);
}, [bubble]);

View File

@@ -8,6 +8,7 @@ import { haptic, noise, sfx, tone } from '../../lib/feedback';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxMs } from '../../lib/motion';
const ROLL_MS = 650;
const HOUSE = 'house';
@@ -308,7 +309,7 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps<LasVeg
const end = setTimeout(() => {
setRolling(false);
setFlick(null);
}, ROLL_MS);
}, fxMs(ROLL_MS));
return () => {
clearInterval(t);
clearTimeout(end);
@@ -382,17 +383,17 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps<LasVeg
// Short-lived effects: forget them so later re-renders (e.g. the casino turning into a button) don't replay them.
useEffect(() => {
if (!drop) return;
const t = setTimeout(() => setDrop(null), 900);
const t = setTimeout(() => setDrop(null), fxMs(900));
return () => clearTimeout(t);
}, [drop]);
useEffect(() => {
if (dealt === null) return;
const t = setTimeout(() => setDealt(null), 1500);
const t = setTimeout(() => setDealt(null), fxMs(1500));
return () => clearTimeout(t);
}, [dealt]);
useEffect(() => {
if (!banner) return;
const t = setTimeout(() => setBanner(null), 1700);
const t = setTimeout(() => setBanner(null), fxMs(1700));
return () => clearTimeout(t);
}, [banner]);

View File

@@ -19,6 +19,7 @@ import { useChatOutbox, useTypingSignal } from '../../lib/chat-input';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxMs } from '../../lib/motion';
type Kind = LiarView['phase']['kind'];
@@ -714,7 +715,7 @@ function useLiarFx(v: LiarView, me: string | null, players: Record<string, Publi
if (fresh.some((e) => e.t !== 'phase' && e.t !== 'left')) {
timers.current.forEach(clearTimeout);
timers.current = [];
const later = (ms: number, f: () => void) => (ms ? void timers.current.push(setTimeout(f, ms)) : f());
const later = (ms: number, f: () => void) => (ms ? void timers.current.push(setTimeout(f, fxMs(ms))) : f());
const name = (id: string) => `${nick(players, id)}님`;
let t = 0;
const vote = fresh.find((e) => e.t === 'vote');

View File

@@ -19,6 +19,7 @@ import { useChatOutbox, useTypingSignal } from '../../lib/chat-input';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxMs } from '../../lib/motion';
// ---------------------------------------------------------------- names (original names only, docs §12)
@@ -820,7 +821,7 @@ function useMafiaFx(v: MafiaView, players: Record<string, PublicUser>, showBanne
if (fresh.length) {
timers.current.forEach(clearTimeout);
timers.current = [];
const later = (ms: number, f: () => void) => (ms ? void timers.current.push(setTimeout(f, ms)) : f());
const later = (ms: number, f: () => void) => (ms ? void timers.current.push(setTimeout(f, fxMs(ms))) : f());
const start = isNight(p) && !isNight(v) ? 900 : 0;
if (dying.length || saved.length) {
later(start, () => setTileFx({ dying, saved }));
@@ -882,7 +883,7 @@ function MafiaBoard({ view: v, me, players, act, pending }: BoardProps<MafiaView
wasNight.current = night;
if (night === before || ph.kind === 'ended' || ph.kind === 'roleReveal') return;
setSky({ kind: night ? 'night' : 'day', key: phaseKey });
const t = setTimeout(() => setSky(null), 1800);
const t = setTimeout(() => setSky(null), fxMs(1800));
return () => clearTimeout(t);
}, [phaseKey]); // eslint-disable-line react-hooks/exhaustive-deps

View File

@@ -10,6 +10,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { itemsOf, type Item } from './replay';
import { fxMs } from '../../lib/motion';
const COLORS = ['#e5484d', '#2f7cf6', '#1f9d55', '#f2a10c', '#8e5cf0', '#0ea5a4'];
@@ -428,7 +429,7 @@ function useRaceDrawing(v: MagicalAthleteView, liveStart: boolean, g: Geo) {
const t = setTimeout(() => {
timers.current.delete(t);
fn();
}, ms);
}, fxMs(ms));
timers.current.add(t);
};
useEffect(() => {
@@ -600,7 +601,7 @@ function useRaceDrawing(v: MagicalAthleteView, liveStart: boolean, g: Geo) {
pump();
}
: stepWalk,
last ? ms + (c.jump ? 60 : 120) : ms,
fxMs(last ? ms + (c.jump ? 60 : 120) : ms),
);
};
@@ -619,7 +620,7 @@ function useRaceDrawing(v: MagicalAthleteView, liveStart: boolean, g: Geo) {
w.timer = setTimeout(() => {
w.timer = null;
pump();
}, wait);
}, fxMs(wait));
return;
}
}

View File

@@ -9,6 +9,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { MAHJONG_TILE_CREDIT, Tile, tileName, tileOrder, tileShort } from './Tile';
import { fxMs } from '../../lib/motion';
const WIND = ['동', '남', '서', '북'];
const POS_KO = ['나', '오른쪽', '맞은편', '왼쪽'];
@@ -1120,13 +1121,13 @@ function MahjongBoard({ view: v, me, players, act, pending, deadline, tapConfirm
}, [hand, v.phase]);
useEffect(() => {
if (!dealing) return;
const t = setTimeout(() => setDealing(false), 900);
const t = setTimeout(() => setDealing(false), fxMs(900));
return () => clearTimeout(t);
}, [dealing]);
useEffect(() => {
if (!banner) return;
const t = setTimeout(() => setBanner((b) => (b && b.key === banner.key ? null : b)), 1700);
const t = setTimeout(() => setBanner((b) => (b && b.key === banner.key ? null : b)), fxMs(1700));
return () => clearTimeout(t);
}, [banner]);
@@ -1140,7 +1141,7 @@ function MahjongBoard({ view: v, me, players, act, pending, deadline, tapConfirm
}, [mine]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (!callout) return;
const t = setTimeout(() => setCallout((x) => (x && x.seq === callout.seq ? null : x)), 1300);
const t = setTimeout(() => setCallout((x) => (x && x.seq === callout.seq ? null : x)), fxMs(1300));
return () => clearTimeout(t);
}, [callout]);
useEffect(() => {

View File

@@ -10,6 +10,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
import { newEvents, toSegments, type Seg } from './events';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxMs } from '../../lib/motion';
type GameEvent = MarbleView['log'][number];
@@ -391,7 +392,7 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps<MarbleVi
const t = setTimeout(() => {
timers.current.delete(t);
fn();
}, ms);
}, fxMs(ms));
timers.current.add(t);
};
useEffect(() => {
@@ -526,7 +527,7 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps<MarbleVi
}
w.cur = { seg, i: 0, k: ++seen.current.k };
rerender((x) => x + 1);
w.timer = setTimeout(step, seg.walk ? stepMs(seg) : 160);
w.timer = setTimeout(step, fxMs(seg.walk ? stepMs(seg) : 160));
return;
}
};
@@ -555,7 +556,7 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps<MarbleVi
pump();
}
: step,
last ? (seg.walk ? 90 : 260) : stepMs(seg),
fxMs(last ? (seg.walk ? 90 : 260) : stepMs(seg)),
);
};
@@ -578,7 +579,7 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps<MarbleVi
const seq = r.seq;
setRolling(seq);
later(() => setRolling((x) => (x === seq ? null : x)), ROLL_MS);
walker.current.hold = Date.now() + ROLL_MS;
walker.current.hold = Date.now() + fxMs(ROLL_MS);
}
const thirdDouble = added?.some((e) => e.type === 'toIsland' && e.why === 'doubles');
if (r.double && !thirdDouble)
@@ -1188,7 +1189,7 @@ function PlayerCard({ p, v, me, players, deadline }: { p: MarblePlayerView; v: M
prev.current = p.cash;
if (d === 0) return;
setDelta({ n: d, k: Date.now() });
const t = setTimeout(() => setDelta(null), 1600);
const t = setTimeout(() => setDelta(null), fxMs(1600));
return () => clearTimeout(t);
}, [p.cash]);
const status: string[] = [];

View File

@@ -11,6 +11,7 @@ import { useSeatRows } from '../../lib/seat-rows';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow, resolvedHandSize } from './help';
import { quickStart } from './quick';
import { fxMs } from '../../lib/motion';
const MODE_KO: Record<NNOptions['mode'], string> = { 'kr-product': '전용 카드', classic: '트럼프 카드' };
const SUIT_KO: Record<string, string> = { S: '스페이드', H: '하트', D: '다이아', C: '클로버' };
@@ -55,8 +56,9 @@ function useCountUp(target: number): number {
}
let raf = 0;
const t0 = performance.now();
const len = fxMs(420);
const step = (t: number) => {
const k = Math.min(1, (t - t0) / 420);
const k = Math.min(1, (t - t0) / len);
setShown(Math.round(start + (target - start) * (1 - (1 - k) * (1 - k))));
if (k < 1) raf = requestAnimationFrame(step);
};
@@ -635,7 +637,7 @@ const nnLogKey = (e: LogEntry) => `${e.seq}-${e.t}-${'p' in e ? e.p : ''}`;
/** Sounds + motion for every change of the table, mine or anyone else's (log entries since the last view). */
function useNinetyNineFx(v: NinetyNineView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, ms) : f());
const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, fxMs(ms)) : f());
const who = (id: string) => (id === me ? '나' : `${nick(players, id)}님`);
const dealAll = (delay: number) => {
const deck = fxEl('nn-deck');

View File

@@ -12,6 +12,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner
import { fanCard, fanLayout, type FanLayout } from './fan';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxAnim, fxMs } from '../../lib/motion';
// Kept local (type-only import above) so the screen chunk does not pull in the rules module + zod.
const JOKER = 'X1';
@@ -72,7 +73,7 @@ function liftFly(from: DOMRect, to: Element | null | undefined, delay: number):
const dy = b.top + b.height / 2 - (from.top + from.height / 2);
// Onto a card in my hand: shrink to its size. Onto a seat: a small card.
const s = b.width <= 120 ? Math.max(0.4, Math.min(1.2, b.width / from.width)) : 0.6;
const anim = g.animate(
const anim = fxAnim(g.animate(
[
{ transform: 'translate(0px, 0px) scale(1) rotate(0deg)', opacity: 1 },
{ transform: 'translate(0px, -28px) scale(1.08) rotate(-4deg)', opacity: 1, offset: 0.3 },
@@ -80,11 +81,11 @@ function liftFly(from: DOMRect, to: Element | null | undefined, delay: number):
{ transform: `translate(${dx}px, ${dy}px) scale(${s}) rotate(0deg)`, opacity: 0 },
],
{ duration: LIFT_MS, delay, easing: 'cubic-bezier(.35,.6,.3,1)', fill: 'both' },
);
));
const done = () => g.remove();
anim.onfinish = done;
anim.oncancel = done;
setTimeout(done, LIFT_MS + delay + 1500);
setTimeout(done, fxMs(LIFT_MS + delay) + 1500);
return true;
}
@@ -92,8 +93,8 @@ function liftFly(from: DOMRect, to: Element | null | undefined, delay: number):
function reveal(el: Element, delay: number): void {
const h = el as HTMLElement;
if (typeof h.animate !== 'function') return;
h.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 120, delay, fill: 'backwards' });
h.animate([{ transform: 'scale(.8)' }, { transform: 'scale(1.1)', offset: 0.6 }, { transform: 'scale(1)' }], { duration: 280, delay, easing: 'ease-out', composite: 'add' });
fxAnim(h.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 120, delay, fill: 'backwards' }));
fxAnim(h.animate([{ transform: 'scale(.8)' }, { transform: 'scale(1.1)', offset: 0.6 }, { transform: 'scale(1)' }], { duration: 280, delay, easing: 'ease-out', composite: 'add' }));
}
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
@@ -618,10 +619,10 @@ function MyArea({ v, me, players, act, pending, deadline, fresh, bubble }: { v:
const dx = a[0] - b[0];
const dy = a[1] - b[1];
if (Math.abs(dx) + Math.abs(dy) < 2 || typeof c.animate !== 'function') continue;
c.animate(
fxAnim(c.animate(
[{ transform: `translate(${dx}px, ${dy}px)` }, { transform: `translate(${dx / 2}px, ${dy / 2 - 18}px)`, offset: 0.45 }, { transform: 'translate(0px, 0px)' }],
{ duration: 480, delay: n++ * 14, easing: 'cubic-bezier(.3,.7,.3,1)', fill: 'backwards', composite: 'add' },
);
));
}
}, [order, width, l.wrap]);
return (
@@ -729,12 +730,12 @@ function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm
if (msgs.length) setAnnounce(msgs.join(' '));
if (Object.keys(bub).length) {
setBubbles((b) => ({ ...b, ...bub }));
setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in bub)))), 2500);
setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in bub)))), fxMs(2500));
}
prev.current = { logCount: v.logCount, hand, turn: v.turn };
if (shuffled) {
setRiffle(true);
const t = setTimeout(() => setRiffle(false), 1000);
const t = setTimeout(() => setRiffle(false), fxMs(1000));
return () => clearTimeout(t);
}
return undefined;
@@ -767,7 +768,7 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string,
const amPlayer = !!me && v.order.includes(me);
const hand = v.myHand ?? [];
const prevHand = useRef(hand);
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, ms) : f());
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, fxMs(ms)) : f());
/** My seat is my own area; the hand inside it is a better spot for cards leaving / arriving. */
const spot = (p: string) => (p === me ? (fxEl('om-hand') ?? seatEl(p)) : seatEl(p));
const entries = v.log.map((e, i) => ({ e, n: v.logCount - v.log.length + i }));
@@ -858,7 +859,7 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string,
setTimeout(() => {
bump(seatEl(thief), 'shake');
bump(fxEl('om-table')?.querySelector('.om-thief-joker'), 'pop');
}, 200);
}, fxMs(200));
});
const started = useRef(false);
useLayoutEffect(() => {
@@ -867,7 +868,7 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string,
// Mounted right at the start (nobody has drawn or shuffled yet): show the deal once.
if (v.phase !== 'playing' || v.logCount !== 0 || v.turnNo !== 1) return;
sfx.shuffle();
setTimeout(() => sfx.deal(8, 60), 300);
setTimeout(() => sfx.deal(8, 60), fxMs(300));
// Next frame: the card rows lay themselves out once their width is known (useWidth), so measure after that.
requestAnimationFrame(() => {
const table = fxEl('om-table');

View File

@@ -10,6 +10,7 @@ import { bump, useBanner } from '../card-fx';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxMs } from '../../lib/motion';
type Color = 'black' | 'white';
const COLOR_KO: Record<Color, string> = { black: '흑', white: '백' };
@@ -59,7 +60,7 @@ function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps<OmokView>)
const [banner, showBanner] = useBanner();
useEffect(() => {
if (!refused) return;
const t = setTimeout(() => setRefused(null), 950);
const t = setTimeout(() => setRefused(null), fxMs(950));
return () => clearTimeout(t);
}, [refused]);

View File

@@ -5,6 +5,7 @@
import { useLayoutEffect, useRef, useState, type RefObject } from 'react';
import type { CardFace, LogEntry, OneCardView } from '@bg/games/one-card';
import { haptic, noise, sfx, tone } from '../../lib/feedback';
import { fxAnim, fxMs } from '../../lib/motion';
export interface Banner {
key: number;
@@ -128,14 +129,14 @@ function flyCards(root: HTMLElement, layer: HTMLElement, to: string, n: number,
el.remove();
continue;
}
const anim = el.animate(
const anim = fxAnim(el.animate(
[
{ transform: `translate(${x0}px, ${y0}px) rotate(0deg) scale(1)`, opacity: 1 },
{ transform: `translate(${(x0 + x1) / 2}px, ${Math.min(y0, y1) - lift}px) rotate(${i % 2 ? 160 : -160}deg) scale(1.08)`, opacity: 1, offset: 0.55 },
{ transform: `translate(${x1}px, ${y1}px) rotate(${i % 2 ? 350 : -350}deg) scale(0.7)`, opacity: 0.85 },
],
{ duration: FLY_MS, delay: delay0 + i * gap, easing: 'cubic-bezier(.3,.6,.35,1)', fill: 'both' },
);
));
anim.onfinish = () => el.remove();
anim.oncancel = () => el.remove();
}
@@ -147,7 +148,7 @@ function hitTable(root: HTMLElement, n: number, delay: number): void {
const table = root.querySelector<HTMLElement>('.oc-table');
if (!table || reduced() || typeof table.animate !== 'function') return;
const d = Math.min(14, 4 + n);
table.animate(
fxAnim(table.animate(
[
{ transform: 'none' },
{ transform: `translateX(${-d}px) rotate(-1deg)`, offset: 0.15 },
@@ -157,11 +158,11 @@ function hitTable(root: HTMLElement, n: number, delay: number): void {
{ transform: 'none' },
],
{ duration: 520, delay, easing: 'ease-out' },
);
table.animate(
));
fxAnim(table.animate(
[{ boxShadow: '0 0 0 0 rgba(239,68,68,0), inset 0 0 0 0 rgba(239,68,68,0)' }, { boxShadow: '0 0 30px 10px rgba(239,68,68,.85), inset 0 0 70px 20px rgba(239,68,68,.6)', offset: 0.3 }, { boxShadow: '0 0 0 0 rgba(239,68,68,0), inset 0 0 0 0 rgba(239,68,68,0)' }],
{ duration: 700, delay },
);
));
}
interface Ctx {
@@ -342,7 +343,7 @@ export function useOneCardFx({ view: v, me, nick }: Ctx, root: RefObject<HTMLDiv
if (banners.length || Object.keys(next).length) {
setFx((f) => ({ ...f, ...next, banners: [...f.banners, ...banners].slice(-3) }));
for (const b of banners) {
const t = window.setTimeout(() => setFx((f) => ({ ...f, banners: f.banners.filter((x) => x.key !== b.key) })), 1700);
const t = window.setTimeout(() => setFx((f) => ({ ...f, banners: f.banners.filter((x) => x.key !== b.key) })), fxMs(1700));
timers.current.push(t);
}
}

View File

@@ -12,6 +12,7 @@ import { helpNow } from './help';
import { quickStart } from './quick';
import { COLOR_HEX, COLOR_INK, COLOR_KO, ColorCardArt, colorCardLabel, patternName } from './ColorCard';
import { FX_CSS, useOneCardFx, type Fx } from './fx';
import { fxMs } from '../../lib/motion';
const SUITS: Suit[] = ['S', 'H', 'D', 'C'];
const COLORS: Color[] = ['R', 'Y', 'G', 'B'];
@@ -213,7 +214,7 @@ function AttackCount({ n, uno }: { n: number; uno: boolean }) {
tone(320 + k * 45, 55, 'square', 0.035);
if (k >= n) window.clearInterval(id);
},
Math.max(45, Math.min(110, 420 / (n - from))),
fxMs(Math.max(45, Math.min(110, 420 / (n - from)))),
);
return () => window.clearInterval(id);
}, [n]);

View File

@@ -11,6 +11,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxAnim, fxMs } from '../../lib/motion';
const MODE_KO: Record<PokerMode, string> = {
holdem: '텍사스 홀덤',
@@ -308,19 +309,19 @@ const pokerSfx = {
declare: (delay = 0) => tone(660, 120, 'triangle', 0.1, delay, { slideTo: 990 }),
};
const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, ms) : f());
const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, fxMs(ms)) : f());
/** Card turned over in place (WAAPI so React's own style/transform stays). */
function flipIn(el: Element | null | undefined, delay = 0): void {
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
(el as HTMLElement).animate(
fxAnim((el as HTMLElement).animate(
[
{ transform: 'perspective(600px) rotateY(90deg)' },
{ transform: 'perspective(600px) rotateY(-12deg)', offset: 0.6 },
{ transform: 'perspective(600px) rotateY(0deg)' },
],
{ duration: 420, delay, easing: 'ease', fill: 'backwards', composite: 'add' },
);
));
}
/**
@@ -337,19 +338,19 @@ function turnOver(el: Element | null | undefined, delay = 0): void {
back.setAttribute('aria-hidden', 'true');
Object.assign(back.style, { left: `${r.left}px`, top: `${r.top}px`, width: `${r.width}px`, height: `${r.height}px` });
document.body.appendChild(back);
const a = back.animate([{ transform: 'perspective(600px) rotateY(0deg)' }, { transform: 'perspective(600px) rotateY(-90deg)' }], { duration: half, delay, easing: 'ease-in', fill: 'both' });
const a = fxAnim(back.animate([{ transform: 'perspective(600px) rotateY(0deg)' }, { transform: 'perspective(600px) rotateY(-90deg)' }], { duration: half, delay, easing: 'ease-in', fill: 'both' }));
const done = () => back.remove();
a.onfinish = done;
a.oncancel = done;
setTimeout(done, delay + half + 1500);
(el as HTMLElement).animate(
setTimeout(done, fxMs(delay + half) + 1500);
fxAnim((el as HTMLElement).animate(
[
{ transform: 'perspective(600px) rotateY(90deg)' },
{ transform: 'perspective(600px) rotateY(-12deg)', offset: 0.65 },
{ transform: 'perspective(600px) rotateY(0deg)' },
],
{ duration: 300, delay: delay + half, easing: 'ease-out', fill: 'backwards', composite: 'add' },
);
));
}
/** The card elements of a seat on the table (forehead, hole, choice, up — same order as SeatCards). */

View File

@@ -11,6 +11,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, seatEl, useBanner, useNewEntries
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxMs } from '../../lib/motion';
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
@@ -52,7 +53,7 @@ function useTimed<T>(): [T | null, (v: T, ms: number) => void] {
const set = useCallback((v: T, ms: number) => {
clearTimeout(timer.current);
setVal(v);
timer.current = setTimeout(() => setVal(null), ms);
timer.current = setTimeout(() => setVal(null), fxMs(ms));
}, []);
return [val, set];
}
@@ -372,7 +373,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
const iWon = top.includes(me ?? '');
const text = iWon ? '승리!' : top.length ? `${top.map((p) => nick(players, p)).join(', ')}님 승리` : '게임 끝';
clearTimeout(winTimer.current);
winTimer.current = setTimeout(() => showBanner(text, iWon ? 'gold' : 'blue', v.match.total > 1 ? `${v.match.total}판 합계` : undefined), prev.phase === 'playing' ? 1500 : 0);
winTimer.current = setTimeout(() => showBanner(text, iWon ? 'gold' : 'blue', v.match.total > 1 ? `${v.match.total}판 합계` : undefined), prev.phase === 'playing' ? fxMs(1500) : 0);
}
}, [v]); // eslint-disable-line react-hooks/exhaustive-deps

View File

@@ -13,6 +13,7 @@ import { HwatuCard } from '../../components/cards/HwatuCard';
import { haptic, sfx, sounds } from '../../lib/feedback';
import { usePhone } from '../../lib/media';
import type { BoardProps } from '../types';
import { fxMs } from '../../lib/motion';
export const BET_KO: Record<BetType, string> = { check: '체크', ping: '삥', call: '콜', ddadang: '따당', quarter: '쿼터', half: '하프', full: '풀', die: '다이' };
/** Number keys like 한게임 섯다 (콜 7, 다이 8, 삥 4, 체크 5, 따당 1, 하프 0); 쿼터 2 and 풀 9 are ours. */
@@ -408,7 +409,7 @@ function useTableEffects(v: SeotdaView, me: string | null, tableRef: React.RefOb
const add: Fly[] = Array.from({ length: n }, (_, i) => ({ id: ++flyId.current, sx: a.x + (i % 2 ? 6 : -6), sy: a.y, dx: b.x - a.x, dy: b.y - a.y, d: i * 70 }));
setFlies((f) => [...f, ...add]);
const ids = new Set(add.map((x) => x.id));
setTimeout(() => setFlies((f) => f.filter((x) => !ids.has(x.id))), 700 + n * 70);
setTimeout(() => setFlies((f) => f.filter((x) => !ids.has(x.id))), fxMs(700 + n * 70));
};
useEffect(() => {
@@ -435,7 +436,7 @@ function useTableEffects(v: SeotdaView, me: string | null, tableRef: React.RefOb
sfx.chips(n);
launch(e.p, 'pot', n);
}
}, i * 220);
}, fxMs(i * 220));
});
// Result: reveal, payout, banner.
if (v.handPhase === 'handEnd' && prev.phase !== 'handEnd') {
@@ -456,13 +457,13 @@ function useTableEffects(v: SeotdaView, me: string | null, tableRef: React.RefOb
sounds.win();
haptic([40, 30, 80]);
} else if (me && v.showdown?.hands.some((h) => h.id === me) && !v.showdown.pots.some((p) => p.type === 'rematch' && p.winners.includes(me))) sounds.lose();
}, v.showdown ? 450 : 150);
}, fxMs(v.showdown ? 450 : 150));
}
}); // every render: cheap comparisons against the refs
useEffect(() => {
if (!banner) return undefined;
const t = setTimeout(() => setBanner(null), 1700);
const t = setTimeout(() => setBanner(null), fxMs(1700));
return () => clearTimeout(t);
}, [banner]);

View File

@@ -22,6 +22,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, useBanner, useChange, useNewEntr
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxMs } from '../../lib/motion';
// Type-only imports above keep the rules module out of the bundle; the few constants live here.
const COLORS: Color[] = ['W', 'U', 'G', 'R', 'K'];
@@ -438,7 +439,7 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
useEffect(() => {
if (!shake) return;
const t = setTimeout(() => setShake(null), 400);
const t = setTimeout(() => setShake(null), fxMs(400));
return () => clearTimeout(t);
}, [shake]);
@@ -946,7 +947,7 @@ function gemSpot(p: string, c: TokenColor, me: string | null): Element | null {
* previous view). Nothing on the first render (join, reload, replay jump).
*/
function useSplendorFx(v: SplendorView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, ms) : f());
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, fxMs(ms)) : f());
// Board of the previous view (slot key → card id) to know where a bought / reserved card was.
const prevBoard = useRef<Record<string, string | null> | null>(null);
// Nobles and my reserved cards disappear from the DOM with the new view: remember their rects while the DOM still

View File

@@ -11,6 +11,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
import { COLOR_HEX, COLOR_INK, COLOR_KO, ColorCardArt, patternName } from '../one-card/ColorCard';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxMs } from '../../lib/motion';
const COLORS: Color[] = ['R', 'Y', 'G', 'B'];
@@ -705,7 +706,7 @@ function UnoBoard({ view: v, me, players, act, pending, deadline }: BoardProps<U
/** Sounds + motion for every change of the table, mine or anyone else's (log entries since the last view). */
function useUnoFx(v: UnoView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, ms) : f());
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, fxMs(ms)) : f());
useNewEntries(v.log, logKey, (fresh) => {
let t = 0;
for (const e of fresh) {
@@ -781,7 +782,7 @@ function useUnoFx(v: UnoView, me: string | null, players: Record<string, PublicU
const deal = (myHand: boolean) => {
const deck = fxEl('uno-deck');
sfx.shuffle();
setTimeout(() => sfx.deal(7, 60), 300);
setTimeout(() => sfx.deal(7, 60), fxMs(300));
if (myHand) document.querySelectorAll('.un-hand .un-card').forEach((el, i) => flyFrom(el, deck, { delay: 280 + i * 60, rotate: 10 }));
for (const s of v.seats) if (s.id !== me && !s.left) flyGhost(deck, seatEl(s.id), { count: 3, gap: 90, delay: 280 });
};

View File

@@ -8,6 +8,7 @@ import { haptic, noise, sfx, tone } from '../../lib/feedback';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxMs } from '../../lib/motion';
// The client draws from the view only; names and hints live here so the rules module isn't bundled.
const NAME: Record<Category, string> = {
@@ -245,7 +246,7 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
const end = setTimeout(() => {
setAnim(null);
setFlick(null);
}, ROLL_MS);
}, fxMs(ROLL_MS));
return () => {
clearInterval(t);
clearTimeout(end);
@@ -254,7 +255,7 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
useEffect(() => {
if (!flash) return;
const t = setTimeout(() => setFlash(null), 1600);
const t = setTimeout(() => setFlash(null), fxMs(1600));
return () => clearTimeout(t);
}, [flash]);

View File

@@ -10,6 +10,7 @@ import { helpNow } from './help';
import { houseRules, optionsSummary } from './house-rules';
import { quickStart } from './quick';
import { HOP_MS, moveSound, throwSound } from './sound';
import { fxMs } from '../../lib/motion';
type From = number | 'home';
/** A source the player can pick: a stack (`"7"`, or `"7#2"` when stacks stand apart on 7) or the waiting pieces (`"home"`). */
@@ -217,7 +218,7 @@ function Sticks({ view: v, players }: { view: YutView; players: Record<string, P
seen.current = lt.no;
if (reducedMotion()) return;
setTossing(true);
const t = setTimeout(() => setTossing(false), 820);
const t = setTimeout(() => setTossing(false), fxMs(820));
return () => clearTimeout(t);
}, [lt?.no]); // eslint-disable-line react-hooks/exhaustive-deps
const sticks = lt?.sticks ?? [false, true, false, true];
@@ -338,22 +339,22 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
useEffect(() => {
if (!anim) return;
if (anim.i >= anim.pts.length - 1) {
const t = setTimeout(() => setAnim(null), 120);
const t = setTimeout(() => setAnim(null), fxMs(120));
return () => clearTimeout(t);
}
const t = setTimeout(() => setAnim((a) => (a && a.no === anim.no ? { ...a, i: a.i + 1 } : a)), 170);
const t = setTimeout(() => setAnim((a) => (a && a.no === anim.no ? { ...a, i: a.i + 1 } : a)), fxMs(170));
return () => clearTimeout(t);
}, [anim]);
useEffect(() => {
if (!landing) return;
const t = setTimeout(() => setLanding((l) => (l && l.no === landing.no ? null : l)), landing.delayMs + 700);
const t = setTimeout(() => setLanding((l) => (l && l.no === landing.no ? null : l)), fxMs(landing.delayMs + 700));
return () => clearTimeout(t);
}, [landing]);
useEffect(() => {
if (!flash) return;
const t = setTimeout(() => setFlash(null), 1100);
const t = setTimeout(() => setFlash(null), fxMs(1100));
return () => clearTimeout(t);
}, [flash]);

View File

@@ -0,0 +1,33 @@
import { afterEach, expect, test } from 'bun:test';
import { BASE_SLOWDOWN, fxAnim, fxMs, gameSpeed, motionScale, setGameSpeed } from './motion';
afterEach(() => setGameSpeed(1));
test('speed ×1 is a little slower than the written lengths; the admin speed divides them', () => {
expect(BASE_SLOWDOWN).toBe(1.5);
expect(fxMs(1000)).toBe(1500);
setGameSpeed(2);
expect(fxMs(1000)).toBe(750);
setGameSpeed(1 / 16);
expect(fxMs(1000)).toBe(24_000);
setGameSpeed(16);
expect(fxMs(1600)).toBe(150);
});
test('out-of-range or broken speeds are clamped / ignored', () => {
setGameSpeed(100);
expect(gameSpeed()).toBe(16);
setGameSpeed(0.001);
expect(gameSpeed()).toBe(1 / 16);
setGameSpeed('fast');
expect(gameSpeed()).toBe(1);
setGameSpeed(undefined);
expect(motionScale()).toBe(1.5);
});
test('fxAnim plays a Web Animation at the game speed (delay and duration together)', () => {
const anim = { playbackRate: 1 } as Animation;
setGameSpeed(3);
expect(fxAnim(anim).playbackRate).toBe(2);
expect(fxAnim(null)).toBeNull();
});

View File

@@ -0,0 +1,79 @@
/**
* Game speed on screen (admin setting `gameSpeed`, docs/14-admin.md §5; docs/07-ui-ux.md).
* Everything that moves in a game takes `motionScale()` times the length written in the code:
* - CSS animations and transitions inside the game screen: `useMotionScope` sets their `playbackRate`
* (delays and staggers included), so game CSS keeps its plain durations.
* - Web Animations (`el.animate(...)`): wrap them in `fxAnim` (flying copies live on <body>, outside the scope).
* - Timers that stage effects (how long a banner stays, the next step of a sequence, removing a flying copy): `fxMs`.
* Real-time things (turn timers, `[role="timer"]` bars, the drawing stream) and the chat are not scaled.
*/
import { useEffect, type RefObject } from 'react';
import { clampGameSpeed, GAME_SPEED_DEFAULT } from '@bg/shared/lite';
/** At speed ×1 everything takes this much longer than the durations written in the code (2026-10-14: a bit slower). */
export const BASE_SLOWDOWN = 1.5;
/** Animations inside these are left alone (real time / not part of the game). */
const SKIP = '.chat-panel, [role="timer"]';
let speed = GAME_SPEED_DEFAULT;
const listeners = new Set<() => void>();
/** Sets the speed from /api/config or the room view (out-of-range values are clamped). */
export function setGameSpeed(x: unknown): void {
const v = clampGameSpeed(x);
if (v === speed) return;
speed = v;
for (const f of listeners) f();
}
export const gameSpeed = (): number => speed;
/** How many times longer than written: `BASE_SLOWDOWN / speed`. */
export const motionScale = (): number => BASE_SLOWDOWN / speed;
/** A staging delay / duration in ms at the current game speed. */
export const fxMs = (ms: number): number => Math.round(ms * motionScale());
/** Plays a Web Animation at the current game speed (its duration, delay and staggers all scale). */
export function fxAnim<T extends Animation | null | undefined>(anim: T): T {
if (anim) anim.playbackRate = 1 / motionScale();
return anim;
}
function targetOf(a: Animation): Element | null {
const t = a.effect instanceof KeyframeEffect ? a.effect.target : null;
return t instanceof Element ? t : null;
}
/** Sets the playback rate of every animation under `root` (except chat / timers). Exported for tests. */
export function applyMotion(root: Element): void {
const rate = 1 / motionScale();
for (const a of root.getAnimations({ subtree: true })) {
if (a.playbackRate === rate) continue;
const t = targetOf(a);
if (t && t.closest(SKIP)) continue;
a.playbackRate = rate;
}
}
/**
* Keeps the CSS animations and transitions under `ref` (the game screen) at the game speed. Game animations start
* from DOM changes (a new element, a class, a style); the mutation observer runs before the next frame, so a new
* animation never plays a frame at the wrong speed.
*/
export function useMotionScope(ref: RefObject<Element | null>): void {
useEffect(() => {
const root = ref.current;
if (!root || typeof MutationObserver === 'undefined' || typeof root.getAnimations !== 'function') return;
const run = () => applyMotion(root);
const obs = new MutationObserver(run);
obs.observe(root, { subtree: true, childList: true, attributes: true });
listeners.add(run);
run();
return () => {
obs.disconnect();
listeners.delete(run);
};
}, [ref]);
}

View File

@@ -67,7 +67,7 @@ export interface RoomPreview {
export const api = {
config: () =>
call<{ discord: boolean; catalog: (CatalogEntry & { notice?: string })[]; siteName: string; announcement: string; maintenance: boolean }>('GET', '/api/config'),
call<{ discord: boolean; catalog: (CatalogEntry & { notice?: string })[]; siteName: string; announcement: string; maintenance: boolean; gameSpeed?: number }>('GET', '/api/config'),
me: () => call<MeResponse>('GET', '/api/me'),
guest: (nickname: string) => call<{ me: PublicUser }>('POST', '/api/auth/guest', { nickname }),
updateMe: (patch: { nickname?: string; useAvatar?: boolean; settings?: Settings }) => call<{ me: PublicUser }>('PATCH', '/api/me', patch),

View File

@@ -6,6 +6,7 @@ import { create } from 'zustand';
import { PROTOCOL, type GameResultView, type PublicUser, type RoomView, type ServerMessage } from '@bg/shared/lite';
import { toast } from '../store/toast';
import { markOutdated, noteServerBuild } from '../lib/update';
import { setGameSpeed } from '../lib/motion';
export type ConnStatus = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'replaced' | 'offline';
@@ -277,6 +278,7 @@ class GameSocket {
}
case 'room':
if (m.seq >= st.roomSeq || m.room.code !== st.room?.code) {
if (m.room.gameSpeed !== undefined) setGameSpeed(m.room.gameSpeed);
useRoom.setState({ room: m.room, roomSeq: m.seq, joinError: null });
if (m.room.status === 'playing' && st.result) useRoom.setState({ result: null });
}

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 { fxMs, useMotionScope } from '../lib/motion';
const STEP_MS = 1000;
@@ -106,6 +107,8 @@ function Player({ data, ui, onBack }: { data: ReplayData; ui: GameUI; onBack: ()
// The board is remounted on jumps (처음/끝/slider) so its move animations and sounds only follow single steps.
const [mount, setMount] = useState(0);
const at = useRef(0);
const layout = useRef<HTMLDivElement>(null);
useMotionScope(layout);
const go = (n: number, keepPlaying = false) => {
const t = Math.max(0, Math.min(last, n));
@@ -120,7 +123,7 @@ function Player({ data, ui, onBack }: { data: ReplayData; ui: GameUI; onBack: ()
useEffect(() => {
if (!playing) return;
if (i >= last) return setPlaying(false);
const t = setTimeout(() => goRef.current(i + 1, true), STEP_MS);
const t = setTimeout(() => goRef.current(i + 1, true), fxMs(STEP_MS));
return () => clearTimeout(t);
}, [playing, i, last]);
@@ -236,7 +239,7 @@ function Player({ data, ui, onBack }: { data: ReplayData; ui: GameUI; onBack: ()
<span className="muted small wide-only">{when}</span>
</div>
</nav>
<div className={`game-layout${wide ? '' : ' replay-narrow'}`}>
<div className={`game-layout${wide ? '' : ' replay-narrow'}`} ref={layout}>
<div className="game-main">
{!wide && status}
<div {...readOnly}>

View File

@@ -19,6 +19,7 @@ import { VolumeControl } from '../components/VolumeControl';
import { useWide } from '../lib/media';
import { GameHelp } from '../components/GameHelp';
import { PlayerName } from '../components/PlayerCard';
import { useMotionScope } from '../lib/motion';
export default function RoomPage() {
const { code = '' } = useParams();
@@ -640,6 +641,8 @@ function GameView({ room, ui, me, players, pending, slow }: { room: RoomView; ui
const game = useRoom((s) => s.game)!;
const tapConfirm = useSession((s) => s.settings.tapConfirm);
const wide = useWide();
const layout = useRef<HTMLDivElement>(null);
useMotionScope(layout);
const myTurn = ui.isMyTurn(game.view, me.id);
const isPlayer = room.seats.some((s) => s?.user.id === me.id) && game.active !== undefined;
const props = {
@@ -692,7 +695,7 @@ function GameView({ room, ui, me, players, pending, slow }: { room: RoomView; ui
</>
);
return (
<div className="game-layout">
<div className="game-layout" ref={layout}>
<div className="game-main">
{!wide && statusRow}
<ui.Board {...props} />

View File

@@ -1,7 +1,7 @@
/** 관리자 사이트 (docs/14-admin.md). Downloaded only when /admin is opened. */
import { useCallback, useEffect, useState, type ReactNode } from 'react';
import { NavLink, Route, Routes, useNavigate, useParams } from 'react-router';
import { formatRoomCode, type MyGameSummary } from '@bg/shared/lite';
import { formatRoomCode, GAME_SPEED_MAX, GAME_SPEED_MIN, type MyGameSummary } from '@bg/shared/lite';
import { ConfirmSheet, Sheet } from '../../components/ui';
import { apiCall, discordLoginUrl, type Role } from '../../net/api';
import { useSession } from '../../store/session';
@@ -351,6 +351,14 @@ function Rooms() {
// ------------------------------------------------------------------ site
const SPEED_PRESETS = [1 / 16, 1 / 8, 1 / 4, 1 / 2, 1, 2, 4, 8, 16];
/** 0.25 → "1/4배", 1.5 → "1.5배". */
function speedLabel(x: number): string {
if (!Number.isFinite(x) || x <= 0) return '-';
if (x < 1 && Number.isInteger(Math.round((1 / x) * 1000) / 1000)) return `1/${Math.round(1 / x)}배`;
return `${Math.round(x * 1000) / 1000}배`;
}
function Site() {
const [d] = useLoad<{ site: any }>('/site');
const [s, setS] = useState<any>(null);
@@ -400,6 +408,38 @@ function Site() {
</label>
{bool('maintenance', '점검 모드(새 방 만들기 막기)', '점검 중', '정상')}
</section>
<section className="card stack">
<div className="stack" style={{ gap: 6 }}>
<strong id="game-speed-label">
게임 속도 배율 <span className="muted small">(1/16~16배, 기본 1배)</span>
</strong>
<p className="muted small" style={{ margin: 0 }}>
게임 화면의 애니메이션과 컴퓨터가 생각하는 시간이 이 배율만큼 빨라져요. 2배는 두 배 빠르게, 1/2배는 두 배 느리게. 저장하면 진행 중인 방에도 바로 적용돼요. 턴 제한 시간 같은 규칙 시간은 바뀌지 않아요.
</p>
<div className="segmented" role="group" aria-labelledby="game-speed-label" style={{ flexWrap: 'wrap' }}>
{SPEED_PRESETS.map((x) => (
<button key={x} type="button" aria-pressed={s.gameSpeed === x} onClick={() => setS({ ...s, gameSpeed: x })}>
{speedLabel(x)}
</button>
))}
</div>
<label className="field">
직접 입력(배)
<input
className="input"
type="number"
min={GAME_SPEED_MIN}
max={GAME_SPEED_MAX}
step="any"
value={s.gameSpeed}
onChange={(e) => setS({ ...s, gameSpeed: Number(e.target.value) })}
/>
</label>
<span className="muted small" aria-live="polite">
지금 값: {speedLabel(s.gameSpeed)}
</span>
</div>
</section>
<section className="card stack">
{num('maxRoomsPerUser', '사용자당 동시에 만들 수 있는 방', 1, 50)}
{num('maxRooms', '서버 전체 방 수 제한', 10, 20000)}

View File

@@ -3,6 +3,7 @@ import { create } from 'zustand';
import type { CatalogEntry, PublicUser } from '@bg/shared/lite';
import { api, type Settings } from '../net/api';
import { socket } from '../net/socket';
import { setGameSpeed } from '../lib/motion';
const LS_KEY = 'bg.settings';
@@ -75,13 +76,14 @@ export const useSession = create<SessionState>((set, get) => ({
hasDiscordAvatar: false,
async refresh() {
const [cfg, me] = await Promise.all([
api.config().catch(() => ({ discord: false, catalog: [] as CatalogEntry[], siteName: '같이 놀자 보드게임', announcement: '', maintenance: false })),
api.config().catch(() => ({ discord: false, catalog: [] as CatalogEntry[], siteName: '같이 놀자 보드게임', announcement: '', maintenance: false, gameSpeed: 1 })),
api.me().catch(() => ({ me: null }) as Awaited<ReturnType<typeof api.me>>),
]);
const settings = { ...get().settings, ...withoutDeviceOnly(me.settings ?? {}) };
applySettings(settings);
localStorage.setItem(LS_KEY, JSON.stringify(settings));
document.title = cfg.siteName;
setGameSpeed(cfg.gameSpeed);
set({
loaded: true,
me: me.me,