feat : add board interactions

This commit is contained in:
GuillaumeSD
2024-02-23 04:01:18 +01:00
parent 2af0959e82
commit 814d3ecf09
19 changed files with 458 additions and 107 deletions

View File

@@ -1,42 +1,61 @@
import { Grid } from "@mui/material";
import LoadGameButton from "../loadGame/loadGameButton";
import { useRouter } from "next/router";
import { useEffect } from "react";
import { useCallback, useEffect } from "react";
import { useChessActions } from "@/hooks/useChess";
import { boardAtom, gameAtom } from "./states";
import {
boardAtom,
boardOrientationAtom,
gameAtom,
gameEvalAtom,
} from "./states";
import { useGameDatabase } from "@/hooks/useGameDatabase";
import { useAtomValue, useSetAtom } from "jotai";
import { Chess } from "chess.js";
export default function LoadGame() {
const router = useRouter();
const { gameId } = router.query;
const game = useAtomValue(gameAtom);
const gameActions = useChessActions(gameAtom);
const boardActions = useChessActions(boardAtom);
const { getGame } = useGameDatabase();
const setEval = useSetAtom(gameEvalAtom);
const setBoardOrientation = useSetAtom(boardOrientationAtom);
const resetAndSetGamePgn = useCallback(
(pgn: string) => {
boardActions.reset();
setEval(undefined);
setBoardOrientation(true);
gameActions.setPgn(pgn);
},
[boardActions, gameActions, setEval, setBoardOrientation]
);
useEffect(() => {
const loadGame = async () => {
if (typeof gameId !== "string") return;
const game = await getGame(parseInt(gameId));
if (!game) return;
const gamefromDb = await getGame(parseInt(gameId));
if (!gamefromDb) return;
boardActions.reset();
gameActions.setPgn(game.pgn);
const gamefromDbChess = new Chess();
gamefromDbChess.loadPgn(gamefromDb.pgn);
if (game.history().join() === gamefromDbChess.history().join()) return;
resetAndSetGamePgn(gamefromDb.pgn);
setEval(gamefromDb.eval);
};
loadGame();
}, [gameId]);
}, [gameId, getGame, game, resetAndSetGamePgn, setEval]);
if (!router.isReady || gameId) return null;
return (
<Grid item container xs={12} justifyContent="center" alignItems="center">
<LoadGameButton
setGame={(game) => {
boardActions.reset();
gameActions.setPgn(game.pgn());
}}
/>
<LoadGameButton setGame={(game) => resetAndSetGamePgn(game.pgn())} />
</Grid>
);
}