feat : mui & state refacto
This commit is contained in:
36
src/hooks/useChess.ts
Normal file
36
src/hooks/useChess.ts
Normal 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 };
|
||||
};
|
||||
29
src/hooks/useLocalStorage.ts
Normal file
29
src/hooks/useLocalStorage.ts
Normal 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);
|
||||
}
|
||||
Reference in New Issue
Block a user