From 5096ff76fdc399fa099d437e36039b06ffa761d3 Mon Sep 17 00:00:00 2001 From: Owen Rees Date: Mon, 19 Oct 2026 14:01:46 +0200 Subject: [PATCH] allow selection of variants as diagrams and pass along as path (#4) --- .gitignore | 1 + TODO | 1 + src/hooks/useChessGame.ts | 16 ++-- src/hooks/useLichessPgnViewer.ts | 133 ++++++++++++++++++++----------- src/interfaces.ts | 1 + src/pages/Chessboard.tsx | 4 +- src/reducers/gameReducer.ts | 6 +- src/utils/pgnUtils.ts | 4 + 8 files changed, 109 insertions(+), 57 deletions(-) diff --git a/.gitignore b/.gitignore index c520d81..009b048 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,4 @@ dist-ssr __unconfig* todos.json data +.codegraph \ No newline at end of file diff --git a/TODO b/TODO index 6b15b09..ec5ecac 100644 --- a/TODO +++ b/TODO @@ -9,5 +9,6 @@ - checkbox and toggle disabled states - react query on for study and chapter load, to allow caching - https://specification.website/checklist/ +- variations - react query to cache the study and chapters \ No newline at end of file diff --git a/src/hooks/useChessGame.ts b/src/hooks/useChessGame.ts index 2b43586..4a03e99 100644 --- a/src/hooks/useChessGame.ts +++ b/src/hooks/useChessGame.ts @@ -12,7 +12,7 @@ import type { IHeader, IPosition } from "#/interfaces.ts"; import { gameReducer, initialGameState } from "#/reducers/gameReducer.ts"; import { recordPdfSuccess } from "#/server/pdfMetrics.ts"; import { downloadPDF } from "#/utils/pdfUtils.ts"; -import { buildPgnString, getHeaders } from "#/utils/pgnUtils.ts"; +import { buildPgnString, diagramKey, getHeaders } from "#/utils/pgnUtils.ts"; import { downloadString } from "#/utils/stringUtils.ts"; export const useChessGame = () => { @@ -23,14 +23,15 @@ export const useChessGame = () => { const [currentPosition, setCurrentPosition] = useState({ ply: 0, fen: "", + path: [], }); const [generatingPdf, setGeneratingPdf] = useState(false); const fileInputRef = useRef(null); - const handlePlyChange = useCallback(({ ply, fen }: IPosition) => { - setCurrentPosition({ ply, fen }); + const handlePlyChange = useCallback(({ ply, fen, path }: IPosition) => { + setCurrentPosition({ ply, fen, path }); }, []); const handleSavePgn = () => { @@ -157,14 +158,15 @@ export const useChessGame = () => { const handleToggleDiagram = () => { if (!gameState.pgn) return; - const { ply, fen } = currentPosition; + const { ply, fen, path } = currentPosition; if (ply === 0) return; - const exists = gameState.diagrams.some((d) => d.ply === ply); + const key = diagramKey(path); + const exists = gameState.diagrams.some((d) => diagramKey(d.path) === key); gameDispatch( exists - ? { type: "DELETE_DIAGRAM", payload: { ply } } - : { type: "ADD_DIAGRAM", payload: { ply, fen } }, + ? { type: "DELETE_DIAGRAM", payload: { path } } + : { type: "ADD_DIAGRAM", payload: { ply, fen, path } }, ); }; diff --git a/src/hooks/useLichessPgnViewer.ts b/src/hooks/useLichessPgnViewer.ts index 3b668e2..1e1c85a 100644 --- a/src/hooks/useLichessPgnViewer.ts +++ b/src/hooks/useLichessPgnViewer.ts @@ -1,13 +1,27 @@ import LichessPgnViewer from "lichess-pgn-viewer"; -import { type RefObject, useEffect, useRef } from "react"; +import { useEffect, useRef } from "react"; import type { IPosition } from "#/interfaces.ts"; type ViewerRef = ReturnType; -type HandlePlyChange = ({ ply, fen }: IPosition) => void; +type HandlePlyChange = (position: IPosition) => void; -interface IHandleBoardClick { - viewerRef: RefObject; - handlePlyChange: HandlePlyChange; +interface ViewerPath { + empty: () => boolean; + init: () => ViewerPath; +} + +interface ViewerMoveData { + fen: string; + ply: number; + path: ViewerPath; +} + +interface ViewerNode { + data?: { san: string }; +} + +interface ViewerGame { + nodeAt: (path: ViewerPath) => ViewerNode | undefined; } interface IProps { @@ -15,66 +29,91 @@ interface IProps { handlePlyChange: HandlePlyChange; } -const getBoardEventData = () => { - 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 getPosition = (viewer: ViewerRef | null): IPosition | null => { + if (!viewer) return null; -const handleBoardClick = ({ - viewerRef, - handlePlyChange, -}: IHandleBoardClick) => { - const { ply } = getBoardEventData(); - const fen = viewerRef.current?.curData().fen ?? ""; - handlePlyChange({ ply, fen }); + const data = viewer.curData() as unknown as Partial; + if (typeof data.ply !== "number" || !data.path || !data.fen) return null; + + const game = viewer.game as unknown as ViewerGame; + const path: string[] = []; + let current = data.path; + while (!current.empty()) { + const node = game.nodeAt(current); + if (node?.data) path.unshift(node.data.san); + current = current.init(); + } + + return { ply: data.ply, fen: data.fen, path }; }; export const useLichessPgnViewer = ({ gamePgn, handlePlyChange }: IProps) => { const viewerRef = useRef(null); + const handlePlyChangeRef = useRef(handlePlyChange); + const lastKeyRef = useRef(""); + handlePlyChangeRef.current = handlePlyChange; useEffect(() => { - const element: HTMLElement | null = document.querySelector(".lpv-board"); - if (!element) return; + const host = document.querySelector(".lpv-board"); + if (!host) return; - viewerRef.current = LichessPgnViewer(element, { + // Mount the viewer into a fresh child so React keeps ownership of the + // host element and the viewer can replace its own root freely. + host.replaceChildren(); + lastKeyRef.current = ""; + + const mount = document.createElement("div"); + host.appendChild(mount); + + viewerRef.current = LichessPgnViewer(mount, { pgn: gamePgn, scrollToMove: false, }); - const boardButtons = document.querySelectorAll(".lpv__controls"); - const movesList = document.querySelectorAll(".lpv__moves"); - if (!boardButtons || !movesList) return; + return () => { + host.replaceChildren(); + viewerRef.current = null; + }; + }, [gamePgn]); - const handleClick = () => handleBoardClick({ viewerRef, handlePlyChange }); - const clickHandlerDelay = () => setTimeout(() => handleClick, 250); + useEffect(() => { + let timeout = 0; - boardButtons.forEach((button) => { - button.addEventListener("click", handleClick); - button.addEventListener("touchstart", handleClick); - }); + const updatePosition = () => { + window.clearTimeout(timeout); + timeout = window.setTimeout(() => { + const position = getPosition(viewerRef.current); + if (!position) return; - movesList.forEach((move) => { - move.addEventListener("click", clickHandlerDelay); - move.addEventListener("touchstart", clickHandlerDelay); - }); + const key = `${position.ply}|${position.path.join(" ")}`; + if (key === lastKeyRef.current) return; + + lastKeyRef.current = key; + handlePlyChangeRef.current(position); + }, 0); + }; + + // Listen at the document level so the handler survives the viewer + // re-rendering its inner DOM (it replaces the moves/controls nodes). + const handleInteraction = (event: Event) => { + const target = event.target; + if (!(target instanceof Element) || !target.closest(".lpv")) return; + updatePosition(); + }; + + document.addEventListener("mousedown", handleInteraction); + document.addEventListener("touchstart", handleInteraction); + document.addEventListener("click", handleInteraction); + document.addEventListener("keyup", handleInteraction); return () => { - boardButtons.forEach((button) => { - button.removeEventListener("click", handleClick); - button.removeEventListener("touchstart", handleClick); - }); - - movesList.forEach((move) => { - move.removeEventListener("click", clickHandlerDelay); - move.removeEventListener("touchstart", clickHandlerDelay); - }); + window.clearTimeout(timeout); + document.removeEventListener("mousedown", handleInteraction); + document.removeEventListener("touchstart", handleInteraction); + document.removeEventListener("click", handleInteraction); + document.removeEventListener("keyup", handleInteraction); }; - }, [gamePgn, handlePlyChange]); + }, []); return viewerRef; }; diff --git a/src/interfaces.ts b/src/interfaces.ts index f1ac15d..1a47dab 100644 --- a/src/interfaces.ts +++ b/src/interfaces.ts @@ -20,6 +20,7 @@ export interface IUserStudyChapter { export interface IPosition { ply: number; fen: string; + path: string[]; } export interface IHeader { diff --git a/src/pages/Chessboard.tsx b/src/pages/Chessboard.tsx index 65ab725..fd4d9c6 100644 --- a/src/pages/Chessboard.tsx +++ b/src/pages/Chessboard.tsx @@ -9,6 +9,7 @@ import SelectStudyChapter from "#/components/SelectStudyChapter.tsx"; import { useLichessUser } from "#/context/LichessUserContext.tsx"; import { useChessGame } from "#/hooks/useChessGame.ts"; import { useLichess } from "#/hooks/useLichess.ts"; +import { diagramKey } from "#/utils/pgnUtils.ts"; const PgnViewer = lazy(() => import("#/components/PgnViewer.tsx")); @@ -100,7 +101,8 @@ const Chessboard = () => { type="checkbox" className="checkbox-accent" checked={gameState.diagrams.some( - (d) => d.ply === currentPosition.ply, + (d) => + diagramKey(d.path) === diagramKey(currentPosition.path), )} onChange={handleToggleDiagram} /> diff --git a/src/reducers/gameReducer.ts b/src/reducers/gameReducer.ts index 755427e..24ea2ea 100644 --- a/src/reducers/gameReducer.ts +++ b/src/reducers/gameReducer.ts @@ -1,11 +1,12 @@ import type { IGameState, IHeader, IPosition } from "#/interfaces.ts"; +import { diagramKey } from "#/utils/pgnUtils.ts"; export type GameAction = | { type: "SET_GAME"; payload: { pgn: string; headers: IHeader } } | { type: "CLEAR_GAME" } | { type: "SET_HEADERS"; payload: IHeader } | { type: "ADD_DIAGRAM"; payload: IPosition } - | { type: "DELETE_DIAGRAM"; payload: { ply: number } } + | { type: "DELETE_DIAGRAM"; payload: { path: string[] } } | { type: "TOGGLE_DIAGRAM_CLOCK" }; const defaultHeaderFields = { @@ -59,7 +60,8 @@ export const gameReducer = (state: IGameState, action: GameAction) => { return { ...state, diagrams: state.diagrams.filter( - (diagram: IPosition) => diagram.ply !== action.payload.ply, + (diagram: IPosition) => + diagramKey(diagram.path) !== diagramKey(action.payload.path), ), }; case "TOGGLE_DIAGRAM_CLOCK": diff --git a/src/utils/pgnUtils.ts b/src/utils/pgnUtils.ts index 7abb9b5..561204e 100644 --- a/src/utils/pgnUtils.ts +++ b/src/utils/pgnUtils.ts @@ -1,5 +1,9 @@ import type { IGameState } from "#/interfaces.ts"; +// A stable identifier for a diagram position: the SAN move sequence from the +// root. This distinguishes mainline and variation positions that share a ply. +export const diagramKey = (path: string[]) => path.join(" "); + export const getHeaders = (pgn: string) => { const pgnHeader = pgn.split(/\n\n/g)[0];