feat: Move frontend board logic to npm setup

This commit is contained in:
sigmasternchen 2024-10-26 22:53:10 +02:00
parent b658b4493d
commit 450e2450db
3 changed files with 49 additions and 47 deletions

43
js/src/board.js Normal file
View file

@ -0,0 +1,43 @@
const loadBoard = (board) => {
const getSquare = square => board.getElementsByClassName(square)[0];
const clearSelection = () => {
board.classList.remove("moveSelection");
board.querySelectorAll(".source").forEach(element => {
element.classList.remove("source")
});
board.querySelectorAll(".movePossible").forEach(element => {
element.classList.remove("movePossible")
});
};
const enterSelection = (moves) => {
board.classList.add("moveSelection");
for (const move of moves) {
getSquare(move.target).classList.add("movePossible");
getSquare(move.source).classList.add("source");
}
}
const moveSelected = (move) => {
// TODO
};
board.querySelectorAll(".piece.hasMoves").forEach(element => {
element.addEventListener("click", event => {
clearSelection();
const moves = element.getAttribute("data-moves").split(";").map(move => ({
encoded: move,
source: move.split(",")[0].split("-")[2],
target: move.split(",")[1]
}));
enterSelection(moves);
event.stopPropagation();
});
});
board.addEventListener("click", () => {
clearSelection();
});
}
export const loadBoards = () => {
document.querySelectorAll(".board.interactive").forEach(loadBoard);
};

View file

@ -1,3 +1,8 @@
import htmx from 'htmx.org'; import htmx from 'htmx.org';
import {loadBoards} from './board';
window.htmx = htmx; window.htmx = htmx;
window.addEventListener("load", () => {
loadBoards();
});

View file

@ -60,49 +60,3 @@ function getImageForPice(Piece $piece): string {
} }
?> ?>
</div> </div>
<?php
if ($interactive) {
?>
<script>
window.addEventListener("load", () => {
const board = document.getElementById("board<?= $boardId ?>");
const getSquare = square => board.getElementsByClassName(square)[0];
const clearSelection = () => {
board.classList.remove("moveSelection");
board.querySelectorAll(".source").forEach(element => {
element.classList.remove("source")
});
board.querySelectorAll(".movePossible").forEach(element => {
element.classList.remove("movePossible")
});
};
const enterSelection = (moves) => {
board.classList.add("moveSelection");
for (const move of moves) {
getSquare(move.target).classList.add("movePossible");
getSquare(move.source).classList.add("source");
}
}
const moveSelected = (move) => {
// TODO
};
board.querySelectorAll(".piece.hasMoves").forEach(element => {
element.addEventListener("click", event => {
clearSelection();
const moves = element.getAttribute("data-moves").split(";").map(move => ({
encoded: move,
source: move.split(",")[0].split("-")[2],
target: move.split(",")[1]
}));
enterSelection(moves);
event.stopPropagation();
});
});
board.addEventListener("click", () => {
clearSelection();
});
});
</script>
<?php
}