diff --git a/assets/js/hooks/chessBoard.js b/assets/js/hooks/chessBoard.js index 4a6ae28..a09f6c8 100644 --- a/assets/js/hooks/chessBoard.js +++ b/assets/js/hooks/chessBoard.js @@ -3,21 +3,41 @@ import { Chess } from 'chess.js'; export const ChessBoard = { mounted() { - this.chess = new Chess(); + this.chess = new Chess(); - this.ground = Chessground(this.el, { - fen: this.chess.fen(), - movable: { - color: 'white', - free: false, - dests: this.getValidDests() - }, - events: { - move: (orig, dest, _metadata) => { - this.handleMove(orig, dest); - } - } - }); + this.ground = Chessground(this.el, { + fen: this.chess.fen(), + movable: { + color: 'white', + free: false, + dests: this.getValidDests() + }, + events: { + move: (orig, dest, _metadata) => { + this.handleMove(orig, dest); + } + } + }); + + this.handleEvent("set_fen", ({ fen }) => { + try { + this.chess.load(fen); + + const currentTurnColor = this.chess.turn() === 'w' ? 'white' : 'black'; + + this.ground.set({ + fen: fen, + turnColor: currentTurnColor, + movable: { + color: currentTurnColor, + dests: this.getValidDests() + } + }); + } catch (error) { + console.error("Invalid FEN string submitted:", error); + alert("Invalid FEN configuration!"); + } + }); }, getValidDests() { diff --git a/lib/chesstrainer_web/live/chess_test_live.ex b/lib/chesstrainer_web/live/chess_test_live.ex index 08fb0fd..9815924 100644 --- a/lib/chesstrainer_web/live/chess_test_live.ex +++ b/lib/chesstrainer_web/live/chess_test_live.ex @@ -12,6 +12,24 @@ defmodule ChesstrainerWeb.ChessTestLive do
Last Played Move:
@@ -40,6 +58,18 @@ defmodule ChesstrainerWeb.ChessTestLive do """ end + @impl true + def handle_event("load_fen", %{"fen" => fen}, socket) do + clean_fen = String.trim(fen) + + {:noreply, + socket + |> assign(:last_move, "Position Loaded") + |> assign(:san, "None yet") + |> assign(:move_list, []) + |> push_event("set_fen", %{fen: clean_fen})} + end + @impl true def handle_event( "move_played",