mirror of
https://github.com/TheRealOwenRees/chess-scribe-website.git
synced 2026-07-23 09:56:57 +00:00
move the pgn viewer related logic into a hook and type the ref
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
import LichessPgnViewer from "lichess-pgn-viewer";
|
||||
import { useEffect, useRef } from "react";
|
||||
import type { IPosition } from "#/interfaces.ts";
|
||||
|
||||
type ViewerRef = ReturnType<typeof LichessPgnViewer>;
|
||||
|
||||
interface IProps {
|
||||
gamePgn: string;
|
||||
handlePlyChange: ({ ply, fen }: IPosition) => void;
|
||||
}
|
||||
|
||||
export const useLichessPgnViewer = ({ gamePgn, handlePlyChange }: IProps) => {
|
||||
const viewerRef = useRef<ViewerRef | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const element: HTMLElement | null = document.querySelector(".lpv-board");
|
||||
if (!element) return;
|
||||
|
||||
viewerRef.current = LichessPgnViewer(element, {
|
||||
pgn: gamePgn,
|
||||
scrollToMove: false,
|
||||
});
|
||||
|
||||
const boardButtons = document.querySelectorAll(".lpv__controls");
|
||||
const movesList = document.querySelectorAll(".lpv__moves");
|
||||
if (!boardButtons || !movesList) return;
|
||||
|
||||
const clickHandlerDelay = () => {
|
||||
setTimeout(() => handleClick(), 250);
|
||||
};
|
||||
|
||||
// Hack using DOM manipulation
|
||||
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 } = boardEventListener();
|
||||
const fen = viewerRef.current?.curData().fen ?? "";
|
||||
handlePlyChange({ ply, fen });
|
||||
};
|
||||
|
||||
boardButtons.forEach((button) => {
|
||||
button.addEventListener("click", handleClick);
|
||||
button.addEventListener("touchstart", handleClick);
|
||||
});
|
||||
|
||||
movesList.forEach((move) => {
|
||||
move.addEventListener("click", clickHandlerDelay);
|
||||
move.addEventListener("touchstart", clickHandlerDelay);
|
||||
});
|
||||
|
||||
return () => {
|
||||
boardButtons.forEach((button) => {
|
||||
button.removeEventListener("click", handleClick);
|
||||
button.removeEventListener("touchstart", handleClick);
|
||||
});
|
||||
|
||||
movesList.forEach((move) => {
|
||||
move.removeEventListener("click", clickHandlerDelay);
|
||||
move.removeEventListener("touchstart", clickHandlerDelay);
|
||||
});
|
||||
};
|
||||
}, [gamePgn, handlePlyChange]);
|
||||
|
||||
return viewerRef;
|
||||
};
|
||||
Reference in New Issue
Block a user