From 4102135acd2935a270b8a92e268c734abedc5e63 Mon Sep 17 00:00:00 2001 From: stefan-kp <65659186+stefan-kp@users.noreply.github.com> Date: Sat, 29 Nov 2025 08:50:44 +0100 Subject: [PATCH 1/2] Add play-from-position flow --- src/app/analysis/__tests__/page.test.tsx | 13 ++- src/app/analysis/page.tsx | 127 ++++++++++++++++++++++- src/app/page.tsx | 31 +++++- src/components/ChessGame.tsx | 11 +- src/lib/i18n/translations.ts | 30 ++++++ 5 files changed, 206 insertions(+), 6 deletions(-) diff --git a/src/app/analysis/__tests__/page.test.tsx b/src/app/analysis/__tests__/page.test.tsx index db43817..19db74c 100644 --- a/src/app/analysis/__tests__/page.test.tsx +++ b/src/app/analysis/__tests__/page.test.tsx @@ -1,4 +1,5 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { DebugProvider } from "@/contexts/DebugContext"; jest.mock("next/navigation", () => ({ useRouter: jest.fn(() => ({ @@ -83,7 +84,11 @@ describe("AnalysisPage", () => { `; const loadGame = () => { - render(); + render( + + + + ); const textarea = screen.getByPlaceholderText(/Paste PGN or FEN here/i); fireEvent.change(textarea, { target: { value: samplePgn } }); fireEvent.click(screen.getByText(/Start Analysis/i)); @@ -125,7 +130,11 @@ describe("AnalysisPage", () => { }); it("shows an error when the notation cannot be parsed", () => { - render(); + render( + + + + ); const textarea = screen.getByPlaceholderText(/Paste PGN or FEN here/i); fireEvent.change(textarea, { target: { value: "invalid" } }); fireEvent.click(screen.getByText(/Start Analysis/i)); diff --git a/src/app/analysis/page.tsx b/src/app/analysis/page.tsx index 2090086..1963fae 100644 --- a/src/app/analysis/page.tsx +++ b/src/app/analysis/page.tsx @@ -3,7 +3,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Chess } from "chess.js"; import { Chessboard } from "react-chessboard"; -import { Brain, ChevronLeft, ChevronRight, Loader2, ArrowLeft, Download } from "lucide-react"; +import { Brain, ChevronLeft, ChevronRight, Loader2, ArrowLeft, Download, PlayCircle } from "lucide-react"; import { useRouter } from "next/navigation"; import Header from "@/components/Header"; @@ -64,6 +64,10 @@ export default function AnalysisPage() { const [comments, setComments] = useState>({}); const [chatSession, setChatSession] = useState(null); const [showImportModal, setShowImportModal] = useState(false); + const [showPlayModal, setShowPlayModal] = useState(false); + const [playPersonality, setPlayPersonality] = useState(PERSONALITIES[0]); + const [playColor, setPlayColor] = useState<"white" | "black">("white"); + const [playStrength, setPlayStrength] = useState(15); useEffect(() => { const storedKey = localStorage.getItem("gemini_api_key"); @@ -72,6 +76,10 @@ export default function AnalysisPage() { if (storedLang) setLanguage(storedLang as SupportedLanguage); }, []); + useEffect(() => { + setPlayPersonality(selectedPersonality); + }, [selectedPersonality]); + useEffect(() => { const sf = new Stockfish(); setStockfish(sf); @@ -218,6 +226,18 @@ IMPORTANT: loadGameFromPgnOrFen(pgn); }; + const handleStartGameFromPosition = () => { + const payload = { + fen: currentFen, + personalityId: playPersonality.id, + color: playColor, + stockfishDepth: playStrength, + }; + + localStorage.setItem("chess_tutor_pending_game", JSON.stringify(payload)); + router.push("/"); + }; + useEffect(() => { if (!stockfish || !currentFen) return; ensureEvaluation(currentFen); @@ -497,6 +517,17 @@ INSTRUCTIONS: +
+ +
@@ -597,6 +628,100 @@ INSTRUCTIONS: language={language} /> )} + + {/* Play From Position Modal */} + {showPlayModal && ( +
+
+
+
+

{t.analysis.playFromHere}

+

{t.analysis.playDescription}

+
+ +
+ +
+
+

{t.analysis.chooseOpponent}

+
+ {PERSONALITIES.map(p => ( + + ))} +
+
+ +
+
+

{t.analysis.chooseSide}

+
+ {(["white", "black"] as const).map(color => ( + + ))} +
+
+ +
+

{t.analysis.chooseStrength}

+
+
{t.game.stockfishStrength}: {playStrength}
+ setPlayStrength(parseInt(e.target.value))} + className="w-full" + /> +
{t.game.depth}: {playStrength}
+
+
+
+
+ +
+ + +
+
+
+ )} ); } diff --git a/src/app/page.tsx b/src/app/page.tsx index 0a28489..44f80d7 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -4,7 +4,7 @@ import { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; import ChessGame from "@/components/ChessGame"; import StartScreen from "@/components/StartScreen"; -import { Personality } from "@/lib/personalities"; +import { Personality, PERSONALITIES } from "@/lib/personalities"; import { SavedGame, deleteSavedGame, loadSavedGames } from "@/lib/savedGames"; type ViewState = 'start' | 'game'; @@ -21,6 +21,7 @@ export default function Home() { initialPgn?: string; initialPersonality: Personality; initialColor: 'white' | 'black'; + initialStockfishDepth?: number; } | null>(null); const [savedGames, setSavedGames] = useState([]); @@ -35,6 +36,33 @@ export default function Home() { setSavedGames(loadSavedGames()); + const pendingGameRaw = localStorage.getItem("chess_tutor_pending_game"); + if (pendingGameRaw) { + try { + const pendingGame = JSON.parse(pendingGameRaw) as { + fen: string; + personalityId: string; + color: 'white' | 'black'; + stockfishDepth?: number; + }; + + const personality = PERSONALITIES.find(p => p.id === pendingGame.personalityId) || PERSONALITIES[0]; + + setGameProps({ + gameId: crypto.randomUUID ? crypto.randomUUID() : `game-${Date.now()}`, + initialFen: pendingGame.fen, + initialPersonality: personality, + initialColor: pendingGame.color, + initialStockfishDepth: pendingGame.stockfishDepth, + }); + setView('game'); + } catch (err) { + console.error("Failed to load pending game", err); + } finally { + localStorage.removeItem("chess_tutor_pending_game"); + } + } + setMounted(true); }, [router]); @@ -98,6 +126,7 @@ export default function Home() { initialPgn={gameProps.initialPgn} initialPersonality={gameProps.initialPersonality} initialColor={gameProps.initialColor} + initialStockfishDepth={gameProps.initialStockfishDepth} onBack={handleBackToMenu} /> )} diff --git a/src/components/ChessGame.tsx b/src/components/ChessGame.tsx index 0932d4d..e795535 100644 --- a/src/components/ChessGame.tsx +++ b/src/components/ChessGame.tsx @@ -24,6 +24,7 @@ interface ChessGameProps { initialPgn?: string; initialPersonality: Personality; initialColor: 'white' | 'black'; + initialStockfishDepth?: number; onBack: () => void; } @@ -36,7 +37,7 @@ const PIECE_VALUES: Record = { 'k': 0 }; -export default function ChessGame({ gameId, initialFen, initialPgn, initialPersonality, initialColor, onBack }: ChessGameProps) { +export default function ChessGame({ gameId, initialFen, initialPgn, initialPersonality, initialColor, initialStockfishDepth, onBack }: ChessGameProps) { const gameRef = useRef(new Chess(initialFen || "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")); const [fen, setFen] = useState(gameRef.current.fen()); const [stockfish, setStockfish] = useState(null); @@ -55,7 +56,7 @@ export default function ChessGame({ gameId, initialFen, initialPgn, initialPerso const [computerMove, setComputerMove] = useState(null); const [isAnalyzing, setIsAnalyzing] = useState(false); const [apiKey, setApiKey] = useState(null); - const [stockfishDepth, setStockfishDepth] = useState(15); + const [stockfishDepth, setStockfishDepth] = useState(initialStockfishDepth ?? 15); // Settings const [language, setLanguage] = useState('en'); @@ -108,6 +109,12 @@ export default function ChessGame({ gameId, initialFen, initialPgn, initialPerso return () => sf.terminate(); }, []); + useEffect(() => { + if (typeof initialStockfishDepth === 'number') { + setStockfishDepth(initialStockfishDepth); + } + }, [initialStockfishDepth]); + // Load Settings & Initial State useEffect(() => { const storedKey = localStorage.getItem("gemini_api_key"); diff --git a/src/lib/i18n/translations.ts b/src/lib/i18n/translations.ts index bf9bec9..97832d5 100644 --- a/src/lib/i18n/translations.ts +++ b/src/lib/i18n/translations.ts @@ -97,6 +97,12 @@ export interface Translations { evaluation: string; bestMove: string; aiAnalysis: string; + playFromHere: string; + playDescription: string; + chooseOpponent: string; + chooseSide: string; + chooseStrength: string; + startPlay: string; modeTitle: string; modeDescription: string; pasteLabel: string; @@ -244,6 +250,12 @@ const en: Translations = { evaluation: 'Evaluation', bestMove: 'Best Move', aiAnalysis: 'AI Analysis', + playFromHere: 'Play from this position', + playDescription: 'Pick a character, side, and engine strength to continue playing from the current move.', + chooseOpponent: 'Choose your opponent', + chooseSide: 'Choose your color', + chooseStrength: 'Opponent strength', + startPlay: 'Start from here', modeTitle: 'Analyze an Existing Game', modeDescription: 'Upload a PGN or FEN and let your coach walk you through every move with engine-backed insights.', pasteLabel: 'PGN or FEN Input', @@ -392,6 +404,12 @@ const de: Translations = { evaluation: 'Bewertung', bestMove: 'Bester Zug', aiAnalysis: 'KI-Analyse', + playFromHere: 'Von dieser Stellung spielen', + playDescription: 'Wähle Charakter, Farbe und Engine-Stärke, um ab dem aktuellen Zug weiterzuspielen.', + chooseOpponent: 'Gegner auswählen', + chooseSide: 'Wähle deine Farbe', + chooseStrength: 'Stärke des Gegners', + startPlay: 'Hier weiterspielen', modeTitle: 'Bestehende Partie analysieren', modeDescription: 'PGN oder FEN hochladen und vom Coach mit Engine-Unterstützung durch die Partie führen lassen.', pasteLabel: 'PGN- oder FEN-Eingabe', @@ -540,6 +558,12 @@ const fr: Translations = { evaluation: 'Évaluation', bestMove: 'Meilleur coup', aiAnalysis: 'Analyse IA', + playFromHere: 'Jouer depuis cette position', + playDescription: 'Choisissez un personnage, une couleur et la force du moteur pour continuer depuis ce coup.', + chooseOpponent: 'Choisir votre adversaire', + chooseSide: 'Choisissez votre couleur', + chooseStrength: 'Force de l’adversaire', + startPlay: 'Commencer ici', modeTitle: 'Analyser une partie existante', modeDescription: 'Importez un PGN ou un FEN et laissez le coach commenter chaque coup avec l’aide du moteur.', pasteLabel: 'Saisie PGN ou FEN', @@ -688,6 +712,12 @@ const it: Translations = { evaluation: 'Valutazione', bestMove: 'Mossa migliore', aiAnalysis: 'Analisi IA', + playFromHere: 'Gioca da questa posizione', + playDescription: 'Scegli personaggio, colore e forza del motore per continuare da questa mossa.', + chooseOpponent: 'Scegli l’avversario', + chooseSide: 'Scegli il tuo colore', + chooseStrength: 'Forza dell’avversario', + startPlay: 'Inizia da qui', modeTitle: 'Analizza una partita esistente', modeDescription: 'Carica un PGN o un FEN e lascia che il coach commenti ogni mossa con il supporto del motore.', pasteLabel: 'Input PGN o FEN', From 0e678e0187a407c5b6c115f946cd42c7e284b4ac Mon Sep 17 00:00:00 2001 From: Stefan Date: Sat, 29 Nov 2025 10:18:23 +0100 Subject: [PATCH 2/2] analysis --- package-lock.json | 20 ++ src/app/analysis/page.tsx | 427 +++++++++++++++++++------------ src/components/OpeningsModal.tsx | 273 ++++++++++++++++++++ src/components/StartScreen.tsx | 38 ++- src/lib/i18n/translations.ts | 35 +++ 5 files changed, 613 insertions(+), 180 deletions(-) create mode 100644 src/components/OpeningsModal.tsx diff --git a/package-lock.json b/package-lock.json index 8cf6b6d..53f4dbf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -112,6 +112,7 @@ "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/code-frame": "^7.27.1", "@babel/generator": "^7.28.5", @@ -699,6 +700,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=18" }, @@ -722,6 +724,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=18" } @@ -743,6 +746,7 @@ "resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz", "integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==", "license": "MIT", + "peer": true, "dependencies": { "@dnd-kit/accessibility": "^3.1.1", "@dnd-kit/utilities": "^3.2.2", @@ -2945,6 +2949,7 @@ "integrity": "sha512-ZsJzA5thDQMSQO788d7IocwwQbI8B5OPzmqNvpf3NY/+MHDAS759Wo0gd2WQeXYt5AAAQjzcrTVC6SKCuYgoCQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "undici-types": "~6.21.0" } @@ -2954,6 +2959,7 @@ "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.6.tgz", "integrity": "sha512-p/jUvulfgU7oKtj6Xpk8cA2Y1xKTtICGpJYeJXz2YVO2UcvjQgeRMLDGfDeqeRW2Ta+0QNFwcc8X3GH8SxZz6w==", "license": "MIT", + "peer": true, "dependencies": { "csstype": "^3.2.2" } @@ -2964,6 +2970,7 @@ "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==", "dev": true, "license": "MIT", + "peer": true, "peerDependencies": { "@types/react": "^19.2.0" } @@ -3051,6 +3058,7 @@ "integrity": "sha512-lJi3PfxVmo0AkEY93ecfN+r8SofEqZNGByvHAI3GBLrvt1Cw6H5k1IM02nSzu0RfUafr2EvFSw0wAsZgubNplQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.47.0", "@typescript-eslint/types": "8.47.0", @@ -3587,6 +3595,7 @@ "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "dev": true, "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -4107,6 +4116,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "baseline-browser-mapping": "^2.8.25", "caniuse-lite": "^1.0.30001754", @@ -5085,6 +5095,7 @@ "integrity": "sha512-BhHmn2yNOFA9H9JmmIVKJmd288g9hrVRDkdoIgRCRuSySRUHH7r/DI6aAXW9T1WwUuY3DFgrcaqB+deURBLR5g==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", @@ -5270,6 +5281,7 @@ "integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@rtsao/scc": "^1.1.0", "array-includes": "^3.1.9", @@ -7080,6 +7092,7 @@ "integrity": "sha512-F26gjC0yWN8uAA5m5Ss8ZQf5nDHWGlN/xWZIh8S5SRbsEKBovwZhxGd6LJlbZYxBgCYOtreSUyb8hpXyGC5O4A==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@jest/core": "30.2.0", "@jest/types": "30.2.0", @@ -8066,6 +8079,7 @@ "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "cssstyle": "^4.2.1", "data-urls": "^5.0.0", @@ -10119,6 +10133,7 @@ "resolved": "https://registry.npmjs.org/react/-/react-19.2.0.tgz", "integrity": "sha512-tmbWg6W31tQLeB5cdIBOicJDJRR2KzXsV7uSK9iNfLWQ5bIZfxuPEHp7M8wiHyHnn0DD1i7w3Zmin0FtkrwoCQ==", "license": "MIT", + "peer": true, "engines": { "node": ">=0.10.0" } @@ -10146,6 +10161,7 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.0.tgz", "integrity": "sha512-UlbRu4cAiGaIewkPyiRGJk0imDN2T3JjieT6spoL2UeSf5od4n5LB/mQ4ejmxhCFT1tYe8IvaFulzynWovsEFQ==", "license": "MIT", + "peer": true, "dependencies": { "scheduler": "^0.27.0" }, @@ -11307,6 +11323,7 @@ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -11498,6 +11515,7 @@ "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@cspotcode/source-map-support": "^0.8.0", "@tsconfig/node10": "^1.0.7", @@ -11688,6 +11706,7 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -12420,6 +12439,7 @@ "integrity": "sha512-JInaHOamG8pt5+Ey8kGmdcAcg3OL9reK8ltczgHTAwNhMys/6ThXHityHxVV2p3fkw/c+MAvBHFVYHFZDmjMCQ==", "dev": true, "license": "MIT", + "peer": true, "funding": { "url": "https://github.com/sponsors/colinhacks" } diff --git a/src/app/analysis/page.tsx b/src/app/analysis/page.tsx index 1963fae..04353b9 100644 --- a/src/app/analysis/page.tsx +++ b/src/app/analysis/page.tsx @@ -3,7 +3,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Chess } from "chess.js"; import { Chessboard } from "react-chessboard"; -import { Brain, ChevronLeft, ChevronRight, Loader2, ArrowLeft, Download, PlayCircle } from "lucide-react"; +import { Brain, ChevronLeft, ChevronRight, Loader2, ArrowLeft, Download, PlayCircle, Upload, RotateCcw } from "lucide-react"; import { useRouter } from "next/navigation"; import Header from "@/components/Header"; @@ -19,6 +19,7 @@ import { ChatSession } from "@google/generative-ai"; import ReactMarkdown from "react-markdown"; import { useDebug } from "@/contexts/DebugContext"; import { GameImportModal } from "@/components/GameImportModal"; +import { OpeningsModal } from "@/components/OpeningsModal"; interface MoveStep { san: string; @@ -65,6 +66,7 @@ export default function AnalysisPage() { const [chatSession, setChatSession] = useState(null); const [showImportModal, setShowImportModal] = useState(false); const [showPlayModal, setShowPlayModal] = useState(false); + const [showOpeningsModal, setShowOpeningsModal] = useState(false); const [playPersonality, setPlayPersonality] = useState(PERSONALITIES[0]); const [playColor, setPlayColor] = useState<"white" | "black">("white"); const [playStrength, setPlayStrength] = useState(15); @@ -74,6 +76,18 @@ export default function AnalysisPage() { const storedLang = localStorage.getItem("chess_tutor_language"); if (storedKey) setApiKey(storedKey); if (storedLang) setLanguage(storedLang as SupportedLanguage); + + // Check for pending analysis from saved game + const pendingAnalysis = localStorage.getItem("chess_tutor_pending_analysis"); + if (pendingAnalysis) { + localStorage.removeItem("chess_tutor_pending_analysis"); + setInput(pendingAnalysis); + setDetectedFormat(detectChessFormat(pendingAnalysis)); + // Load the game after a short delay to ensure stockfish is ready + setTimeout(() => { + loadGameFromPgnOrFen(pendingAnalysis); + }, 100); + } }, []); useEffect(() => { @@ -226,6 +240,19 @@ IMPORTANT: loadGameFromPgnOrFen(pgn); }; + const handleResetAnalysis = () => { + setInput(""); + setDetectedFormat(null); + setSteps([]); + setCurrentIndex(0); + setStepDetails({}); + setComments({}); + setInitialFen(DEFAULT_START); + evaluationCache.current = {}; + setEvaluationVersion(v => v + 1); + setError(null); + }; + const handleStartGameFromPosition = () => { const payload = { fen: currentFen, @@ -400,90 +427,137 @@ INSTRUCTIONS:
-
-
-
-

- {t.analysis.modeTitle} -

-

{t.analysis.modeDescription}

+ {/* Phase 1: Import View - shown when no game is loaded */} + {steps.length === 0 && ( +
+
+
+

+ {t.analysis.modeTitle} +

+

{t.analysis.modeDescription}

+
-
- - + +
+
+ +