mirror of
https://github.com/TheRealOwenRees/chess-scribe-website.git
synced 2026-11-18 10:42:06 +00:00
allow selection of variants as diagrams and pass along as path (#4)
This commit is contained in:
@@ -12,3 +12,4 @@ dist-ssr
|
|||||||
__unconfig*
|
__unconfig*
|
||||||
todos.json
|
todos.json
|
||||||
data
|
data
|
||||||
|
.codegraph
|
||||||
@@ -9,5 +9,6 @@
|
|||||||
- checkbox and toggle disabled states
|
- checkbox and toggle disabled states
|
||||||
- react query on for study and chapter load, to allow caching
|
- react query on for study and chapter load, to allow caching
|
||||||
- https://specification.website/checklist/
|
- https://specification.website/checklist/
|
||||||
|
- variations
|
||||||
|
|
||||||
- react query to cache the study and chapters
|
- react query to cache the study and chapters
|
||||||
@@ -12,7 +12,7 @@ import type { IHeader, IPosition } from "#/interfaces.ts";
|
|||||||
import { gameReducer, initialGameState } from "#/reducers/gameReducer.ts";
|
import { gameReducer, initialGameState } from "#/reducers/gameReducer.ts";
|
||||||
import { recordPdfSuccess } from "#/server/pdfMetrics.ts";
|
import { recordPdfSuccess } from "#/server/pdfMetrics.ts";
|
||||||
import { downloadPDF } from "#/utils/pdfUtils.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";
|
import { downloadString } from "#/utils/stringUtils.ts";
|
||||||
|
|
||||||
export const useChessGame = () => {
|
export const useChessGame = () => {
|
||||||
@@ -23,14 +23,15 @@ export const useChessGame = () => {
|
|||||||
const [currentPosition, setCurrentPosition] = useState<IPosition>({
|
const [currentPosition, setCurrentPosition] = useState<IPosition>({
|
||||||
ply: 0,
|
ply: 0,
|
||||||
fen: "",
|
fen: "",
|
||||||
|
path: [],
|
||||||
});
|
});
|
||||||
|
|
||||||
const [generatingPdf, setGeneratingPdf] = useState(false);
|
const [generatingPdf, setGeneratingPdf] = useState(false);
|
||||||
|
|
||||||
const fileInputRef = useRef<HTMLInputElement | null>(null);
|
const fileInputRef = useRef<HTMLInputElement | null>(null);
|
||||||
|
|
||||||
const handlePlyChange = useCallback(({ ply, fen }: IPosition) => {
|
const handlePlyChange = useCallback(({ ply, fen, path }: IPosition) => {
|
||||||
setCurrentPosition({ ply, fen });
|
setCurrentPosition({ ply, fen, path });
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleSavePgn = () => {
|
const handleSavePgn = () => {
|
||||||
@@ -157,14 +158,15 @@ export const useChessGame = () => {
|
|||||||
|
|
||||||
const handleToggleDiagram = () => {
|
const handleToggleDiagram = () => {
|
||||||
if (!gameState.pgn) return;
|
if (!gameState.pgn) return;
|
||||||
const { ply, fen } = currentPosition;
|
const { ply, fen, path } = currentPosition;
|
||||||
if (ply === 0) return;
|
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(
|
gameDispatch(
|
||||||
exists
|
exists
|
||||||
? { type: "DELETE_DIAGRAM", payload: { ply } }
|
? { type: "DELETE_DIAGRAM", payload: { path } }
|
||||||
: { type: "ADD_DIAGRAM", payload: { ply, fen } },
|
: { type: "ADD_DIAGRAM", payload: { ply, fen, path } },
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,27 @@
|
|||||||
import LichessPgnViewer from "lichess-pgn-viewer";
|
import LichessPgnViewer from "lichess-pgn-viewer";
|
||||||
import { type RefObject, useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
import type { IPosition } from "#/interfaces.ts";
|
import type { IPosition } from "#/interfaces.ts";
|
||||||
|
|
||||||
type ViewerRef = ReturnType<typeof LichessPgnViewer>;
|
type ViewerRef = ReturnType<typeof LichessPgnViewer>;
|
||||||
type HandlePlyChange = ({ ply, fen }: IPosition) => void;
|
type HandlePlyChange = (position: IPosition) => void;
|
||||||
|
|
||||||
interface IHandleBoardClick {
|
interface ViewerPath {
|
||||||
viewerRef: RefObject<ViewerRef | null>;
|
empty: () => boolean;
|
||||||
handlePlyChange: HandlePlyChange;
|
init: () => ViewerPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ViewerMoveData {
|
||||||
|
fen: string;
|
||||||
|
ply: number;
|
||||||
|
path: ViewerPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ViewerNode {
|
||||||
|
data?: { san: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ViewerGame {
|
||||||
|
nodeAt: (path: ViewerPath) => ViewerNode | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IProps {
|
interface IProps {
|
||||||
@@ -15,66 +29,91 @@ interface IProps {
|
|||||||
handlePlyChange: HandlePlyChange;
|
handlePlyChange: HandlePlyChange;
|
||||||
}
|
}
|
||||||
|
|
||||||
const getBoardEventData = () => {
|
const getPosition = (viewer: ViewerRef | null): IPosition | null => {
|
||||||
const variationTags = document.querySelector("variation");
|
if (!viewer) return null;
|
||||||
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 handleBoardClick = ({
|
const data = viewer.curData() as unknown as Partial<ViewerMoveData>;
|
||||||
viewerRef,
|
if (typeof data.ply !== "number" || !data.path || !data.fen) return null;
|
||||||
handlePlyChange,
|
|
||||||
}: IHandleBoardClick) => {
|
const game = viewer.game as unknown as ViewerGame;
|
||||||
const { ply } = getBoardEventData();
|
const path: string[] = [];
|
||||||
const fen = viewerRef.current?.curData().fen ?? "";
|
let current = data.path;
|
||||||
handlePlyChange({ ply, fen });
|
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) => {
|
export const useLichessPgnViewer = ({ gamePgn, handlePlyChange }: IProps) => {
|
||||||
const viewerRef = useRef<ViewerRef | null>(null);
|
const viewerRef = useRef<ViewerRef | null>(null);
|
||||||
|
const handlePlyChangeRef = useRef(handlePlyChange);
|
||||||
|
const lastKeyRef = useRef("");
|
||||||
|
handlePlyChangeRef.current = handlePlyChange;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const element: HTMLElement | null = document.querySelector(".lpv-board");
|
const host = document.querySelector<HTMLElement>(".lpv-board");
|
||||||
if (!element) return;
|
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,
|
pgn: gamePgn,
|
||||||
scrollToMove: false,
|
scrollToMove: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
const boardButtons = document.querySelectorAll(".lpv__controls");
|
return () => {
|
||||||
const movesList = document.querySelectorAll(".lpv__moves");
|
host.replaceChildren();
|
||||||
if (!boardButtons || !movesList) return;
|
viewerRef.current = null;
|
||||||
|
};
|
||||||
|
}, [gamePgn]);
|
||||||
|
|
||||||
const handleClick = () => handleBoardClick({ viewerRef, handlePlyChange });
|
useEffect(() => {
|
||||||
const clickHandlerDelay = () => setTimeout(() => handleClick, 250);
|
let timeout = 0;
|
||||||
|
|
||||||
boardButtons.forEach((button) => {
|
const updatePosition = () => {
|
||||||
button.addEventListener("click", handleClick);
|
window.clearTimeout(timeout);
|
||||||
button.addEventListener("touchstart", handleClick);
|
timeout = window.setTimeout(() => {
|
||||||
});
|
const position = getPosition(viewerRef.current);
|
||||||
|
if (!position) return;
|
||||||
|
|
||||||
movesList.forEach((move) => {
|
const key = `${position.ply}|${position.path.join(" ")}`;
|
||||||
move.addEventListener("click", clickHandlerDelay);
|
if (key === lastKeyRef.current) return;
|
||||||
move.addEventListener("touchstart", clickHandlerDelay);
|
|
||||||
});
|
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 () => {
|
return () => {
|
||||||
boardButtons.forEach((button) => {
|
window.clearTimeout(timeout);
|
||||||
button.removeEventListener("click", handleClick);
|
document.removeEventListener("mousedown", handleInteraction);
|
||||||
button.removeEventListener("touchstart", handleClick);
|
document.removeEventListener("touchstart", handleInteraction);
|
||||||
});
|
document.removeEventListener("click", handleInteraction);
|
||||||
|
document.removeEventListener("keyup", handleInteraction);
|
||||||
movesList.forEach((move) => {
|
|
||||||
move.removeEventListener("click", clickHandlerDelay);
|
|
||||||
move.removeEventListener("touchstart", clickHandlerDelay);
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
}, [gamePgn, handlePlyChange]);
|
}, []);
|
||||||
|
|
||||||
return viewerRef;
|
return viewerRef;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ export interface IUserStudyChapter {
|
|||||||
export interface IPosition {
|
export interface IPosition {
|
||||||
ply: number;
|
ply: number;
|
||||||
fen: string;
|
fen: string;
|
||||||
|
path: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IHeader {
|
export interface IHeader {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import SelectStudyChapter from "#/components/SelectStudyChapter.tsx";
|
|||||||
import { useLichessUser } from "#/context/LichessUserContext.tsx";
|
import { useLichessUser } from "#/context/LichessUserContext.tsx";
|
||||||
import { useChessGame } from "#/hooks/useChessGame.ts";
|
import { useChessGame } from "#/hooks/useChessGame.ts";
|
||||||
import { useLichess } from "#/hooks/useLichess.ts";
|
import { useLichess } from "#/hooks/useLichess.ts";
|
||||||
|
import { diagramKey } from "#/utils/pgnUtils.ts";
|
||||||
|
|
||||||
const PgnViewer = lazy(() => import("#/components/PgnViewer.tsx"));
|
const PgnViewer = lazy(() => import("#/components/PgnViewer.tsx"));
|
||||||
|
|
||||||
@@ -100,7 +101,8 @@ const Chessboard = () => {
|
|||||||
type="checkbox"
|
type="checkbox"
|
||||||
className="checkbox-accent"
|
className="checkbox-accent"
|
||||||
checked={gameState.diagrams.some(
|
checked={gameState.diagrams.some(
|
||||||
(d) => d.ply === currentPosition.ply,
|
(d) =>
|
||||||
|
diagramKey(d.path) === diagramKey(currentPosition.path),
|
||||||
)}
|
)}
|
||||||
onChange={handleToggleDiagram}
|
onChange={handleToggleDiagram}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import type { IGameState, IHeader, IPosition } from "#/interfaces.ts";
|
import type { IGameState, IHeader, IPosition } from "#/interfaces.ts";
|
||||||
|
import { diagramKey } from "#/utils/pgnUtils.ts";
|
||||||
|
|
||||||
export type GameAction =
|
export type GameAction =
|
||||||
| { type: "SET_GAME"; payload: { pgn: string; headers: IHeader } }
|
| { type: "SET_GAME"; payload: { pgn: string; headers: IHeader } }
|
||||||
| { type: "CLEAR_GAME" }
|
| { type: "CLEAR_GAME" }
|
||||||
| { type: "SET_HEADERS"; payload: IHeader }
|
| { type: "SET_HEADERS"; payload: IHeader }
|
||||||
| { type: "ADD_DIAGRAM"; payload: IPosition }
|
| { type: "ADD_DIAGRAM"; payload: IPosition }
|
||||||
| { type: "DELETE_DIAGRAM"; payload: { ply: number } }
|
| { type: "DELETE_DIAGRAM"; payload: { path: string[] } }
|
||||||
| { type: "TOGGLE_DIAGRAM_CLOCK" };
|
| { type: "TOGGLE_DIAGRAM_CLOCK" };
|
||||||
|
|
||||||
const defaultHeaderFields = {
|
const defaultHeaderFields = {
|
||||||
@@ -59,7 +60,8 @@ export const gameReducer = (state: IGameState, action: GameAction) => {
|
|||||||
return {
|
return {
|
||||||
...state,
|
...state,
|
||||||
diagrams: state.diagrams.filter(
|
diagrams: state.diagrams.filter(
|
||||||
(diagram: IPosition) => diagram.ply !== action.payload.ply,
|
(diagram: IPosition) =>
|
||||||
|
diagramKey(diagram.path) !== diagramKey(action.payload.path),
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
case "TOGGLE_DIAGRAM_CLOCK":
|
case "TOGGLE_DIAGRAM_CLOCK":
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
import type { IGameState } from "#/interfaces.ts";
|
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) => {
|
export const getHeaders = (pgn: string) => {
|
||||||
const pgnHeader = pgn.split(/\n\n/g)[0];
|
const pgnHeader = pgn.split(/\n\n/g)[0];
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user