mirror of
https://github.com/sigmasternchen/php-chess
synced 2025-03-15 07:58:54 +00:00
refactor: Change board handling to HTMX extension to allow reloading
This commit is contained in:
parent
f36fba17d9
commit
a98fb64975
5 changed files with 41 additions and 11 deletions
|
@ -3,11 +3,27 @@
|
|||
require_once '../src/core.php';
|
||||
|
||||
use Game\Game;
|
||||
use Game\Move;
|
||||
|
||||
session_start();
|
||||
|
||||
if (isset($_SESSION["game"])) {
|
||||
$game = $_SESSION["game"];
|
||||
} else {
|
||||
$game = Game::fromStartPosition();
|
||||
$_SESSION["game"] = $game;
|
||||
}
|
||||
|
||||
$content = function() use ($game) {
|
||||
require '../src/View/fragments/game.php';
|
||||
};
|
||||
|
||||
if (isset($_GET["move"])) {
|
||||
$move = Move::fromJS($_REQUEST["move"]);
|
||||
$game->applyInPlace($move);
|
||||
|
||||
$content();
|
||||
} else {
|
||||
require '../src/View/base.php';
|
||||
}
|
||||
|
||||
|
|
|
@ -3,6 +3,7 @@
|
|||
"version": "1.0.0",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"watch": "esbuild ./src/index.js --bundle --outfile=../html/static/bundle.js --watch",
|
||||
"build": "esbuild ./src/index.js --bundle --outfile=../html/static/bundle.js",
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
import htmx from 'htmx.org';
|
||||
|
||||
const loadBoard = (board) => {
|
||||
const boardId = board.getAttribute("data-board");
|
||||
|
@ -46,6 +47,18 @@ const loadBoard = (board) => {
|
|||
});
|
||||
}
|
||||
|
||||
export const loadBoards = () => {
|
||||
document.querySelectorAll(".board.interactive").forEach(loadBoard);
|
||||
};
|
||||
htmx.defineExtension('board', {
|
||||
onEvent : function(name, event) {
|
||||
console.log(name);
|
||||
if (name !== "htmx:afterProcessNode" ||
|
||||
(
|
||||
event?.target?.getAttribute("hx-ext") ??
|
||||
event?.target?.getAttribute("data-hx-ext" ?? "")
|
||||
) !== "board"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
loadBoard(event.target);
|
||||
}
|
||||
})
|
|
@ -1,8 +1,4 @@
|
|||
import htmx from 'htmx.org';
|
||||
import {loadBoards} from './board';
|
||||
import "./board.ext";
|
||||
|
||||
window.htmx = htmx;
|
||||
|
||||
window.addEventListener("load", () => {
|
||||
loadBoards();
|
||||
});
|
|
@ -29,10 +29,14 @@ function getImageForPice(Piece $piece): string {
|
|||
}
|
||||
|
||||
?>
|
||||
<div class="gameinfo">
|
||||
Current Player: <?= $game->getCurrentSide()->name ?><br />
|
||||
Game State: <?= $game->getGameState()->name ?>
|
||||
</div>
|
||||
<div class="board <?= $interactive ? "interactive" : "" ?>" id="board<?= $boardId ?>"
|
||||
data-board="<?= $boardId ?>"
|
||||
<?php if ($interactive) { ?>
|
||||
data-hx-post="/?move" data-hx-trigger="chess-move-<?= $boardId ?> from:body"
|
||||
data-hx-ext="board" data-hx-post="/?move" data-hx-trigger="chess-move-<?= $boardId ?> from:body"
|
||||
<?php } ?>
|
||||
>
|
||||
<?php
|
||||
|
|
Loading…
Reference in a new issue