mirror of
https://github.com/randyjc/Rahoot.git
synced 2026-03-14 04:25:35 +01:00
feat(reconnect): add reconnect for player & manager
This commit is contained in:
@@ -4,12 +4,12 @@ import { QuizzWithId } from "@rahoot/common/types/game"
|
||||
import ManagerPassword from "@rahoot/web/components/game/create/ManagerPassword"
|
||||
import SelectQuizz from "@rahoot/web/components/game/create/SelectQuizz"
|
||||
import { useEvent, useSocket } from "@rahoot/web/contexts/socketProvider"
|
||||
import { useManagerGameStore } from "@rahoot/web/stores/game"
|
||||
import { useManagerStore } from "@rahoot/web/stores/manager"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useState } from "react"
|
||||
|
||||
export default function Manager() {
|
||||
const { setStatus } = useManagerGameStore()
|
||||
const { setGameId, setStatus } = useManagerStore()
|
||||
const router = useRouter()
|
||||
const { socket } = useSocket()
|
||||
|
||||
@@ -22,6 +22,7 @@ export default function Manager() {
|
||||
})
|
||||
|
||||
useEvent("manager:gameCreated", ({ gameId, inviteCode }) => {
|
||||
setGameId(gameId)
|
||||
setStatus("SHOW_ROOM", { text: "Waiting for the players", inviteCode })
|
||||
router.push(`/game/manager/${gameId}`)
|
||||
})
|
||||
@@ -32,7 +33,6 @@ export default function Manager() {
|
||||
const handleCreate = (quizzId: string) => {
|
||||
console.log(quizzId)
|
||||
socket?.emit("game:create", quizzId)
|
||||
console.log("create room")
|
||||
}
|
||||
|
||||
if (!isAuth) {
|
||||
|
||||
@@ -8,24 +8,36 @@ import Question from "@rahoot/web/components/game/states/Question"
|
||||
import Result from "@rahoot/web/components/game/states/Result"
|
||||
import Start from "@rahoot/web/components/game/states/Start"
|
||||
import Wait from "@rahoot/web/components/game/states/Wait"
|
||||
import { useEvent } from "@rahoot/web/contexts/socketProvider"
|
||||
import { usePlayerGameStore } from "@rahoot/web/stores/game"
|
||||
import { useEvent, useSocket } from "@rahoot/web/contexts/socketProvider"
|
||||
import { usePlayerStore } from "@rahoot/web/stores/player"
|
||||
import { useQuestionStore } from "@rahoot/web/stores/question"
|
||||
import { GAME_STATE_COMPONENTS } from "@rahoot/web/utils/constants"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useEffect } from "react"
|
||||
import { useParams, useRouter } from "next/navigation"
|
||||
import toast from "react-hot-toast"
|
||||
|
||||
export default function Game() {
|
||||
const router = useRouter()
|
||||
const { player, logout } = usePlayerStore()
|
||||
const { status, setStatus, resetStatus } = usePlayerGameStore()
|
||||
const { socket, isConnected } = useSocket()
|
||||
const { gameId: gameIdParam }: { gameId?: string } = useParams()
|
||||
const { status, setPlayer, logout, setGameId, setStatus, resetStatus } =
|
||||
usePlayerStore()
|
||||
const { setQuestionStates } = useQuestionStore()
|
||||
|
||||
useEffect(() => {
|
||||
if (!player) {
|
||||
router.replace("/")
|
||||
useEvent("connect", () => {
|
||||
if (gameIdParam) {
|
||||
socket?.emit("player:reconnect", { gameId: gameIdParam })
|
||||
}
|
||||
}, [player, router])
|
||||
})
|
||||
|
||||
useEvent(
|
||||
"player:successReconnect",
|
||||
({ gameId, status, player, currentQuestion }) => {
|
||||
setGameId(gameId)
|
||||
setStatus(status.name, status.data)
|
||||
setPlayer(player)
|
||||
setQuestionStates(currentQuestion)
|
||||
},
|
||||
)
|
||||
|
||||
useEvent("game:status", ({ name, data }) => {
|
||||
if (name in GAME_STATE_COMPONENTS) {
|
||||
@@ -35,11 +47,19 @@ export default function Game() {
|
||||
|
||||
useEvent("game:reset", () => {
|
||||
router.replace("/")
|
||||
logout()
|
||||
resetStatus()
|
||||
logout()
|
||||
toast("The game has been reset by the host")
|
||||
})
|
||||
|
||||
if (!isConnected) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (!gameIdParam) {
|
||||
return null
|
||||
}
|
||||
|
||||
let component = null
|
||||
|
||||
switch (status.name) {
|
||||
|
||||
@@ -11,16 +11,20 @@ import Responses from "@rahoot/web/components/game/states/Responses"
|
||||
import Room from "@rahoot/web/components/game/states/Room"
|
||||
import Start from "@rahoot/web/components/game/states/Start"
|
||||
import { useEvent, useSocket } from "@rahoot/web/contexts/socketProvider"
|
||||
import { useManagerGameStore } from "@rahoot/web/stores/game"
|
||||
import { useManagerStore } from "@rahoot/web/stores/manager"
|
||||
import { useQuestionStore } from "@rahoot/web/stores/question"
|
||||
import { GAME_STATE_COMPONENTS_MANAGER } from "@rahoot/web/utils/constants"
|
||||
import { useParams } from "next/navigation"
|
||||
import { useParams, useRouter } from "next/navigation"
|
||||
import { useEffect, useState } from "react"
|
||||
import toast from "react-hot-toast"
|
||||
|
||||
export default function ManagerGame() {
|
||||
const { socket } = useSocket()
|
||||
const router = useRouter()
|
||||
const { gameId: gameIdParam }: { gameId?: string } = useParams()
|
||||
const { socket, isConnected } = useSocket()
|
||||
const [nextText, setNextText] = useState("Start")
|
||||
const { status, setStatus } = useManagerGameStore()
|
||||
const { gameId }: { gameId?: string } = useParams()
|
||||
const { gameId, status, setGameId, setStatus, setPlayers } = useManagerStore()
|
||||
const { setQuestionStates } = useQuestionStore()
|
||||
|
||||
useEvent("game:status", ({ name, data }) => {
|
||||
if (name in GAME_STATE_COMPONENTS_MANAGER) {
|
||||
@@ -28,12 +32,41 @@ export default function ManagerGame() {
|
||||
}
|
||||
})
|
||||
|
||||
useEvent("connect", () => {
|
||||
if (gameIdParam) {
|
||||
socket?.emit("manager:reconnect", { gameId: gameIdParam })
|
||||
}
|
||||
})
|
||||
|
||||
useEvent(
|
||||
"manager:successReconnect",
|
||||
({ gameId, status, players, currentQuestion }) => {
|
||||
setGameId(gameId)
|
||||
setStatus(status.name, status.data)
|
||||
setPlayers(players)
|
||||
setQuestionStates(currentQuestion)
|
||||
},
|
||||
)
|
||||
|
||||
useEvent("game:reset", () => {
|
||||
router.replace("/manager")
|
||||
toast("Game is not available anymore")
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (status.name === "SHOW_START") {
|
||||
if (status.name === Status.SHOW_START) {
|
||||
setNextText("Start")
|
||||
}
|
||||
}, [status.name])
|
||||
|
||||
if (!isConnected) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (!gameId) {
|
||||
return null
|
||||
}
|
||||
|
||||
const handleSkip = () => {
|
||||
setNextText("Skip")
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
"use client"
|
||||
|
||||
import { GameUpdateQuestion } from "@rahoot/common/types/game"
|
||||
import background from "@rahoot/web/assets/background.webp"
|
||||
import Button from "@rahoot/web/components/Button"
|
||||
import { useEvent, useSocket } from "@rahoot/web/contexts/socketProvider"
|
||||
import { usePlayerStore } from "@rahoot/web/stores/player"
|
||||
import { useQuestionStore } from "@rahoot/web/stores/question"
|
||||
import Image from "next/image"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { PropsWithChildren, useEffect, useState } from "react"
|
||||
import { PropsWithChildren, useEffect } from "react"
|
||||
|
||||
type Props = PropsWithChildren & {
|
||||
textNext?: string
|
||||
@@ -23,10 +23,9 @@ export default function GameWrapper({
|
||||
}: Props) {
|
||||
const { isConnected, connect } = useSocket()
|
||||
const { player, logout } = usePlayerStore()
|
||||
const { questionStates, setQuestionStates } = useQuestionStore()
|
||||
const router = useRouter()
|
||||
|
||||
const [questionState, setQuestionState] = useState<GameUpdateQuestion>()
|
||||
|
||||
useEffect(() => {
|
||||
if (!isConnected) {
|
||||
connect()
|
||||
@@ -39,7 +38,7 @@ export default function GameWrapper({
|
||||
})
|
||||
|
||||
useEvent("game:updateQuestion", ({ current, total }) => {
|
||||
setQuestionState({
|
||||
setQuestionStates({
|
||||
current,
|
||||
total,
|
||||
})
|
||||
@@ -56,9 +55,9 @@ export default function GameWrapper({
|
||||
</div>
|
||||
|
||||
<div className="flex w-full justify-between p-4">
|
||||
{questionState && (
|
||||
{questionStates && (
|
||||
<div className="shadow-inset flex items-center rounded-md bg-white p-2 px-4 text-lg font-bold text-black">
|
||||
{`${questionState.current} / ${questionState.total}`}
|
||||
{`${questionStates.current} / ${questionStates.total}`}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -11,12 +11,16 @@ import { KeyboardEvent, useState } from "react"
|
||||
|
||||
export default function Username() {
|
||||
const { socket } = useSocket()
|
||||
const { player, login } = usePlayerStore()
|
||||
const { gameId, login } = usePlayerStore()
|
||||
const router = useRouter()
|
||||
const [username, setUsername] = useState("")
|
||||
|
||||
const handleLogin = () => {
|
||||
socket?.emit("player:login", { gameId: player?.gameId, data: { username } })
|
||||
if (!gameId) {
|
||||
return
|
||||
}
|
||||
|
||||
socket?.emit("player:login", { gameId, data: { username } })
|
||||
}
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
|
||||
@@ -33,9 +33,10 @@ export default function Answers({
|
||||
volume: 0.1,
|
||||
})
|
||||
|
||||
const [playMusic] = useSound(SFX_ANSWERS_MUSIC, {
|
||||
const [playMusic, { stop: stopMusic }] = useSound(SFX_ANSWERS_MUSIC, {
|
||||
volume: 0.2,
|
||||
interrupt: true,
|
||||
loop: true,
|
||||
})
|
||||
|
||||
const handleAnswer = (answerKey: number) => () => {
|
||||
@@ -53,9 +54,12 @@ export default function Answers({
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
console.log("play music")
|
||||
playMusic()
|
||||
}, [])
|
||||
|
||||
return () => {
|
||||
stopMusic()
|
||||
}
|
||||
}, [playMusic])
|
||||
|
||||
useEvent("game:cooldown", (sec) => {
|
||||
setCooldown(sec)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { Player } from "@rahoot/common/types/game"
|
||||
import { ManagerStatusDataMap } from "@rahoot/common/types/game/status"
|
||||
import { useEvent, useSocket } from "@rahoot/web/contexts/socketProvider"
|
||||
import { useManagerStore } from "@rahoot/web/stores/manager"
|
||||
import { useState } from "react"
|
||||
|
||||
type Props = {
|
||||
@@ -11,7 +12,8 @@ type Props = {
|
||||
|
||||
export default function Room({ data: { text, inviteCode } }: Props) {
|
||||
const { socket } = useSocket()
|
||||
const [playerList, setPlayerList] = useState<Player[]>([])
|
||||
const { players } = useManagerStore()
|
||||
const [playerList, setPlayerList] = useState<Player[]>(players)
|
||||
const [totalPlayers, setTotalPlayers] = useState(0)
|
||||
|
||||
useEvent("manager:newPlayer", (player) => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/* eslint-disable no-empty-function */
|
||||
"use client"
|
||||
|
||||
import {
|
||||
ClientToServerEvents,
|
||||
ServerToClientEvents,
|
||||
@@ -13,12 +14,14 @@ import React, {
|
||||
useState,
|
||||
} from "react"
|
||||
import { io, Socket } from "socket.io-client"
|
||||
import { v7 as uuid } from "uuid"
|
||||
|
||||
type TypedSocket = Socket<ServerToClientEvents, ClientToServerEvents>
|
||||
|
||||
interface SocketContextValue {
|
||||
socket: TypedSocket | null
|
||||
isConnected: boolean
|
||||
clientId: string
|
||||
connect: () => void
|
||||
disconnect: () => void
|
||||
reconnect: () => void
|
||||
@@ -27,6 +30,7 @@ interface SocketContextValue {
|
||||
const SocketContext = createContext<SocketContextValue>({
|
||||
socket: null,
|
||||
isConnected: false,
|
||||
clientId: "",
|
||||
connect: () => {},
|
||||
disconnect: () => {},
|
||||
reconnect: () => {},
|
||||
@@ -38,11 +42,33 @@ const getSocketServer = async () => {
|
||||
return res.url
|
||||
}
|
||||
|
||||
const getClientId = (): string => {
|
||||
try {
|
||||
const stored = localStorage.getItem("client_id")
|
||||
|
||||
if (stored) {
|
||||
return stored
|
||||
}
|
||||
|
||||
const newId = uuid()
|
||||
localStorage.setItem("client_id", newId)
|
||||
|
||||
return newId
|
||||
} catch {
|
||||
return uuid()
|
||||
}
|
||||
}
|
||||
|
||||
export const SocketProvider = ({ children }: { children: React.ReactNode }) => {
|
||||
const [socket, setSocket] = useState<TypedSocket | null>(null)
|
||||
const [isConnected, setIsConnected] = useState(false)
|
||||
const [clientId] = useState<string>(() => getClientId())
|
||||
|
||||
useEffect(() => {
|
||||
if (socket) {
|
||||
return
|
||||
}
|
||||
|
||||
let s: TypedSocket | null = null
|
||||
|
||||
const initSocket = async () => {
|
||||
@@ -52,6 +78,9 @@ export const SocketProvider = ({ children }: { children: React.ReactNode }) => {
|
||||
s = io(socketUrl, {
|
||||
transports: ["websocket"],
|
||||
autoConnect: false,
|
||||
auth: {
|
||||
clientId,
|
||||
},
|
||||
})
|
||||
|
||||
setSocket(s)
|
||||
@@ -61,7 +90,6 @@ export const SocketProvider = ({ children }: { children: React.ReactNode }) => {
|
||||
})
|
||||
|
||||
s.on("disconnect", () => {
|
||||
console.log("Socket disconnected")
|
||||
setIsConnected(false)
|
||||
})
|
||||
|
||||
@@ -75,28 +103,26 @@ export const SocketProvider = ({ children }: { children: React.ReactNode }) => {
|
||||
|
||||
initSocket()
|
||||
|
||||
// eslint-disable-next-line consistent-return
|
||||
return () => {
|
||||
s?.disconnect()
|
||||
}
|
||||
}, [])
|
||||
}, [clientId])
|
||||
|
||||
const connect = useCallback(() => {
|
||||
if (socket && !socket.connected) {
|
||||
console.log("🔌 Manual connect")
|
||||
socket.connect()
|
||||
}
|
||||
}, [socket])
|
||||
|
||||
const disconnect = useCallback(() => {
|
||||
if (socket && socket.connected) {
|
||||
console.log("🧹 Manual disconnect")
|
||||
socket.disconnect()
|
||||
}
|
||||
}, [socket])
|
||||
|
||||
const reconnect = useCallback(() => {
|
||||
if (socket) {
|
||||
console.log("♻️ Manual reconnect")
|
||||
socket.disconnect()
|
||||
socket.connect()
|
||||
}
|
||||
@@ -107,6 +133,7 @@ export const SocketProvider = ({ children }: { children: React.ReactNode }) => {
|
||||
value={{
|
||||
socket,
|
||||
isConnected,
|
||||
clientId,
|
||||
connect,
|
||||
disconnect,
|
||||
reconnect,
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
import { StatusDataMap } from "@rahoot/common/types/game/status"
|
||||
import { create } from "zustand"
|
||||
|
||||
export type Status<T> = {
|
||||
[K in keyof T]: { name: K; data: T[K] }
|
||||
}[keyof T]
|
||||
|
||||
export function createStatus<T, K extends keyof T>(
|
||||
name: K,
|
||||
data: T[K],
|
||||
): Status<T> {
|
||||
return { name, data }
|
||||
}
|
||||
|
||||
type GameStore<T> = {
|
||||
status: Status<T>
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
setStatus: <K extends keyof T>(name: K, data: T[K]) => void
|
||||
resetStatus: () => void
|
||||
}
|
||||
|
||||
export const usePlayerGameStore = create<GameStore<StatusDataMap>>((set) => {
|
||||
const initialStatus = createStatus<StatusDataMap, "WAIT">("WAIT", {
|
||||
text: "Waiting for the players",
|
||||
})
|
||||
|
||||
return {
|
||||
status: initialStatus,
|
||||
setStatus: (name, data) => set({ status: createStatus(name, data) }),
|
||||
resetStatus: () => set({ status: initialStatus }),
|
||||
}
|
||||
})
|
||||
|
||||
export const useManagerGameStore = create<GameStore<StatusDataMap>>((set) => {
|
||||
const initialStatus = createStatus<StatusDataMap, "SHOW_ROOM">("SHOW_ROOM", {
|
||||
text: "Waiting for the players",
|
||||
})
|
||||
|
||||
return {
|
||||
status: initialStatus,
|
||||
setStatus: (name, data) => set({ status: createStatus(name, data) }),
|
||||
resetStatus: () => set({ status: initialStatus }),
|
||||
}
|
||||
})
|
||||
35
packages/web/src/stores/manager.tsx
Normal file
35
packages/web/src/stores/manager.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
/* eslint-disable no-unused-vars */
|
||||
import { Player } from "@rahoot/common/types/game"
|
||||
import { StatusDataMap } from "@rahoot/common/types/game/status"
|
||||
import { createStatus, Status } from "@rahoot/web/utils/createStatus"
|
||||
import { create } from "zustand"
|
||||
|
||||
type ManagerStore<T> = {
|
||||
gameId: string | null
|
||||
status: Status<T>
|
||||
players: Player[]
|
||||
|
||||
setGameId: (gameId: string | null) => void
|
||||
|
||||
setStatus: <K extends keyof T>(name: K, data: T[K]) => void
|
||||
resetStatus: () => void
|
||||
|
||||
setPlayers: (players: Player[]) => void
|
||||
}
|
||||
|
||||
const initialStatus = createStatus<StatusDataMap, "SHOW_ROOM">("SHOW_ROOM", {
|
||||
text: "Waiting for the players",
|
||||
})
|
||||
|
||||
export const useManagerStore = create<ManagerStore<StatusDataMap>>((set) => ({
|
||||
gameId: null,
|
||||
status: initialStatus,
|
||||
players: [],
|
||||
|
||||
setGameId: (gameId) => set({ gameId }),
|
||||
|
||||
setStatus: (name, data) => set({ status: createStatus(name, data) }),
|
||||
resetStatus: () => set({ status: initialStatus }),
|
||||
|
||||
setPlayers: (players) => set({ players }),
|
||||
}))
|
||||
@@ -1,32 +1,54 @@
|
||||
/* eslint-disable no-unused-vars */
|
||||
import { StatusDataMap } from "@rahoot/common/types/game/status"
|
||||
import { createStatus, Status } from "@rahoot/web/utils/createStatus"
|
||||
import { create } from "zustand"
|
||||
|
||||
type PlayerState = {
|
||||
gameId?: string
|
||||
username?: string
|
||||
points?: number
|
||||
}
|
||||
|
||||
type PlayerStore = {
|
||||
type PlayerStore<T> = {
|
||||
gameId: string | null
|
||||
player: PlayerState | null
|
||||
status: Status<T>
|
||||
|
||||
setGameId: (gameId: string | null) => void
|
||||
|
||||
setPlayer: (state: PlayerState) => void
|
||||
login: (gameId: string) => void
|
||||
join: (username: string) => void
|
||||
updatePoints: (points: number) => void
|
||||
logout: () => void
|
||||
|
||||
setStatus: <K extends keyof T>(name: K, data: T[K]) => void
|
||||
resetStatus: () => void
|
||||
}
|
||||
|
||||
export const usePlayerStore = create<PlayerStore>((set) => ({
|
||||
player: null,
|
||||
const initialStatus = createStatus<StatusDataMap, "WAIT">("WAIT", {
|
||||
text: "Waiting for the players",
|
||||
})
|
||||
|
||||
export const usePlayerStore = create<PlayerStore<StatusDataMap>>((set) => ({
|
||||
gameId: null,
|
||||
player: null,
|
||||
status: initialStatus,
|
||||
currentQuestion: null,
|
||||
|
||||
setGameId: (gameId) => set({ gameId }),
|
||||
|
||||
setPlayer: (player: PlayerState) => set({ player }),
|
||||
login: (username) =>
|
||||
set((state) => ({
|
||||
player: { ...state.player, username },
|
||||
})),
|
||||
|
||||
join: (gameId) =>
|
||||
join: (gameId) => {
|
||||
set((state) => ({
|
||||
player: { ...state.player, gameId, points: 0 },
|
||||
})),
|
||||
gameId,
|
||||
player: { ...state.player, points: 0 },
|
||||
}))
|
||||
},
|
||||
|
||||
updatePoints: (points) =>
|
||||
set((state) => ({
|
||||
@@ -34,4 +56,7 @@ export const usePlayerStore = create<PlayerStore>((set) => ({
|
||||
})),
|
||||
|
||||
logout: () => set({ player: null }),
|
||||
|
||||
setStatus: (name, data) => set({ status: createStatus(name, data) }),
|
||||
resetStatus: () => set({ status: initialStatus }),
|
||||
}))
|
||||
|
||||
14
packages/web/src/stores/question.tsx
Normal file
14
packages/web/src/stores/question.tsx
Normal file
@@ -0,0 +1,14 @@
|
||||
/* eslint-disable no-unused-vars */
|
||||
import { GameUpdateQuestion } from "@rahoot/common/types/game"
|
||||
import { create } from "zustand"
|
||||
|
||||
type QuestionStore = {
|
||||
questionStates: GameUpdateQuestion | null
|
||||
setQuestionStates: (state: GameUpdateQuestion) => void
|
||||
}
|
||||
|
||||
export const useQuestionStore = create<QuestionStore>((set) => ({
|
||||
questionStates: null,
|
||||
setQuestionStates: (state: GameUpdateQuestion) =>
|
||||
set({ questionStates: state }),
|
||||
}))
|
||||
8
packages/web/src/utils/createStatus.ts
Normal file
8
packages/web/src/utils/createStatus.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
export type Status<T> = {
|
||||
[K in keyof T]: { name: K; data: T[K] }
|
||||
}[keyof T]
|
||||
|
||||
export const createStatus = <T, K extends keyof T>(
|
||||
name: K,
|
||||
data: T[K],
|
||||
): Status<T> => ({ name, data })
|
||||
Reference in New Issue
Block a user