allow selection of variants as diagrams and pass along as path (#4)

This commit is contained in:
2026-10-19 14:01:46 +02:00
committed by GitHub
parent 6cca16fa25
commit 5096ff76fd
8 changed files with 109 additions and 57 deletions
+1
View File
@@ -12,3 +12,4 @@ dist-ssr
__unconfig*
todos.json
data
.codegraph
+1
View File
@@ -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
+9 -7
View File
@@ -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<IPosition>({
ply: 0,
fen: "",
path: [],
});
const [generatingPdf, setGeneratingPdf] = useState(false);
const fileInputRef = useRef<HTMLInputElement | null>(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 } },
);
};
+86 -47
View File
@@ -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<typeof LichessPgnViewer>;
type HandlePlyChange = ({ ply, fen }: IPosition) => void;
type HandlePlyChange = (position: IPosition) => void;
interface IHandleBoardClick {
viewerRef: RefObject<ViewerRef | null>;
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<ViewerMoveData>;
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<ViewerRef | null>(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<HTMLElement>(".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;
};
+1
View File
@@ -20,6 +20,7 @@ export interface IUserStudyChapter {
export interface IPosition {
ply: number;
fen: string;
path: string[];
}
export interface IHeader {
+3 -1
View File
@@ -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}
/>
+4 -2
View File
@@ -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":
+4
View File
@@ -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];