V1.0.0
Two Keys: co-op mystery games for couples. Eight games on four engines (story, defuse, sync, labyrinth), two-device and couch play, mobile-first UI. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { GameSummary, RoomState } from '@two-keys/shared';
|
||||
import { getToken, saveSession } from './session';
|
||||
import { request, socket } from './socket';
|
||||
|
||||
/** Re-renders every `ms` and returns the current time. */
|
||||
export function useNow(ms = 1000): number {
|
||||
const [now, setNow] = useState(Date.now());
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => setNow(Date.now()), ms);
|
||||
return () => clearInterval(id);
|
||||
}, [ms]);
|
||||
return now;
|
||||
}
|
||||
|
||||
let gamesCache: Promise<GameSummary[]> | null = null;
|
||||
|
||||
export function useGames(): GameSummary[] | null {
|
||||
const [games, setGames] = useState<GameSummary[] | null>(null);
|
||||
useEffect(() => {
|
||||
gamesCache ??= fetch('/api/games').then((r) => {
|
||||
if (!r.ok) throw new Error('failed to load games');
|
||||
return r.json();
|
||||
});
|
||||
let alive = true;
|
||||
gamesCache.then((g) => alive && setGames(g)).catch(() => {
|
||||
gamesCache = null;
|
||||
if (alive) setGames([]);
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, []);
|
||||
return games;
|
||||
}
|
||||
|
||||
export interface RoomSnapshot {
|
||||
state: RoomState;
|
||||
/** Local time the state arrived, for running clocks between updates. */
|
||||
receivedAt: number;
|
||||
}
|
||||
|
||||
// One join per room at a time, shared between effect runs (StrictMode mounts twice).
|
||||
const joins = new Map<string, ReturnType<typeof request>>();
|
||||
|
||||
function join(code: string) {
|
||||
let pending = joins.get(code);
|
||||
if (!pending) {
|
||||
pending = request('room:join', { code, playerToken: getToken(code) }).then((res) => {
|
||||
joins.delete(code);
|
||||
if (res.ok) saveSession(res.code, res.playerToken);
|
||||
return res;
|
||||
});
|
||||
joins.set(code, pending);
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** Joins (or rejoins) a room and keeps its sanitized state up to date. */
|
||||
export function useRoom(code: string) {
|
||||
const [snapshot, setSnapshot] = useState<RoomSnapshot | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [connected, setConnected] = useState(socket.connected);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
const onConnect = () => {
|
||||
setConnected(true);
|
||||
join(code).then((res) => alive && setError(res.ok ? null : res.message));
|
||||
};
|
||||
const onDisconnect = () => setConnected(false);
|
||||
const onState = (state: RoomState) => {
|
||||
if (state.code === code) setSnapshot({ state, receivedAt: Date.now() });
|
||||
};
|
||||
|
||||
socket.on('connect', onConnect);
|
||||
socket.on('disconnect', onDisconnect);
|
||||
socket.on('room:state', onState);
|
||||
if (socket.connected) onConnect();
|
||||
return () => {
|
||||
alive = false;
|
||||
socket.off('connect', onConnect);
|
||||
socket.off('disconnect', onDisconnect);
|
||||
socket.off('room:state', onState);
|
||||
};
|
||||
}, [code]);
|
||||
|
||||
return { snapshot, error, connected };
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// localStorage can throw (private mode, blocked storage), so every access is wrapped.
|
||||
|
||||
function read(key: string): string | null {
|
||||
try {
|
||||
return localStorage.getItem(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function write(key: string, value: string | null) {
|
||||
try {
|
||||
if (value === null) localStorage.removeItem(key);
|
||||
else localStorage.setItem(key, value);
|
||||
} catch {
|
||||
/* play on without persistence */
|
||||
}
|
||||
}
|
||||
|
||||
const tokenKey = (code: string) => `twokeys:room:${code}`;
|
||||
const LAST_ROOM = 'twokeys:last-room';
|
||||
|
||||
/** The seat token for a room, so a refresh rejoins the same seat. */
|
||||
export const getToken = (code: string) => read(tokenKey(code));
|
||||
|
||||
export function saveSession(code: string, playerToken: string) {
|
||||
write(tokenKey(code), playerToken);
|
||||
write(LAST_ROOM, code);
|
||||
}
|
||||
|
||||
export const getLastRoom = () => read(LAST_ROOM);
|
||||
export const forgetLastRoom = () => write(LAST_ROOM, null);
|
||||
|
||||
export interface BestResult {
|
||||
finalSeconds: number;
|
||||
rank: string;
|
||||
hintsUsed: number;
|
||||
keysEarned: number;
|
||||
}
|
||||
|
||||
export function getBest(gameId: string): BestResult | null {
|
||||
try {
|
||||
return JSON.parse(read(`twokeys:best:${gameId}`) ?? 'null');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Keeps the best result per game: more keys first, then the faster time. */
|
||||
export function saveBest(gameId: string, result: BestResult): boolean {
|
||||
const best = getBest(gameId);
|
||||
const better =
|
||||
!best ||
|
||||
result.keysEarned > best.keysEarned ||
|
||||
(result.keysEarned === best.keysEarned && result.finalSeconds < best.finalSeconds);
|
||||
if (better) write(`twokeys:best:${gameId}`, JSON.stringify(result));
|
||||
return better;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { io } from 'socket.io-client';
|
||||
import type { JoinAck } from '@two-keys/shared';
|
||||
import { pushToast } from './toasts';
|
||||
|
||||
export const socket = io({ transports: ['websocket', 'polling'] });
|
||||
|
||||
socket.on('toast', ({ message }: { message: string }) => pushToast(message));
|
||||
socket.on('error', ({ message }: { message: string }) => pushToast(message, 'error'));
|
||||
|
||||
/** Emit an event that the server acknowledges (room:create, room:join). */
|
||||
export function request(event: string, payload: object): Promise<JoinAck> {
|
||||
return new Promise((resolve) => {
|
||||
socket.timeout(8000).emit(event, payload, (err: Error | null, res: JoinAck) => {
|
||||
resolve(err ? { ok: false, code: 'timeout', message: "Can't reach the server. Check your connection." } : res);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export type Send = (event: string, payload?: Record<string, unknown>) => void;
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useEffect } from 'react';
|
||||
import type { CSSProperties } from 'react';
|
||||
import type { Category, Role, Theme } from '@two-keys/shared';
|
||||
|
||||
/** "#7b1e3a" → "123 30 58", the form Tailwind's rgb(var(--x) / alpha) wants. */
|
||||
export function hexToRgb(hex: string): string {
|
||||
const n = parseInt(hex.slice(1), 16);
|
||||
return `${(n >> 16) & 255} ${(n >> 8) & 255} ${n & 255}`;
|
||||
}
|
||||
|
||||
export function themeVars(theme: Theme): CSSProperties {
|
||||
return {
|
||||
'--primary': hexToRgb(theme.primary),
|
||||
'--accent': hexToRgb(theme.accent),
|
||||
'--bg': hexToRgb(theme.background),
|
||||
'--heading-font': `'${theme.headingFont}'`,
|
||||
} as CSSProperties;
|
||||
}
|
||||
|
||||
/** Applies a game's theme to the whole page while a room is open. */
|
||||
export function useTheme(theme: Theme | undefined) {
|
||||
const key = theme ? JSON.stringify(theme) : '';
|
||||
useEffect(() => {
|
||||
if (!key) return;
|
||||
const root = document.documentElement;
|
||||
const vars = themeVars(JSON.parse(key)) as Record<string, string>;
|
||||
for (const [name, value] of Object.entries(vars)) root.style.setProperty(name, value);
|
||||
return () => {
|
||||
for (const name of Object.keys(vars)) root.style.removeProperty(name);
|
||||
};
|
||||
}, [key]);
|
||||
}
|
||||
|
||||
export const CATEGORY_LABEL: Record<Category, string> = {
|
||||
'murder-mystery': 'Murder Mystery',
|
||||
'escape-room': 'Escape Room',
|
||||
'co-op': 'Co-op',
|
||||
};
|
||||
|
||||
/** A is warm (amber), B is cool (teal). */
|
||||
export const ROLE_TEXT: Record<Role, string> = { A: 'text-roleA', B: 'text-roleB' };
|
||||
export const ROLE_BORDER: Record<Role, string> = { A: 'border-roleA/60', B: 'border-roleB/60' };
|
||||
export const ROLE_BG: Record<Role, string> = { A: 'bg-roleA/15', B: 'bg-roleB/15' };
|
||||
|
||||
export const difficultyKeys = (n: number) => '🔑'.repeat(n);
|
||||
@@ -0,0 +1,32 @@
|
||||
import { useSyncExternalStore } from 'react';
|
||||
|
||||
export interface Toast {
|
||||
id: number;
|
||||
message: string;
|
||||
kind: 'info' | 'error';
|
||||
}
|
||||
|
||||
let toasts: Toast[] = [];
|
||||
let nextId = 1;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function set(next: Toast[]) {
|
||||
toasts = next;
|
||||
listeners.forEach((l) => l());
|
||||
}
|
||||
|
||||
export function pushToast(message: string, kind: Toast['kind'] = 'info') {
|
||||
const id = nextId++;
|
||||
set([...toasts.slice(-2), { id, message, kind }]);
|
||||
setTimeout(() => set(toasts.filter((t) => t.id !== id)), 4500);
|
||||
}
|
||||
|
||||
export function useToasts(): Toast[] {
|
||||
return useSyncExternalStore(
|
||||
(listener) => {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
},
|
||||
() => toasts,
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user