Add multi-game resume list with board previews
This commit is contained in:
+20
-25
@@ -5,6 +5,7 @@ import { useRouter } from "next/navigation";
|
||||
import ChessGame from "@/components/ChessGame";
|
||||
import StartScreen from "@/components/StartScreen";
|
||||
import { Personality } from "@/lib/personalities";
|
||||
import { SavedGame, deleteSavedGame, loadSavedGames } from "@/lib/savedGames";
|
||||
|
||||
type ViewState = 'start' | 'game';
|
||||
|
||||
@@ -15,13 +16,14 @@ export default function Home() {
|
||||
|
||||
// Game Initialization State
|
||||
const [gameProps, setGameProps] = useState<{
|
||||
gameId: string;
|
||||
initialFen?: string;
|
||||
initialPgn?: string;
|
||||
initialPersonality: Personality;
|
||||
initialColor: 'white' | 'black';
|
||||
} | null>(null);
|
||||
|
||||
const [hasSavedGame, setHasSavedGame] = useState(false);
|
||||
const [savedGames, setSavedGames] = useState<SavedGame[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
// Check for API Key
|
||||
@@ -31,11 +33,7 @@ export default function Home() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check for saved game
|
||||
const savedGame = localStorage.getItem("chess_tutor_save");
|
||||
if (savedGame) {
|
||||
setHasSavedGame(true);
|
||||
}
|
||||
setSavedGames(loadSavedGames());
|
||||
|
||||
setMounted(true);
|
||||
}, [router]);
|
||||
@@ -51,6 +49,7 @@ export default function Home() {
|
||||
: options.color;
|
||||
|
||||
setGameProps({
|
||||
gameId: crypto.randomUUID ? crypto.randomUUID() : `game-${Date.now()}`,
|
||||
initialFen: options.fen,
|
||||
initialPgn: options.pgn,
|
||||
initialPersonality: options.personality,
|
||||
@@ -59,31 +58,25 @@ export default function Home() {
|
||||
setView('game');
|
||||
};
|
||||
|
||||
const handleResumeGame = () => {
|
||||
const savedGame = localStorage.getItem("chess_tutor_save");
|
||||
if (savedGame) {
|
||||
try {
|
||||
const data = JSON.parse(savedGame);
|
||||
if (data.fen && data.selectedPersonality) {
|
||||
const handleResumeGame = (game: SavedGame) => {
|
||||
setGameProps({
|
||||
initialFen: data.fen,
|
||||
initialPgn: data.pgn,
|
||||
initialPersonality: data.selectedPersonality,
|
||||
initialColor: data.playerColor || 'white'
|
||||
gameId: game.id,
|
||||
initialFen: game.fen,
|
||||
initialPgn: game.pgn,
|
||||
initialPersonality: game.selectedPersonality,
|
||||
initialColor: game.playerColor || 'white'
|
||||
});
|
||||
setView('game');
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to resume game:", e);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleBackToMenu = () => {
|
||||
setView('start');
|
||||
// Re-check saved game status as it might have changed
|
||||
const savedGame = localStorage.getItem("chess_tutor_save");
|
||||
setHasSavedGame(!!savedGame);
|
||||
setSavedGames(loadSavedGames());
|
||||
};
|
||||
|
||||
const handleDeleteSavedGame = (id: string) => {
|
||||
deleteSavedGame(id);
|
||||
setSavedGames(loadSavedGames());
|
||||
};
|
||||
|
||||
if (!mounted) return null;
|
||||
@@ -94,11 +87,13 @@ export default function Home() {
|
||||
<StartScreen
|
||||
onStartGame={handleStartGame}
|
||||
onResumeGame={handleResumeGame}
|
||||
hasSavedGame={hasSavedGame}
|
||||
savedGames={savedGames}
|
||||
onDeleteSavedGame={handleDeleteSavedGame}
|
||||
/>
|
||||
)}
|
||||
{view === 'game' && gameProps && (
|
||||
<ChessGame
|
||||
gameId={gameProps.gameId}
|
||||
initialFen={gameProps.initialFen}
|
||||
initialPgn={gameProps.initialPgn}
|
||||
initialPersonality={gameProps.initialPersonality}
|
||||
|
||||
@@ -80,6 +80,7 @@ describe("ChessGame Component", () => {
|
||||
await act(async () => {
|
||||
render(
|
||||
<ChessGame
|
||||
gameId="test-game"
|
||||
initialPersonality={mockPersonality}
|
||||
initialColor="white"
|
||||
onBack={() => {}}
|
||||
@@ -94,6 +95,7 @@ describe("ChessGame Component", () => {
|
||||
const Tutor = require('./Tutor').Tutor;
|
||||
render(
|
||||
<ChessGame
|
||||
gameId="test-game"
|
||||
initialPersonality={mockPersonality}
|
||||
initialColor="white"
|
||||
onBack={() => {}}
|
||||
|
||||
@@ -16,8 +16,10 @@ import { GameOverModal, MoveHistoryItem } from "./GameOverModal";
|
||||
import { Brain, ArrowLeft } from "lucide-react";
|
||||
import { CapturedPieces } from "./CapturedPieces";
|
||||
import { detectMissedTactics, uciToSan, DetectedTactic } from "@/lib/tacticDetection";
|
||||
import { upsertSavedGame } from "@/lib/savedGames";
|
||||
|
||||
interface ChessGameProps {
|
||||
gameId: string;
|
||||
initialFen?: string;
|
||||
initialPgn?: string;
|
||||
initialPersonality: Personality;
|
||||
@@ -34,7 +36,7 @@ const PIECE_VALUES: Record<string, number> = {
|
||||
'k': 0
|
||||
};
|
||||
|
||||
export default function ChessGame({ initialFen, initialPgn, initialPersonality, initialColor, onBack }: ChessGameProps) {
|
||||
export default function ChessGame({ gameId, initialFen, initialPgn, initialPersonality, initialColor, 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);
|
||||
@@ -156,15 +158,24 @@ export default function ChessGame({ initialFen, initialPgn, initialPersonality,
|
||||
// Save Game State on Change
|
||||
useEffect(() => {
|
||||
const saveData = {
|
||||
id: gameId,
|
||||
fen,
|
||||
language,
|
||||
selectedPersonality,
|
||||
apiKey,
|
||||
playerColor, // Save player color too
|
||||
pgn: gameRef.current.pgn()
|
||||
pgn: gameRef.current.pgn(),
|
||||
updatedAt: Date.now(),
|
||||
evaluation: evalP0 ? {
|
||||
score: evalP0.score,
|
||||
mate: evalP0.mate,
|
||||
depth: evalP0.depth
|
||||
} : null
|
||||
};
|
||||
|
||||
upsertSavedGame(saveData);
|
||||
localStorage.setItem("chess_tutor_save", JSON.stringify(saveData));
|
||||
}, [fen, language, selectedPersonality, apiKey, playerColor]);
|
||||
}, [fen, language, selectedPersonality, apiKey, playerColor, gameId, evalP0]);
|
||||
|
||||
// Game Over Detection
|
||||
useEffect(() => {
|
||||
|
||||
+109
-22
@@ -1,13 +1,15 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Settings, ChevronDown, ChevronUp, Brain } from "lucide-react";
|
||||
import { Settings, ChevronDown, ChevronUp, Brain, Trash2 } from "lucide-react";
|
||||
import { Personality, PERSONALITIES } from "@/lib/personalities";
|
||||
import { useTranslation } from "@/lib/i18n/useTranslation";
|
||||
import { SupportedLanguage } from "@/lib/i18n/translations";
|
||||
import { detectChessFormat, ChessFormat } from "@/lib/chessFormatDetector";
|
||||
import Header from "./Header";
|
||||
import { SavedGame } from "@/lib/savedGames";
|
||||
import { Chessboard } from "react-chessboard";
|
||||
|
||||
interface StartScreenProps {
|
||||
onStartGame: (options: {
|
||||
@@ -16,11 +18,12 @@ interface StartScreenProps {
|
||||
fen?: string;
|
||||
pgn?: string;
|
||||
}) => void;
|
||||
onResumeGame: () => void;
|
||||
hasSavedGame: boolean;
|
||||
onResumeGame: (game: SavedGame) => void;
|
||||
savedGames: SavedGame[];
|
||||
onDeleteSavedGame: (id: string) => void;
|
||||
}
|
||||
|
||||
export default function StartScreen({ onStartGame, onResumeGame, hasSavedGame }: StartScreenProps) {
|
||||
export default function StartScreen({ onStartGame, onResumeGame, savedGames, onDeleteSavedGame }: StartScreenProps) {
|
||||
const router = useRouter();
|
||||
const [language, setLanguage] = useState<SupportedLanguage>('en');
|
||||
const [showNewGameOptions, setShowNewGameOptions] = useState(false);
|
||||
@@ -29,6 +32,7 @@ export default function StartScreen({ onStartGame, onResumeGame, hasSavedGame }:
|
||||
const [colorSelection, setColorSelection] = useState<'white' | 'black' | 'random'>('white');
|
||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const hasSavedGames = savedGames.length > 0;
|
||||
|
||||
useEffect(() => {
|
||||
const storedLang = localStorage.getItem("chess_tutor_language");
|
||||
@@ -56,6 +60,37 @@ export default function StartScreen({ onStartGame, onResumeGame, hasSavedGame }:
|
||||
});
|
||||
};
|
||||
|
||||
const sortedSavedGames = useMemo(
|
||||
() => [...savedGames].sort((a, b) => b.updatedAt - a.updatedAt),
|
||||
[savedGames]
|
||||
);
|
||||
|
||||
const formatEvaluation = (game: SavedGame) => {
|
||||
if (!game.evaluation) return t.start.noEvaluation;
|
||||
|
||||
if (game.evaluation.mate !== null && game.evaluation.mate !== undefined) {
|
||||
const movesToMate = Math.abs(game.evaluation.mate);
|
||||
const side = game.evaluation.mate > 0 ? t.game.white : t.game.black;
|
||||
return `${side} #${movesToMate}`;
|
||||
}
|
||||
|
||||
if (typeof game.evaluation.score === 'number') {
|
||||
const score = game.playerColor === 'black'
|
||||
? -(game.evaluation.score || 0)
|
||||
: (game.evaluation.score || 0);
|
||||
const display = (score / 100).toFixed(2);
|
||||
return `${score >= 0 ? '+' : ''}${display}`;
|
||||
}
|
||||
|
||||
return t.start.noEvaluation;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasSavedGames) {
|
||||
setShowNewGameOptions(true);
|
||||
}
|
||||
}, [hasSavedGames]);
|
||||
|
||||
if (!mounted) return null;
|
||||
|
||||
return (
|
||||
@@ -82,32 +117,84 @@ export default function StartScreen({ onStartGame, onResumeGame, hasSavedGame }:
|
||||
{t.start.startGame}
|
||||
</h2>
|
||||
|
||||
<div className="space-y-6">
|
||||
{hasSavedGames && (
|
||||
<div className="space-y-4">
|
||||
{/* Resume Option */}
|
||||
{hasSavedGame && !showNewGameOptions && (
|
||||
<div className="space-y-4">
|
||||
<button
|
||||
onClick={onResumeGame}
|
||||
className="w-full py-5 bg-green-600 text-white rounded-xl hover:bg-green-700 font-bold text-xl shadow-lg transition-transform transform hover:scale-[1.02] flex items-center justify-center gap-3"
|
||||
>
|
||||
<span>▶</span> {t.start.resumeGame}
|
||||
</button>
|
||||
<div className="relative flex py-2 items-center">
|
||||
<div className="flex-grow border-t border-gray-200 dark:border-gray-700"></div>
|
||||
<span className="flex-shrink-0 mx-4 text-gray-400 text-sm">OR</span>
|
||||
<div className="flex-grow border-t border-gray-200 dark:border-gray-700"></div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
|
||||
{t.start.savedGamesTitle}
|
||||
</h3>
|
||||
<button
|
||||
onClick={() => setShowNewGameOptions(true)}
|
||||
className="w-full py-3 bg-white dark:bg-gray-700 border-2 border-gray-200 dark:border-gray-600 text-gray-700 dark:text-gray-200 rounded-xl hover:bg-gray-50 dark:hover:bg-gray-600 font-semibold transition-colors"
|
||||
className="text-sm text-blue-600 dark:text-blue-400 hover:underline"
|
||||
>
|
||||
{t.start.startNewGame}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{sortedSavedGames.length === 0 && (
|
||||
<div className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{t.start.savedGamesEmpty}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{sortedSavedGames.map(game => (
|
||||
<div
|
||||
key={game.id}
|
||||
onClick={() => onResumeGame(game)}
|
||||
className="group relative bg-gray-50 dark:bg-gray-700 p-4 rounded-xl border border-gray-200 dark:border-gray-600 hover:border-blue-400 dark:hover:border-blue-300 shadow-sm hover:shadow-md transition-all cursor-pointer"
|
||||
>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onDeleteSavedGame(game.id);
|
||||
}}
|
||||
aria-label={t.start.deleteGame}
|
||||
className="absolute top-2 right-2 p-2 rounded-full bg-white dark:bg-gray-800 text-gray-500 hover:text-red-600 shadow opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
</button>
|
||||
|
||||
<div className="bg-[#779954] p-[2px] rounded-sm">
|
||||
<Chessboard
|
||||
options={{
|
||||
position: game.fen,
|
||||
boardOrientation: game.playerColor,
|
||||
allowDragging: false,
|
||||
darkSquareStyle: { backgroundColor: '#779954' },
|
||||
lightSquareStyle: { backgroundColor: '#e9edcc' },
|
||||
animationDurationInMs: 150,
|
||||
boardStyle: { width: '100%', aspectRatio: '1' }
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mt-3 flex items-start justify-between gap-2 text-sm">
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-lg">{game.selectedPersonality.image}</span>
|
||||
<div>
|
||||
<div className="font-semibold text-gray-900 dark:text-white">{game.selectedPersonality.name}</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400">
|
||||
{t.start.opponentLabel}: {game.playerColor === 'white' ? t.game.black : t.game.white}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div className="text-xs uppercase text-gray-500 dark:text-gray-400">{t.start.evaluationLabel}</div>
|
||||
<div className="font-semibold text-gray-900 dark:text-white">{formatEvaluation(game)}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* New Game Options */}
|
||||
{(!hasSavedGame || showNewGameOptions) && (
|
||||
{(!hasSavedGames || showNewGameOptions) && (
|
||||
<div className="space-y-8 animate-in fade-in slide-in-from-top-4 duration-300">
|
||||
{/* Color Selection */}
|
||||
<div>
|
||||
@@ -223,7 +310,7 @@ export default function StartScreen({ onStartGame, onResumeGame, hasSavedGame }:
|
||||
)}
|
||||
</div>
|
||||
|
||||
{hasSavedGame && (
|
||||
{hasSavedGames && (
|
||||
<button
|
||||
onClick={() => setShowNewGameOptions(false)}
|
||||
className="w-full py-3 text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 transition-colors"
|
||||
|
||||
@@ -42,6 +42,12 @@ export interface Translations {
|
||||
playAsBlack: string;
|
||||
randomColor: string;
|
||||
analyzeGame: string;
|
||||
savedGamesTitle: string;
|
||||
savedGamesEmpty: string;
|
||||
opponentLabel: string;
|
||||
evaluationLabel: string;
|
||||
noEvaluation: string;
|
||||
deleteGame: string;
|
||||
};
|
||||
|
||||
// Game
|
||||
@@ -157,6 +163,12 @@ const en: Translations = {
|
||||
playAsBlack: 'Play as Black',
|
||||
randomColor: 'Random',
|
||||
analyzeGame: 'Analyze a Game',
|
||||
savedGamesTitle: 'Unfinished games',
|
||||
savedGamesEmpty: 'No unfinished games yet.',
|
||||
opponentLabel: 'Opponent',
|
||||
evaluationLabel: 'Evaluation',
|
||||
noEvaluation: 'No evaluation yet',
|
||||
deleteGame: 'Delete game',
|
||||
},
|
||||
game: {
|
||||
playingAs: 'Playing as',
|
||||
@@ -262,6 +274,12 @@ const de: Translations = {
|
||||
playAsBlack: 'Als Schwarz spielen',
|
||||
randomColor: 'Zufällig',
|
||||
analyzeGame: 'Partie analysieren',
|
||||
savedGamesTitle: 'Unfertige Partien',
|
||||
savedGamesEmpty: 'Keine unfertigen Partien vorhanden.',
|
||||
opponentLabel: 'Gegner',
|
||||
evaluationLabel: 'Bewertung',
|
||||
noEvaluation: 'Keine Bewertung',
|
||||
deleteGame: 'Partie löschen',
|
||||
},
|
||||
game: {
|
||||
playingAs: 'Spielst als',
|
||||
@@ -367,6 +385,12 @@ const fr: Translations = {
|
||||
playAsBlack: 'Jouer Noirs',
|
||||
randomColor: 'Aléatoire',
|
||||
analyzeGame: 'Analyser une partie',
|
||||
savedGamesTitle: 'Parties inachevées',
|
||||
savedGamesEmpty: 'Aucune partie en cours.',
|
||||
opponentLabel: 'Adversaire',
|
||||
evaluationLabel: 'Évaluation',
|
||||
noEvaluation: 'Pas d\'évaluation',
|
||||
deleteGame: 'Supprimer la partie',
|
||||
},
|
||||
game: {
|
||||
playingAs: 'Jouant',
|
||||
@@ -472,6 +496,12 @@ const it: Translations = {
|
||||
playAsBlack: 'Gioca Nero',
|
||||
randomColor: 'Casuale',
|
||||
analyzeGame: 'Analizza una partita',
|
||||
savedGamesTitle: 'Partite non finite',
|
||||
savedGamesEmpty: 'Nessuna partita in corso.',
|
||||
opponentLabel: 'Avversario',
|
||||
evaluationLabel: 'Valutazione',
|
||||
noEvaluation: 'Nessuna valutazione',
|
||||
deleteGame: 'Elimina partita',
|
||||
},
|
||||
game: {
|
||||
playingAs: 'Giocando',
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { Personality } from "./personalities";
|
||||
import { StockfishEvaluation } from "./stockfish";
|
||||
import { SupportedLanguage } from "./i18n/translations";
|
||||
|
||||
export type SavedGame = {
|
||||
id: string;
|
||||
fen: string;
|
||||
pgn?: string;
|
||||
selectedPersonality: Personality;
|
||||
playerColor: "white" | "black";
|
||||
updatedAt: number;
|
||||
evaluation?: Pick<StockfishEvaluation, "score" | "mate" | "depth"> | null;
|
||||
language?: SupportedLanguage;
|
||||
apiKey?: string | null;
|
||||
};
|
||||
|
||||
const STORAGE_KEY = "chess_tutor_saves";
|
||||
const LEGACY_KEY = "chess_tutor_save";
|
||||
|
||||
const parseSavedGames = (): SavedGame[] => {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (!raw) return [];
|
||||
|
||||
try {
|
||||
const data = JSON.parse(raw);
|
||||
if (!Array.isArray(data)) return [];
|
||||
return data.filter(Boolean);
|
||||
} catch (e) {
|
||||
console.error("Failed to parse saved games", e);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
const persistSavedGames = (games: SavedGame[]) => {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(games));
|
||||
};
|
||||
|
||||
const loadLegacySave = (): SavedGame[] => {
|
||||
const legacy = localStorage.getItem(LEGACY_KEY);
|
||||
if (!legacy) return [];
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(legacy);
|
||||
if (parsed && parsed.fen && parsed.selectedPersonality) {
|
||||
const legacyGame: SavedGame = {
|
||||
id: parsed.id || `legacy-${Date.now()}`,
|
||||
fen: parsed.fen,
|
||||
pgn: parsed.pgn,
|
||||
selectedPersonality: parsed.selectedPersonality,
|
||||
playerColor: parsed.playerColor || "white",
|
||||
updatedAt: parsed.updatedAt || Date.now(),
|
||||
evaluation: parsed.evaluation || null,
|
||||
};
|
||||
return [legacyGame];
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to migrate legacy save", e);
|
||||
}
|
||||
|
||||
return [];
|
||||
};
|
||||
|
||||
export const loadSavedGames = (): SavedGame[] => {
|
||||
const existing = parseSavedGames();
|
||||
if (existing.length > 0) {
|
||||
return existing.sort((a, b) => b.updatedAt - a.updatedAt);
|
||||
}
|
||||
|
||||
const legacy = loadLegacySave();
|
||||
if (legacy.length > 0) {
|
||||
persistSavedGames(legacy);
|
||||
localStorage.removeItem(LEGACY_KEY);
|
||||
return legacy.sort((a, b) => b.updatedAt - a.updatedAt);
|
||||
}
|
||||
|
||||
return [];
|
||||
};
|
||||
|
||||
export const upsertSavedGame = (game: SavedGame) => {
|
||||
const games = parseSavedGames();
|
||||
const index = games.findIndex(g => g.id === game.id);
|
||||
const updatedGames = index >= 0
|
||||
? games.map(g => (g.id === game.id ? game : g))
|
||||
: [...games, game];
|
||||
|
||||
persistSavedGames(updatedGames);
|
||||
};
|
||||
|
||||
export const deleteSavedGame = (id: string) => {
|
||||
const games = parseSavedGames().filter(g => g.id !== id);
|
||||
persistSavedGames(games);
|
||||
};
|
||||
Reference in New Issue
Block a user