style: apply prettier formatting across codebase
This commit is contained in:
+167
-67
@@ -1,7 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useCallback, useEffect, useRef } from "react";
|
||||
import { fetchArticle, pickTwoArticles, prefetchArticle, POLL_INTERVAL, COUNTDOWN_DURATION } from "./wiki";
|
||||
import {
|
||||
fetchArticle,
|
||||
pickTwoArticles,
|
||||
prefetchArticle,
|
||||
POLL_INTERVAL,
|
||||
COUNTDOWN_DURATION,
|
||||
} from "./wiki";
|
||||
import { useTimer } from "./useTimer";
|
||||
import { saveSession, clearSession } from "./session";
|
||||
import type { Room } from "../app/api/rooms/route";
|
||||
@@ -32,11 +38,18 @@ export function useMultiGame() {
|
||||
// Article loading
|
||||
|
||||
async function loadArticle(t: string): Promise<string | null> {
|
||||
setLoading(true); loadingRef.current = true; setLoadError(null);
|
||||
setLoading(true);
|
||||
loadingRef.current = true;
|
||||
setLoadError(null);
|
||||
const art = await fetchArticle(t);
|
||||
setLoading(false); loadingRef.current = false;
|
||||
if (!art) { setLoadError(`Impossible de charger "${t}".`); return null; }
|
||||
setHtml(art.html); setTitle(art.title);
|
||||
setLoading(false);
|
||||
loadingRef.current = false;
|
||||
if (!art) {
|
||||
setLoadError(`Impossible de charger "${t}".`);
|
||||
return null;
|
||||
}
|
||||
setHtml(art.html);
|
||||
setTitle(art.title);
|
||||
return art.title;
|
||||
}
|
||||
|
||||
@@ -53,14 +66,20 @@ export function useMultiGame() {
|
||||
}
|
||||
|
||||
function stopCountdown() {
|
||||
if (countdownRef.current) { clearInterval(countdownRef.current); countdownRef.current = null; }
|
||||
if (countdownRef.current) {
|
||||
clearInterval(countdownRef.current);
|
||||
countdownRef.current = null;
|
||||
}
|
||||
setCountdown(null);
|
||||
}
|
||||
|
||||
// Polling
|
||||
|
||||
function stopPolling() {
|
||||
if (pollRef.current) { clearInterval(pollRef.current); pollRef.current = null; }
|
||||
if (pollRef.current) {
|
||||
clearInterval(pollRef.current);
|
||||
pollRef.current = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function poll(code: string, pid: string) {
|
||||
@@ -70,8 +89,10 @@ export function useMultiGame() {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "heartbeat", playerId: pid }),
|
||||
});
|
||||
if (res.ok) setRoom((await res.json() as { room: Room }).room);
|
||||
} catch { /* ignore */ }
|
||||
if (res.ok) setRoom(((await res.json()) as { room: Room }).room);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
const pollCodeRef = useRef<string | null>(null);
|
||||
@@ -87,14 +108,18 @@ export function useMultiGame() {
|
||||
// Relance le polling quand le tab redevient visible (les setInterval sont throttlés en arrière-plan)
|
||||
useEffect(() => {
|
||||
function onVisible() {
|
||||
if (document.visibilityState === "visible" && pollCodeRef.current && pollPidRef.current) {
|
||||
if (
|
||||
document.visibilityState === "visible" &&
|
||||
pollCodeRef.current &&
|
||||
pollPidRef.current
|
||||
) {
|
||||
poll(pollCodeRef.current, pollPidRef.current);
|
||||
startPolling(pollCodeRef.current, pollPidRef.current);
|
||||
}
|
||||
}
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
return () => document.removeEventListener("visibilitychange", onVisible);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// Phase sync
|
||||
@@ -107,8 +132,10 @@ export function useMultiGame() {
|
||||
prevRoundRef.current = room.round;
|
||||
|
||||
if (room.phase === "countdown" && prevPhase !== "countdown") {
|
||||
setHtml(""); setLoadError(null);
|
||||
clicksRef.current = 0; setClicksDisplay(0);
|
||||
setHtml("");
|
||||
setLoadError(null);
|
||||
clicksRef.current = 0;
|
||||
setClicksDisplay(0);
|
||||
timerStartedRef.current = false;
|
||||
timer.reset();
|
||||
startCountdown(room.countdownStart ?? Date.now());
|
||||
@@ -125,7 +152,7 @@ export function useMultiGame() {
|
||||
if (room.round !== prevRound && room.phase === "playing") {
|
||||
loadArticle(room.startArticle);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [room]);
|
||||
|
||||
// Countdown -> playing transition
|
||||
@@ -136,72 +163,117 @@ export function useMultiGame() {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "play", playerId }),
|
||||
}).then((r) => r.json()).then((d) => {
|
||||
if ((d as { room: Room }).room) setRoom((d as { room: Room }).room);
|
||||
}).catch(() => {});
|
||||
})
|
||||
.then((r) => r.json())
|
||||
.then((d) => {
|
||||
if ((d as { room: Room }).room) setRoom((d as { room: Room }).room);
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
}, [countdown, room, playerId]);
|
||||
|
||||
// Navigation
|
||||
|
||||
const navigate = useCallback(async (t: string) => {
|
||||
if (!room || !playerId || loadingRef.current || room.phase !== "playing") return;
|
||||
clicksRef.current += 1; setClicksDisplay(clicksRef.current);
|
||||
if (!timerStartedRef.current) { timer.start(); timerStartedRef.current = true; }
|
||||
const navigate = useCallback(
|
||||
async (t: string) => {
|
||||
if (!room || !playerId || loadingRef.current || room.phase !== "playing")
|
||||
return;
|
||||
clicksRef.current += 1;
|
||||
setClicksDisplay(clicksRef.current);
|
||||
if (!timerStartedRef.current) {
|
||||
timer.start();
|
||||
timerStartedRef.current = true;
|
||||
}
|
||||
|
||||
// Heartbeat optimiste pour éviter le kick pendant le chargement de l'article
|
||||
fetch(`/api/rooms/${room.code}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "heartbeat", playerId }),
|
||||
}).catch(() => {});
|
||||
|
||||
const canonical = await loadArticle(t);
|
||||
if (!canonical) return;
|
||||
|
||||
const newHistory = [...historyRef.current, canonical];
|
||||
historyRef.current = newHistory;
|
||||
setHistory(newHistory);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/rooms/${room.code}`, {
|
||||
// Heartbeat optimiste pour éviter le kick pendant le chargement de l'article
|
||||
fetch(`/api/rooms/${room.code}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "navigate", playerId, article: canonical }),
|
||||
});
|
||||
if (res.ok) setRoom((await res.json() as { room: Room }).room);
|
||||
} catch { /* on continue localement */ }
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [room, playerId]);
|
||||
body: JSON.stringify({ action: "heartbeat", playerId }),
|
||||
}).catch(() => {});
|
||||
|
||||
const canonical = await loadArticle(t);
|
||||
if (!canonical) return;
|
||||
|
||||
const newHistory = [...historyRef.current, canonical];
|
||||
historyRef.current = newHistory;
|
||||
setHistory(newHistory);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/rooms/${room.code}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
action: "navigate",
|
||||
playerId,
|
||||
article: canonical,
|
||||
}),
|
||||
});
|
||||
if (res.ok) setRoom(((await res.json()) as { room: Room }).room);
|
||||
} catch {
|
||||
/* on continue localement */
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
},
|
||||
[room, playerId],
|
||||
);
|
||||
|
||||
// Room actions
|
||||
|
||||
async function createRoom(playerName: string, maxPlayers = 16, totalRounds = 3, gameMode: "race" | "all_finish" = "race"): Promise<{ error?: string }> {
|
||||
async function createRoom(
|
||||
playerName: string,
|
||||
maxPlayers = 16,
|
||||
totalRounds = 3,
|
||||
gameMode: "race" | "all_finish" = "race",
|
||||
): Promise<{ error?: string }> {
|
||||
const res = await fetch("/api/rooms", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ playerName, maxPlayers, totalRounds, gameMode }),
|
||||
});
|
||||
const data = await res.json() as { room?: Room; playerId?: string; error?: string };
|
||||
const data = (await res.json()) as {
|
||||
room?: Room;
|
||||
playerId?: string;
|
||||
error?: string;
|
||||
};
|
||||
if (!res.ok) return { error: data.error ?? "Erreur" };
|
||||
setRoom(data.room!); setPlayerId(data.playerId!);
|
||||
setRoom(data.room!);
|
||||
setPlayerId(data.playerId!);
|
||||
startPolling(data.room!.code, data.playerId!);
|
||||
saveSession({ screen: "lobby", multiRoomCode: data.room!.code, multiPlayerId: data.playerId!, playerName });
|
||||
saveSession({
|
||||
screen: "lobby",
|
||||
multiRoomCode: data.room!.code,
|
||||
multiPlayerId: data.playerId!,
|
||||
playerName,
|
||||
});
|
||||
return {};
|
||||
}
|
||||
|
||||
async function joinRoom(playerName: string, code: string): Promise<{ error?: string }> {
|
||||
async function joinRoom(
|
||||
playerName: string,
|
||||
code: string,
|
||||
): Promise<{ error?: string }> {
|
||||
const res = await fetch(`/api/rooms/${code}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "join", playerName }),
|
||||
});
|
||||
const data = await res.json() as { room?: Room; playerId?: string; error?: string };
|
||||
const data = (await res.json()) as {
|
||||
room?: Room;
|
||||
playerId?: string;
|
||||
error?: string;
|
||||
};
|
||||
if (!res.ok) return { error: data.error ?? "Impossible de rejoindre" };
|
||||
setRoom(data.room!); setPlayerId(data.playerId!);
|
||||
setRoom(data.room!);
|
||||
setPlayerId(data.playerId!);
|
||||
startPolling(data.room!.code, data.playerId!);
|
||||
saveSession({ screen: "lobby", multiRoomCode: data.room!.code, multiPlayerId: data.playerId!, playerName });
|
||||
saveSession({
|
||||
screen: "lobby",
|
||||
multiRoomCode: data.room!.code,
|
||||
multiPlayerId: data.playerId!,
|
||||
playerName,
|
||||
});
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -211,9 +283,14 @@ export function useMultiGame() {
|
||||
const res = await fetch(`/api/rooms/${room.code}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "start", playerId, startArticle: puzzle.start, targetArticle: puzzle.target }),
|
||||
body: JSON.stringify({
|
||||
action: "start",
|
||||
playerId,
|
||||
startArticle: puzzle.start,
|
||||
targetArticle: puzzle.target,
|
||||
}),
|
||||
});
|
||||
const data = await res.json() as { room?: Room; error?: string };
|
||||
const data = (await res.json()) as { room?: Room; error?: string };
|
||||
if (!res.ok) return { error: data.error ?? "Erreur" };
|
||||
prefetchArticle(puzzle.start);
|
||||
setRoom(data.room!);
|
||||
@@ -227,7 +304,7 @@ export function useMultiGame() {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "setSearchAllowed", playerId, value }),
|
||||
});
|
||||
if (res.ok) setRoom((await res.json() as { room: Room }).room);
|
||||
if (res.ok) setRoom(((await res.json()) as { room: Room }).room);
|
||||
}
|
||||
|
||||
async function surrender() {
|
||||
@@ -237,7 +314,7 @@ export function useMultiGame() {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "surrender", playerId }),
|
||||
});
|
||||
if (res.ok) setRoom((await res.json() as { room: Room }).room);
|
||||
if (res.ok) setRoom(((await res.json()) as { room: Room }).room);
|
||||
}
|
||||
|
||||
async function nextRound() {
|
||||
@@ -247,7 +324,7 @@ export function useMultiGame() {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "nextRound", playerId }),
|
||||
});
|
||||
if (res.ok) setRoom((await res.json() as { room: Room }).room);
|
||||
if (res.ok) setRoom(((await res.json()) as { room: Room }).room);
|
||||
}
|
||||
|
||||
async function resetGame() {
|
||||
@@ -257,15 +334,21 @@ export function useMultiGame() {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "resetGame", playerId }),
|
||||
});
|
||||
if (res.ok) setRoom((await res.json() as { room: Room }).room);
|
||||
if (res.ok) setRoom(((await res.json()) as { room: Room }).room);
|
||||
}
|
||||
|
||||
function leave() {
|
||||
stopPolling(); stopCountdown(); timer.stop();
|
||||
setRoom(null); setPlayerId(null);
|
||||
setHtml(""); setTitle("");
|
||||
setHistory([]); historyRef.current = [];
|
||||
clicksRef.current = 0; setClicksDisplay(0);
|
||||
stopPolling();
|
||||
stopCountdown();
|
||||
timer.stop();
|
||||
setRoom(null);
|
||||
setPlayerId(null);
|
||||
setHtml("");
|
||||
setTitle("");
|
||||
setHistory([]);
|
||||
historyRef.current = [];
|
||||
clicksRef.current = 0;
|
||||
setClicksDisplay(0);
|
||||
timerStartedRef.current = false;
|
||||
clearSession();
|
||||
}
|
||||
@@ -279,7 +362,7 @@ export function useMultiGame() {
|
||||
body: JSON.stringify({ action: "heartbeat", playerId: pid }),
|
||||
});
|
||||
if (!res.ok) return false;
|
||||
const data = await res.json() as { room: Room };
|
||||
const data = (await res.json()) as { room: Room };
|
||||
setRoom(data.room);
|
||||
setPlayerId(pid);
|
||||
startPolling(code, pid);
|
||||
@@ -290,9 +373,26 @@ export function useMultiGame() {
|
||||
}
|
||||
|
||||
return {
|
||||
room, playerId, html, title, loading, loadError,
|
||||
history, clicks: clicksDisplay, elapsed: timer.elapsed, countdown,
|
||||
createRoom, joinRoom, startGame, nextRound, resetGame, leave, navigate, surrender, setSearchAllowed, restore,
|
||||
room,
|
||||
playerId,
|
||||
html,
|
||||
title,
|
||||
loading,
|
||||
loadError,
|
||||
history,
|
||||
clicks: clicksDisplay,
|
||||
elapsed: timer.elapsed,
|
||||
countdown,
|
||||
createRoom,
|
||||
joinRoom,
|
||||
startGame,
|
||||
nextRound,
|
||||
resetGame,
|
||||
leave,
|
||||
navigate,
|
||||
surrender,
|
||||
setSearchAllowed,
|
||||
restore,
|
||||
retryLoad: () => title && loadArticle(title),
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user