feat : mui & state refacto

This commit is contained in:
GuillaumeSD
2024-02-20 05:08:27 +01:00
parent 70518a8bb8
commit 4502651492
31 changed files with 1481 additions and 800 deletions

36
src/hooks/useChess.ts Normal file
View File

@@ -0,0 +1,36 @@
import { Chess } from "chess.js";
import { PrimitiveAtom, useAtom } from "jotai";
export const useChessActions = (chessAtom: PrimitiveAtom<Chess>) => {
const [game, setGame] = useAtom(chessAtom);
const setPgn = (pgn: string) => {
const newGame = new Chess();
newGame.loadPgn(pgn);
setGame(newGame);
};
const reset = () => {
setGame(new Chess());
};
const copyGame = () => {
const newGame = new Chess();
newGame.loadPgn(game.pgn());
return newGame;
};
const move = (move: { from: string; to: string; promotion?: string }) => {
const newGame = copyGame();
newGame.move(move);
setGame(newGame);
};
const undo = () => {
const newGame = copyGame();
newGame.undo();
setGame(newGame);
};
return { setPgn, reset, move, undo };
};

View File

@@ -0,0 +1,29 @@
import { Dispatch, SetStateAction, useEffect, useState } from "react";
type SetValue<T> = Dispatch<SetStateAction<T>>;
export function useLocalStorage<T>(
key: string,
initialValue: T
): [T, SetValue<T>] {
const [storedValue, setStoredValue] = useState<T>(initialValue);
useEffect(() => {
const item = window.localStorage.getItem(key);
if (item) {
setStoredValue(parseJSON<T>(item));
}
}, [key]);
const setValue: SetValue<T> = (value) => {
const newValue = value instanceof Function ? value(storedValue) : value;
window.localStorage.setItem(key, JSON.stringify(newValue));
setStoredValue(newValue);
};
return [storedValue, setValue];
}
function parseJSON<T>(value: string): T {
return value === "undefined" ? undefined : JSON.parse(value);
}