Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { userSelect } from "./slices/userSlice";
import { useDispatch } from "react-redux";
import { lichessTrySetUser } from "./utils/lichess";
import { UnknownAction } from "@reduxjs/toolkit";
import { Toast } from "./components/common";

const App = () => {
const dispatch: Dispatch<UnknownAction> = useDispatch();
Expand All @@ -30,6 +31,7 @@ const App = () => {

return (
<>
<Toast />
{!loading && <Outlet context={modelRefs} />}
</>
);
Expand Down
5 changes: 3 additions & 2 deletions src/components/common/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ import VideoAndSidebar from "./videoAndSidebar";
import StudyButton from "./studyButton";
import FenButton from "./fenButton";
import DeviceButton from "./deviceButton";
import Toast from "./toast";

export {
export {
SidebarButton, CornersButton, PgnButton, Icon, Corners,
HomeButton, Sidebar, Container, VideoAndSidebar, RecordButton, StopButton, StudyButton,
FenButton, DeviceButton,
FenButton, DeviceButton, Toast,
};
59 changes: 59 additions & 0 deletions src/components/common/toast.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Game, gameSelect, gameSetError } from "../../slices/gameSlice";

const Toast = () => {
const game: Game = gameSelect();
const dispatch = useDispatch();
const [visible, setVisible] = useState(false);
const [show, setShow] = useState(false);

const dismiss = () => {
setVisible(false);
setTimeout(() => {
dispatch(gameSetError(null));
setShow(false);
}, 300);
};

useEffect(() => {
if (game.error) {
setShow(true);
setVisible(true);
const timer = setTimeout(dismiss, 3000);
return () => clearTimeout(timer);
}
}, [game.error]);

if (!show || !game.error) return null;

return (
<div
className="position-fixed top-0 end-0 m-3"
style={{ zIndex: 9999 }}
>
<div
className="toast show"
role="alert"
style={{
backgroundColor: "#dc3545",
color: "white",
opacity: visible ? 1 : 0,
transition: "opacity 0.3s ease-in-out",
}}
>
<div className="toast-body d-flex justify-content-between align-items-center">
{game.error}
<button
type="button"
className="btn-close btn-close-white"
onClick={dismiss}
style={{ filter: "invert(1)" }}
/>
</div>
</div>
</div>
);
};

export default Toast;
14 changes: 9 additions & 5 deletions src/components/play/playSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useEffect, useRef, useState } from "react";
import { lichessPlayMove, lichessStreamGame } from "../../utils/lichess";
import { Color } from "chessops/types";
import { useDispatch } from "react-redux";
import { gameSelect, gameUpdate, makeBoard, makeUpdatePayload } from "../../slices/gameSlice";
import { gameSelect, gameUpdate, gameSetError, makeBoard, makeUpdatePayload } from "../../slices/gameSlice";
import GamesButton from "./gamesButton";

const PlaySidebar = ({ piecesModelRef, xcornersModelRef, videoRef, canvasRef, sidebarRef,
Expand All @@ -31,11 +31,15 @@ const PlaySidebar = ({ piecesModelRef, xcornersModelRef, videoRef, canvasRef, si
useEffect(() => {
const colorToMove = gameRef.current.fen.split(" ")[1];
const lastMove = gameRef.current.lastMove;
if ((colorToMove === color) || (lastMove === "") || (gameId === undefined) || (color === undefined)) {
const fromOpponent = gameRef.current.fromOpponent;
if ((colorToMove === color) || (lastMove === "") || (gameId === undefined) || (color === undefined) || fromOpponent) {
return;
}

lichessPlayMove(token, gameId, lastMove);
lichessPlayMove(token, gameId, lastMove)
.catch((err: string) => {
dispatch(gameSetError(err));
});
}, [gameRef.current])

const streamGameCallback = async (response: any) => {
Expand All @@ -51,8 +55,8 @@ const PlaySidebar = ({ piecesModelRef, xcornersModelRef, videoRef, canvasRef, si
}

const board = makeBoard(gameRef.current);
board.move(lastMove);
const payload = makeUpdatePayload(board);
board.playUci(lastMove);
const payload = makeUpdatePayload(board, false, true);
console.log("payload", payload);
dispatch(gameUpdate(payload));
}
Expand Down
59 changes: 41 additions & 18 deletions src/slices/gameSlice.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,19 @@ import { START_FEN } from '../utils/constants';
import { parseFen, makeFen } from 'chessops/fen';
import { Chess } from 'chessops/chess';
import { parsePgn } from 'chessops/pgn';
import { parseSan } from 'chessops/san';
import { makeUci } from 'chessops/util';
import { parseSan, makeSan } from 'chessops/san';
import { makeUci, parseUci, Uci } from 'chessops/util';

type HistoryEntry = { move: Uci; san: string };

const initialState: Game = {
"moves": "",
"fen": START_FEN,
"start": START_FEN,
"lastMove": "",
"greedy": false
"greedy": false,
"fromOpponent": false,
"error": null
};

const gameSlice = createSlice({
Expand Down Expand Up @@ -44,32 +48,36 @@ const gameSlice = createSlice({
gameResetLastMove(state) {
state.lastMove = initialState.lastMove;
},
gameSetError(state, action) {
state.error = action.payload;
},
gameUpdate(state, action) {
const newState: Game = {
"start": state.start,
"moves": action.payload.moves,
"fen": action.payload.fen,
"lastMove": action.payload.lastMove,
"greedy": action.payload.greedy
"greedy": action.payload.greedy,
"fromOpponent": action.payload.fromOpponent ?? false,
"error": action.payload.error ?? null
}
return newState
}
}
})

const getMovesFromPgn = (pos: any, startFen: string) => {
// Simple mainline PGN generator for chessops
const setup = parseFen(startFen).unwrap();
const tempPos = Chess.fromSetup(setup).unwrap();
const history = pos.history || []; // We'll need to attach history to our chessops board objects
const history = pos.history as HistoryEntry[] || [];

let pgn = "";
history.forEach((move: any) => {
history.forEach((entry: HistoryEntry) => {
if (tempPos.turn === 'white') {
pgn += `${tempPos.fullmoves}. `;
}
pgn += `${move.san} `;
tempPos.play(move);
pgn += `${entry.san} `;
tempPos.play(entry.move);
});
return pgn.trim();
}
Expand All @@ -82,19 +90,21 @@ export const makePgn = (game: Game) => {
return `[FEN "${game.start}"]` + "\n \n" + game.moves;
}

export const makeUpdatePayload = (board: any, greedy: boolean = false) => {
const history = board.history || [];
export const makeUpdatePayload = (board: any, greedy: boolean = false, fromOpponent: boolean = false, error: string | null = null) => {
const history = board.history as HistoryEntry[] || [];
const startFen = board.startFen || START_FEN;

const moves = getMovesFromPgn(board, startFen);
const fen = makeFen(board.toSetup());
const lastMove = (history.length === 0) ? "" : makeUci(history[history.length - 1]);
const lastMove = (history.length === 0) ? "" : makeUci(history[history.length - 1].move);

const payload = {
"moves": moves,
"fen": fen,
"lastMove": lastMove,
"greedy": greedy
"greedy": greedy,
"fromOpponent": fromOpponent,
"error": error
}

return payload
Expand All @@ -104,7 +114,7 @@ export const makeBoard = (game: Game): any => {
const setup = parseFen(game.start).unwrap();
const board: any = Chess.fromSetup(setup).unwrap();
board.startFen = game.start;
board.history = [];
board.history = [] as HistoryEntry[];

const updateFromHistory = () => {
const freshSetup = parseFen(board.startFen).unwrap();
Expand All @@ -116,14 +126,26 @@ export const makeBoard = (game: Game): any => {
board.halfmoves = freshBoard.halfmoves;
board.fullmoves = freshBoard.fullmoves;

board.history.forEach((m: any) => board.play(m));
board.history.forEach((entry: HistoryEntry) => board.play(entry.move));
};

board.playSan = (san: string) => {
const move = parseSan(board, san);
if (move) {
(move as any).san = san;
board.history.push(move);
const entry: HistoryEntry = { move: move as Uci, san };
board.history.push(entry);
board.play(move);
return move;
}
return null;
};

board.playUci = (uci: string) => {
const move = parseUci(uci);
if (move) {
const san = makeSan(board, move);
const entry: HistoryEntry = { move, san };
board.history.push(entry);
board.play(move);
return move;
}
Expand All @@ -150,6 +172,7 @@ export const {
gameSetMoves, gameResetMoves,
gameSetFen, gameResetFen,
gameSetStart, gameResetStart,
gameSetLastMove, gameResetLastMove, gameUpdate
gameSetLastMove, gameResetLastMove,
gameUpdate, gameSetError
} = gameSlice.actions
export default gameSlice.reducer
4 changes: 3 additions & 1 deletion src/types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ interface Game {
moves: string,
start: string,
lastMove: string,
greedy: boolean
greedy: boolean,
fromOpponent: boolean,
error: string | null
}

interface User {
Expand Down
4 changes: 3 additions & 1 deletion src/utils/findPieces.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export const getUpdate = (scoresTensor: tf.Tensor2D, squares: number[]) => {

for (let i = 0; i < squares.length; i++) {
const square = squares[i];
if (square == -1) {
if (typeof square !== 'number' || !Number.isInteger(square) || square < 0 || square >= 64) {
continue;
}
for (let j = 0; j < 12; j++) {
Expand Down Expand Up @@ -220,6 +220,7 @@ export const findPieces = (modelRef: any, videoRef: any, canvasRef: any,
boardRef.current.playSan(move);
possibleMoves.clear();
greedyMoveToTime = {};
state = zeros(64, 12);
}
}

Expand All @@ -236,6 +237,7 @@ export const findPieces = (modelRef: any, videoRef: any, canvasRef: any,
if (hasGreedyMove) {
boardRef.current.playSan(move);
greedyMoveToTime = { greedyMove: greedyMoveToTime[move] };
state = zeros(64, 12);
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/utils/lichess.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ const fetchResponse = async (token: string, path: string, options: any = {}) =>
const res: any = await window.fetch(`${lichessHost}${path}`, config);
if (!res.ok) {
const err = `${res.status} ${res.statusText}`;
alert(err);
console.error(err);
throw err;
}
return res;
Expand Down Expand Up @@ -170,7 +170,7 @@ export const lichessPlayMove = (token: string, gameId: string, move: string) =>
const options = {
method: "POST"
}
fetchResponse(token, path, options);
return fetchResponse(token, path, options);
}

export const lichessTrySetUser = async (navigate: NavigateFunction, dispatch: Dispatch<UnknownAction>) => {
Expand Down
2 changes: 1 addition & 1 deletion src/utils/math.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ export const clamp = (x: number, min: number, max: number) => {
}

export const zeros = (rows: number, columns: number) => {
return Array.from(Array(rows), _ => Array(columns).fill(0));
return Array.from({ length: rows }, () => Array(columns).fill(0));
}