mirror of
https://github.com/TheRealOwenRees/chess-scribe-website.git
synced 2026-07-23 01:46:57 +00:00
add board listeners
This commit is contained in:
@@ -1,5 +1,4 @@
|
||||
import LichessPgnViewer from "lichess-pgn-viewer";
|
||||
import type PgnViewerType from "lichess-pgn-viewer/pgnViewer";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
interface IProps {
|
||||
@@ -8,7 +7,7 @@ interface IProps {
|
||||
|
||||
const PgnViewer = ({ gamePgn }: IProps) => {
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const viewerRef = useRef<PgnViewerType | null>(null);
|
||||
const viewerRef = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
const element: HTMLElement | null = document.querySelector(".lpv-board");
|
||||
@@ -19,10 +18,56 @@ const PgnViewer = ({ gamePgn }: IProps) => {
|
||||
scrollToMove: false,
|
||||
});
|
||||
|
||||
// BOARD EVENT LISTENERS - MOVE INTO HOOK?
|
||||
const boardButtons = document.querySelectorAll(".lpv__controls");
|
||||
const movesList = document.querySelectorAll(".lpv__moves");
|
||||
if (!boardButtons || !movesList) return;
|
||||
|
||||
const clickHandlerDelay = () => {
|
||||
setTimeout(() => handleClick(), 250);
|
||||
};
|
||||
|
||||
const boardEventListener = () => {
|
||||
const variationTags = document.querySelector("variation");
|
||||
const moves = [...document.querySelectorAll("move")].filter((m) => {
|
||||
if (!variationTags) return m.className !== "empty";
|
||||
return (
|
||||
m.parentNode?.querySelector("variation") && m.className !== "empty"
|
||||
);
|
||||
});
|
||||
const ply = moves.findIndex((m) => m.classList.contains("current")) + 1;
|
||||
return { moves, ply };
|
||||
};
|
||||
|
||||
const handleClick = () => {
|
||||
const { ply, moves } = boardEventListener();
|
||||
console.log(ply, moves);
|
||||
};
|
||||
|
||||
boardButtons.forEach((button) => {
|
||||
button.addEventListener("click", handleClick);
|
||||
button.addEventListener("touchstart", handleClick);
|
||||
});
|
||||
|
||||
movesList.forEach((move) => {
|
||||
move.addEventListener("click", clickHandlerDelay);
|
||||
move.addEventListener("touchstart", clickHandlerDelay);
|
||||
});
|
||||
|
||||
return () => {
|
||||
if (containerRef.current) {
|
||||
containerRef.current = null;
|
||||
}
|
||||
|
||||
boardButtons.forEach((button) => {
|
||||
button.removeEventListener("click", handleClick);
|
||||
button.removeEventListener("touchstart", handleClick);
|
||||
});
|
||||
|
||||
movesList.forEach((move) => {
|
||||
move.removeEventListener("click", clickHandlerDelay);
|
||||
move.removeEventListener("touchstart", clickHandlerDelay);
|
||||
});
|
||||
};
|
||||
}, [gamePgn]);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user