Add play-from-position flow

This commit is contained in:
stefan-kp
2025-11-29 08:50:44 +01:00
parent 3e8c16b9c2
commit 4102135acd
5 changed files with 206 additions and 6 deletions
+11 -2
View File
@@ -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(<AnalysisPage />);
render(
<DebugProvider>
<AnalysisPage />
</DebugProvider>
);
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(<AnalysisPage />);
render(
<DebugProvider>
<AnalysisPage />
</DebugProvider>
);
const textarea = screen.getByPlaceholderText(/Paste PGN or FEN here/i);
fireEvent.change(textarea, { target: { value: "invalid" } });
fireEvent.click(screen.getByText(/Start Analysis/i));
+126 -1
View File
@@ -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<Record<number, string>>({});
const [chatSession, setChatSession] = useState<ChatSession | null>(null);
const [showImportModal, setShowImportModal] = useState(false);
const [showPlayModal, setShowPlayModal] = useState(false);
const [playPersonality, setPlayPersonality] = useState<Personality>(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:
<ChevronRight size={20} />
</button>
</div>
<div className="w-full">
<button
onClick={() => {
setPlayColor(orientation);
setShowPlayModal(true);
}}
className="mt-3 inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg shadow hover:bg-blue-700 transition-colors w-full justify-center"
>
<PlayCircle size={18} /> {t.analysis.playFromHere}
</button>
</div>
</div>
</div>
</div>
@@ -597,6 +628,100 @@ INSTRUCTIONS:
language={language}
/>
)}
{/* Play From Position Modal */}
{showPlayModal && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4 py-8">
<div className="bg-white dark:bg-gray-800 rounded-2xl shadow-2xl max-w-2xl w-full p-6 space-y-6 border border-gray-200 dark:border-gray-700">
<div className="flex items-start justify-between gap-4">
<div>
<h3 className="text-2xl font-bold text-gray-900 dark:text-white">{t.analysis.playFromHere}</h3>
<p className="text-sm text-gray-600 dark:text-gray-300 mt-1">{t.analysis.playDescription}</p>
</div>
<button
onClick={() => setShowPlayModal(false)}
className="text-gray-500 hover:text-gray-700 dark:hover:text-gray-200"
aria-label={t.common.close}
>
</button>
</div>
<div className="space-y-4">
<div>
<p className="text-sm font-semibold text-gray-800 dark:text-gray-100 mb-2">{t.analysis.chooseOpponent}</p>
<div className="grid grid-cols-2 gap-2">
{PERSONALITIES.map(p => (
<button
key={p.id}
onClick={() => setPlayPersonality(p)}
className={`p-3 rounded-lg border flex items-center gap-2 ${playPersonality.id === p.id
? "border-blue-500 bg-blue-50 dark:bg-blue-900/30"
: "border-gray-200 dark:border-gray-700"}`}
>
<span className="text-xl">{p.image}</span>
<div className="text-left">
<div className="text-sm font-semibold text-gray-900 dark:text-white">{p.name}</div>
<div className="text-xs text-gray-600 dark:text-gray-300 line-clamp-2">{p.description}</div>
</div>
</button>
))}
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<p className="text-sm font-semibold text-gray-800 dark:text-gray-100">{t.analysis.chooseSide}</p>
<div className="grid grid-cols-2 gap-2">
{(["white", "black"] as const).map(color => (
<button
key={color}
onClick={() => setPlayColor(color)}
className={`py-2 px-3 rounded-lg border text-sm font-medium ${playColor === color
? "border-blue-500 bg-blue-50 dark:bg-blue-900/30"
: "border-gray-200 dark:border-gray-700"}`}
>
{color === "white" ? t.game.white : t.game.black}
</button>
))}
</div>
</div>
<div className="space-y-2">
<p className="text-sm font-semibold text-gray-800 dark:text-gray-100">{t.analysis.chooseStrength}</p>
<div className="bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg p-3">
<div className="text-sm text-gray-700 dark:text-gray-200 mb-1">{t.game.stockfishStrength}: {playStrength}</div>
<input
type="range"
min="1"
max="20"
value={playStrength}
onChange={(e) => setPlayStrength(parseInt(e.target.value))}
className="w-full"
/>
<div className="text-[11px] text-gray-500 dark:text-gray-400 mt-1">{t.game.depth}: {playStrength}</div>
</div>
</div>
</div>
</div>
<div className="flex items-center justify-end gap-3">
<button
onClick={() => setShowPlayModal(false)}
className="px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-700 text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
>
{t.common.cancel}
</button>
<button
onClick={handleStartGameFromPosition}
className="px-4 py-2 rounded-lg bg-blue-600 text-white hover:bg-blue-700 shadow"
>
{t.analysis.startPlay}
</button>
</div>
</div>
</div>
)}
</div>
);
}
+30 -1
View File
@@ -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<SavedGame[]>([]);
@@ -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}
/>
)}
+9 -2
View File
@@ -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<string, number> = {
'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<Stockfish | null>(null);
@@ -55,7 +56,7 @@ export default function ChessGame({ gameId, initialFen, initialPgn, initialPerso
const [computerMove, setComputerMove] = useState<Move | null>(null);
const [isAnalyzing, setIsAnalyzing] = useState(false);
const [apiKey, setApiKey] = useState<string | null>(null);
const [stockfishDepth, setStockfishDepth] = useState(15);
const [stockfishDepth, setStockfishDepth] = useState(initialStockfishDepth ?? 15);
// Settings
const [language, setLanguage] = useState<SupportedLanguage>('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");
+30
View File
@@ -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 ladversaire',
startPlay: 'Commencer ici',
modeTitle: 'Analyser une partie existante',
modeDescription: 'Importez un PGN ou un FEN et laissez le coach commenter chaque coup avec laide 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 lavversario',
chooseSide: 'Scegli il tuo colore',
chooseStrength: 'Forza dellavversario',
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',