Новогодний квиз: ядро, сервер и три экрана

- ядро: контент, reducer всех фаз, undo, проекции по ролям
- сервер: комнаты, сокеты, таймеры, раздача интерфейса и медиа
- интерфейс: табло, пульт ведущего, телефон игрока
- контент: пак 5x5 с финалом и демо-пак с рабочим аудио
- 57 тестов и e2e на трёх вкладках
This commit is contained in:
oskarvitalii committed 2026-11-16 14:32:08 +07:00
commit 89eeea4855
54 files changed
+12010

No files matched your search

+130
View File
@@ -0,0 +1,130 @@
/**
* Единственное соединение страницы с сервером.
*
* Модуль-синглтон: на странице всегда одна роль (табло, пульт или телефон),
* поэтому второй сокет был бы лишним. Компоненты читают `state` и вызывают
* `send` — никакой другой логики здесь нет.
*/
import { ref, shallowRef } from 'vue'
import { io, type Socket } from 'socket.io-client'
import {
EVENTS,
type ClientRole,
type Command,
type GameEvent,
type HelloMessage,
type PublicState,
type ServerError,
} from '@quiz/shared'
export interface ConnectOptions {
role: ClientRole
room: string
token?: string
name?: string
playerId?: string
playerToken?: string
}
const state = shallowRef<PublicState | null>(null)
const hello = shallowRef<HelloMessage | null>(null)
const connected = ref(false)
const connecting = ref(false)
const lastError = ref('')
/** Последнее игровое событие: по нему включаются звук и вспышки. */
const lastEvent = shallowRef<{ value: GameEvent; at: number } | null>(null)
let socket: Socket | null = null
let lastSeq = -1
let counter = 0
function nextId(): string {
counter += 1
return `${Date.now().toString(36)}-${counter}`
}
export function connect(options: ConnectOptions): void {
disconnect()
lastSeq = -1
lastError.value = ''
connecting.value = true
const client = io({
auth: {
room: options.room,
role: options.role,
token: options.token,
name: options.name,
playerId: options.playerId,
playerToken: options.playerToken,
},
})
socket = client
client.on('connect', () => {
connected.value = true
connecting.value = false
})
client.on('disconnect', () => {
connected.value = false
})
client.on('connect_error', (error: Error) => {
connecting.value = false
connected.value = false
lastError.value = error.message
})
client.on(EVENTS.hello, (message: HelloMessage) => {
hello.value = message
// Запоминаем выданный токен: по нему сервер узнает нас после блокировки
// экрана и переподключения.
if (message.playerId && message.playerToken) {
client.auth = {
...(client.auth as Record<string, unknown>),
playerId: message.playerId,
playerToken: message.playerToken,
}
}
})
client.on(EVENTS.state, (next: PublicState) => {
if (next.seq < lastSeq) return
lastSeq = next.seq
state.value = next
})
client.on(EVENTS.error, (error: ServerError) => {
lastError.value = error.reason
})
client.on(EVENTS.event, (value: GameEvent) => {
lastEvent.value = { value, at: Date.now() }
})
}
export function disconnect(): void {
socket?.disconnect()
socket = null
connected.value = false
connecting.value = false
state.value = null
hello.value = null
}
export function send(command: Command): void {
socket?.emit(EVENTS.cmd, { cmdId: nextId(), command })
}
export function undo(): void {
socket?.emit(EVENTS.undo, { cmdId: nextId() })
}
export const game = {
state,
hello,
connected,
connecting,
lastError,
lastEvent,
connect,
disconnect,
send,
undo,
}
+33
View File
@@ -0,0 +1,33 @@
/** Определение комнаты: из ссылки, из сервера или из памяти браузера. */
import { normalizeRoomCode } from '@quiz/shared'
const ROOM_KEY = 'quiz:room'
export function rememberRoom(code: string): void {
try {
localStorage.setItem(ROOM_KEY, normalizeRoomCode(code))
} catch {
// Приватный режим — переживём.
}
}
export async function resolveRoom(fromQuery: unknown): Promise<string> {
if (typeof fromQuery === 'string' && fromQuery.trim()) return normalizeRoomCode(fromQuery)
try {
const response = await fetch('/api/room')
if (response.ok) {
const data = (await response.json()) as { code?: string }
if (data.code) return normalizeRoomCode(data.code)
}
} catch {
// Сервер может быть ещё не поднят — ниже попробуем сохранённое значение.
}
try {
return localStorage.getItem(ROOM_KEY) ?? ''
} catch {
return ''
}
}
+18
View File
@@ -0,0 +1,18 @@
/** Одно всплывающее сообщение на всё приложение. */
import { ref } from 'vue'
const message = ref('')
let timer: ReturnType<typeof setTimeout> | undefined
export function useToast() {
function say(text: string): void {
message.value = text
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
message.value = ''
}, 2800)
}
return { message, say }
}