- 서버: 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>
235 lines
11 KiB
TypeScript
235 lines
11 KiB
TypeScript
/**
|
|
* Motion + sound helpers shared by the card games (포커·고스톱·달무티·99·도둑잡기·우노·바퀴벌레 포커·뱅!, 2026-10-13).
|
|
*
|
|
* - 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 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;
|
|
|
|
type Where = Element | DOMRect | null | undefined;
|
|
|
|
function rectOf(w: Where): DOMRect | null {
|
|
if (!w) return null;
|
|
const r = w instanceof Element ? w.getBoundingClientRect() : w;
|
|
return r.width === 0 && r.height === 0 ? null : r;
|
|
}
|
|
|
|
const center = (r: DOMRect) => ({ x: r.left + r.width / 2, y: r.top + r.height / 2 });
|
|
|
|
/** `CSS.escape` (games usually shadow `CSS` with their own style string). */
|
|
export const cssEsc = (v: string): string => CSS.escape(v);
|
|
|
|
/** First element matching `[data-fx="<name>"]` (pile, deck, pot, hand …) or a seat `[data-fx-seat="<player id>"]`. */
|
|
export const fxEl = (name: string): Element | null => document.querySelector(`[data-fx="${CSS.escape(name)}"]`);
|
|
export const seatEl = (player: string): Element | null => document.querySelector(`[data-fx-seat="${CSS.escape(player)}"]`);
|
|
|
|
export interface FlyOpts {
|
|
ms?: number;
|
|
delay?: number;
|
|
/** Start scale (default 0.6). */
|
|
scale?: number;
|
|
/** Start rotation in degrees (default -10). */
|
|
rotate?: number;
|
|
}
|
|
|
|
/** Makes `el` (already at its final place) fly in from `from` (an element or rect). */
|
|
export function flyFrom(el: Element | null | undefined, from: Where, o: FlyOpts = {}): void {
|
|
const a = rectOf(from);
|
|
const b = rectOf(el);
|
|
if (!el || !a || !b || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
|
|
const p = center(a);
|
|
const q = center(b);
|
|
const dx = p.x - q.x;
|
|
const dy = p.y - q.y;
|
|
if (Math.abs(dx) + Math.abs(dy) < 4) return;
|
|
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' },
|
|
),
|
|
);
|
|
}
|
|
|
|
export type GhostKind = 'card' | 'hwatu' | 'chip' | 'coin';
|
|
|
|
export interface GhostOpts {
|
|
kind?: GhostKind;
|
|
/** How many copies (staggered by `gap` ms), e.g. dealing 3 cards or a stack of chips. */
|
|
count?: number;
|
|
gap?: number;
|
|
ms?: number;
|
|
delay?: number;
|
|
/** Optional text on the ghost (a chip amount, a card name). */
|
|
label?: string;
|
|
/** Extra class for a game-specific look (game CSS must target `.fx-ghost.<class>`). */
|
|
className?: string;
|
|
}
|
|
|
|
const GHOST_SIZE: Record<GhostKind, [number, number]> = { card: [40, 56], hwatu: [34, 54], chip: [22, 22], coin: [22, 22] };
|
|
|
|
/**
|
|
* A temporary copy flying from one place to another (card dealt to a seat, chips to the pot, pot to the winner …).
|
|
* Fixed-position, pointer-events none, removed when done.
|
|
*/
|
|
export function flyGhost(from: Where, to: Where, o: GhostOpts = {}): void {
|
|
const a = rectOf(from);
|
|
const b = rectOf(to);
|
|
if (!a || !b || reducedMotion() || typeof document === 'undefined') return;
|
|
ensureCss();
|
|
const kind = o.kind ?? 'card';
|
|
const [w, h] = GHOST_SIZE[kind];
|
|
const p = center(a);
|
|
const q = center(b);
|
|
const n = Math.max(1, Math.min(o.count ?? 1, 12));
|
|
for (let i = 0; i < n; i++) {
|
|
const g = document.createElement('div');
|
|
g.className = `fx-ghost fx-ghost-${kind}${o.className ? ` ${o.className}` : ''}`;
|
|
g.setAttribute('aria-hidden', 'true');
|
|
if (o.label) g.textContent = o.label;
|
|
g.style.left = `${p.x - w / 2}px`;
|
|
g.style.top = `${p.y - h / 2}px`;
|
|
document.body.appendChild(g);
|
|
const jitter = n > 1 ? (i - (n - 1) / 2) * 6 : 0;
|
|
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, fxMs((o.ms ?? 480) + (o.delay ?? 0) + i * (o.gap ?? 70)) + 1500);
|
|
}
|
|
}
|
|
|
|
/** Quick attention wiggle / pop on an element that is already there (a seat that drew, a counter that changed). */
|
|
export function bump(el: Element | null | undefined, kind: 'pop' | 'shake' = 'pop'): void {
|
|
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
|
|
const frames =
|
|
kind === 'pop'
|
|
? [{ transform: 'scale(1)' }, { transform: 'scale(1.12)', offset: 0.4 }, { transform: 'scale(1)' }]
|
|
: [
|
|
{ transform: 'translateX(0px)' },
|
|
{ transform: 'translateX(-6px) rotate(-2deg)', offset: 0.25 },
|
|
{ transform: 'translateX(6px) rotate(2deg)', offset: 0.5 },
|
|
{ transform: 'translateX(-4px) rotate(-1deg)', offset: 0.75 },
|
|
{ transform: 'translateX(0px)' },
|
|
];
|
|
fxAnim((el as HTMLElement).animate(frames, { duration: kind === 'pop' ? 320 : 420, easing: 'ease-out', composite: 'add' }));
|
|
}
|
|
|
|
// ---------------------------------------------------------------- hooks
|
|
|
|
/**
|
|
* Calls `onNew` (in a layout effect, before paint, so new elements can still be animated from elsewhere) with the
|
|
* entries of `list` whose `key` was not there on the previous render. Never on the first render. A jump of more
|
|
* than `max` new entries at once (resync, reconnect) is skipped silently.
|
|
*/
|
|
export function useNewEntries<T>(list: readonly T[] | null | undefined, key: (t: T) => string | number, onNew: (fresh: T[]) => void, max = 12): void {
|
|
const seen = useRef<Set<string | number> | null>(null);
|
|
const cb = useRef(onNew);
|
|
cb.current = onNew;
|
|
useLayoutEffect(() => {
|
|
const items = list ?? [];
|
|
const keys = items.map(key);
|
|
const prev = seen.current;
|
|
seen.current = new Set(keys);
|
|
if (!prev) return;
|
|
const fresh = items.filter((_, i) => !prev.has(keys[i]!));
|
|
if (fresh.length && fresh.length <= max) cb.current(fresh);
|
|
});
|
|
}
|
|
|
|
/** Calls `onChange(now, before)` in a layout effect when `value` (compared with `Object.is`) changes; not on the first render. */
|
|
export function useChange<T>(value: T, onChange: (now: T, before: T) => void): void {
|
|
const prev = useRef<{ v: T } | null>(null);
|
|
const cb = useRef(onChange);
|
|
cb.current = onChange;
|
|
useLayoutEffect(() => {
|
|
const before = prev.current;
|
|
prev.current = { v: value };
|
|
if (before && !Object.is(before.v, value)) cb.current(value, before.v);
|
|
}, [value]);
|
|
}
|
|
|
|
export type BannerTone = 'gold' | 'red' | 'blue' | 'green' | 'dark';
|
|
|
|
/**
|
|
* Big short banner over the screen (우노!, 뻑!, 고!, 혁명!, 뱅! …). `show` replaces the current one.
|
|
* Render `node` once inside the board.
|
|
*/
|
|
export function useBanner(): [ReactNode, (text: string, tone?: BannerTone, sub?: string) => void] {
|
|
const [b, setB] = useState<{ id: number; text: string; tone: BannerTone; sub?: string } | null>(null);
|
|
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
const show = (text: string, tone: BannerTone = 'gold', sub?: string) => {
|
|
ensureCss();
|
|
if (timer.current) clearTimeout(timer.current);
|
|
setB((old) => ({ id: (old?.id ?? 0) + 1, text, tone, sub }));
|
|
timer.current = setTimeout(() => setB(null), fxMs(1700));
|
|
};
|
|
useLayoutEffect(() => () => {
|
|
if (timer.current) clearTimeout(timer.current);
|
|
}, []);
|
|
const node = b ? (
|
|
<div className="fx-banner-wrap" aria-hidden>
|
|
<div key={b.id} className={`fx-banner anim-banner fx-${b.tone}`}>
|
|
{b.text}
|
|
{b.sub && <small>{b.sub}</small>}
|
|
</div>
|
|
</div>
|
|
) : null;
|
|
return [node, show];
|
|
}
|
|
|
|
// ---------------------------------------------------------------- CSS
|
|
|
|
const FX_CSS = `
|
|
.fx-ghost { position: fixed; z-index: 60; pointer-events: none; box-sizing: border-box; will-change: transform, opacity; }
|
|
.fx-ghost-card { width: 40px; height: 56px; border-radius: 6px; background: #1e3a8a; border: 2px solid #fff;
|
|
box-shadow: 0 3px 8px rgba(0,0,0,.35), inset 0 0 0 4px #1e3a8a, inset 0 0 0 6px #93c5fd; }
|
|
.fx-ghost-hwatu { width: 34px; height: 54px; border-radius: 4px; background: #b91c1c; border: 2px solid #1f2937;
|
|
box-shadow: 0 3px 8px rgba(0,0,0,.35), inset 0 0 0 3px #7f1d1d; }
|
|
.fx-ghost-chip, .fx-ghost-coin { width: 22px; height: 22px; border-radius: 50%; display: flex; align-items: center; justify-content: center;
|
|
font: 800 10px/1 system-ui, sans-serif; color: #fff; white-space: nowrap; }
|
|
.fx-ghost-chip { background: #dc2626; border: 3px dashed #fff; box-shadow: 0 2px 5px rgba(0,0,0,.4), 0 0 0 1px #7f1d1d; }
|
|
.fx-ghost-coin { background: #f59e0b; border: 2px solid #fde68a; box-shadow: 0 2px 5px rgba(0,0,0,.4), 0 0 0 1px #92400e; color: #451a03; }
|
|
.fx-banner-wrap { position: fixed; inset: 0; z-index: 70; display: flex; align-items: center; justify-content: center; pointer-events: none; }
|
|
.fx-banner { pointer-events: none; font-size: clamp(2.2rem, 9vw, 4.6rem); font-weight: 900; letter-spacing: .02em; line-height: 1.05; text-align: center;
|
|
padding: .18em .6em; border-radius: 22px; color: #fff; border: 5px solid #fff; box-shadow: 0 10px 30px rgba(0,0,0,.4);
|
|
text-shadow: 0 3px 0 rgba(0,0,0,.3); display: flex; flex-direction: column; align-items: center; max-width: 92vw; }
|
|
.fx-banner small { font-size: .32em; font-weight: 800; text-shadow: none; opacity: .95; margin-top: .2em; }
|
|
.fx-gold { background: linear-gradient(180deg, #f59e0b, #d97706); }
|
|
.fx-red { background: linear-gradient(180deg, #ef4444, #b91c1c); }
|
|
.fx-blue { background: linear-gradient(180deg, #3b82f6, #1d4ed8); }
|
|
.fx-green { background: linear-gradient(180deg, #22c55e, #15803d); }
|
|
.fx-dark { background: linear-gradient(180deg, #374151, #111827); }
|
|
`;
|
|
|
|
let cssDone = false;
|
|
function ensureCss(): void {
|
|
if (cssDone || typeof document === 'undefined') return;
|
|
cssDone = true;
|
|
const s = document.createElement('style');
|
|
s.dataset.fx = 'card-fx';
|
|
s.textContent = FX_CSS;
|
|
document.head.appendChild(s);
|
|
}
|