Merge game history feature: Add multi-game save and analysis mode
This commit is contained in:
@@ -0,0 +1,131 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
|
||||
jest.mock("react-chessboard", () => ({
|
||||
Chessboard: ({ position }: { position: string }) => (
|
||||
<div data-testid="chessboard" data-fen={position} />
|
||||
),
|
||||
}));
|
||||
|
||||
jest.mock("@/lib/stockfish", () => {
|
||||
const stockfishInstance = {
|
||||
evaluate: jest.fn(),
|
||||
terminate: jest.fn(),
|
||||
};
|
||||
const Stockfish = jest.fn(() => stockfishInstance);
|
||||
return {
|
||||
__esModule: true,
|
||||
Stockfish,
|
||||
__mock: { stockfishInstance },
|
||||
};
|
||||
});
|
||||
|
||||
jest.mock("@/lib/tacticDetection", () => {
|
||||
const detectMissedTactics = jest.fn();
|
||||
const uciToSan = jest.fn();
|
||||
return {
|
||||
__esModule: true,
|
||||
detectMissedTactics,
|
||||
uciToSan,
|
||||
__mock: { detectMissedTactics, uciToSan },
|
||||
};
|
||||
});
|
||||
|
||||
const { __mock: stockfishMocks } = jest.requireMock("@/lib/stockfish") as {
|
||||
__mock: { stockfishInstance: { evaluate: jest.Mock; terminate: jest.Mock } };
|
||||
};
|
||||
const { __mock: tacticMocks } = jest.requireMock("@/lib/tacticDetection") as {
|
||||
__mock: { detectMissedTactics: jest.Mock; uciToSan: jest.Mock };
|
||||
};
|
||||
|
||||
const evaluateMock = stockfishMocks.stockfishInstance.evaluate;
|
||||
const detectMissedTacticsMock = tacticMocks.detectMissedTactics;
|
||||
const uciToSanMock = tacticMocks.uciToSan;
|
||||
|
||||
import AnalysisPage from "../page";
|
||||
|
||||
describe("AnalysisPage", () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
localStorage.clear();
|
||||
evaluateMock.mockImplementation((fen: string) => {
|
||||
const sideToMove = fen.split(" ")[1];
|
||||
const baseEval = sideToMove === "w" ? 0 : 50;
|
||||
return Promise.resolve({
|
||||
bestMove: "e2e4",
|
||||
ponder: null,
|
||||
score: baseEval,
|
||||
mate: null,
|
||||
depth: 12,
|
||||
});
|
||||
});
|
||||
detectMissedTacticsMock.mockReturnValue([]);
|
||||
uciToSanMock.mockReturnValue("e4");
|
||||
});
|
||||
|
||||
const samplePgn = `
|
||||
[Event "Casual Game"]
|
||||
[Site "Berlin GER"]
|
||||
[Date "1852.??.??"]
|
||||
[Round "?"]
|
||||
[White "Adolf Anderssen"]
|
||||
[Black "Jean Dufresne"]
|
||||
[Result "1-0"]
|
||||
|
||||
1. e4 e5 2. Nf3 Nc6 3. Bb5 a6
|
||||
`;
|
||||
|
||||
const loadGame = () => {
|
||||
render(<AnalysisPage />);
|
||||
const textarea = screen.getByPlaceholderText(/Paste PGN or FEN here/i);
|
||||
fireEvent.change(textarea, { target: { value: samplePgn } });
|
||||
fireEvent.click(screen.getByText(/Start Analysis/i));
|
||||
};
|
||||
|
||||
it("replays PGN moves with engine evaluations", async () => {
|
||||
loadGame();
|
||||
|
||||
fireEvent.click(screen.getByText(/Next Move/i));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Move 1 \/ 6/)).toBeInTheDocument();
|
||||
expect(screen.getByText("+0.50")).toBeInTheDocument();
|
||||
expect(screen.getByText("-0.50")).toBeInTheDocument();
|
||||
expect(screen.getAllByText("e4")[0]).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(detectMissedTacticsMock).toHaveBeenCalled();
|
||||
expect(uciToSanMock).toHaveBeenCalledWith(expect.any(String), "e2e4");
|
||||
});
|
||||
|
||||
it("surfaces detected tactics with material context", async () => {
|
||||
detectMissedTacticsMock.mockReturnValue([
|
||||
{
|
||||
tactic_type: "fork",
|
||||
affected_squares: ["e5"],
|
||||
material_delta: 300,
|
||||
piece_roles: ["white knight"],
|
||||
move: "Nf3",
|
||||
},
|
||||
]);
|
||||
|
||||
loadGame();
|
||||
fireEvent.click(screen.getByText(/Next Move/i));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/fork \(~3.0 pawns\) on e5/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("shows an error when the notation cannot be parsed", () => {
|
||||
render(<AnalysisPage />);
|
||||
const textarea = screen.getByPlaceholderText(/Paste PGN or FEN here/i);
|
||||
fireEvent.change(textarea, { target: { value: "invalid" } });
|
||||
fireEvent.click(screen.getByText(/Start Analysis/i));
|
||||
|
||||
expect(
|
||||
screen.getByText(
|
||||
"Could not load that PGN or FEN. Please check the notation."
|
||||
)
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,459 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Chess } from "chess.js";
|
||||
import { Chessboard } from "react-chessboard";
|
||||
import { Brain, ChevronLeft, ChevronRight, Loader2 } from "lucide-react";
|
||||
|
||||
import Header from "@/components/Header";
|
||||
import { SupportedLanguage } from "@/lib/i18n/translations";
|
||||
import { useTranslation } from "@/lib/i18n/useTranslation";
|
||||
import { Personality, PERSONALITIES } from "@/lib/personalities";
|
||||
import { Stockfish, StockfishEvaluation } from "@/lib/stockfish";
|
||||
import { detectChessFormat, ChessFormat } from "@/lib/chessFormatDetector";
|
||||
import { detectMissedTactics, DetectedTactic, uciToSan } from "@/lib/tacticDetection";
|
||||
import { lookupOpening } from "@/lib/openings";
|
||||
import { getGenAIModel } from "@/lib/gemini";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
|
||||
interface MoveStep {
|
||||
san: string;
|
||||
color: "white" | "black";
|
||||
moveNumber: number;
|
||||
fenBefore: string;
|
||||
fenAfter: string;
|
||||
}
|
||||
|
||||
interface StepDetails {
|
||||
evalBefore?: StockfishEvaluation;
|
||||
evalAfter?: StockfishEvaluation;
|
||||
cpLoss?: number;
|
||||
missedTactics?: DetectedTactic[];
|
||||
bestMoveSan?: string | null;
|
||||
comment?: string;
|
||||
}
|
||||
|
||||
const DEFAULT_START = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
|
||||
|
||||
export default function AnalysisPage() {
|
||||
const [language, setLanguage] = useState<SupportedLanguage>("en");
|
||||
const [apiKey, setApiKey] = useState<string | null>(null);
|
||||
const t = useTranslation(language);
|
||||
|
||||
const [input, setInput] = useState("");
|
||||
const [detectedFormat, setDetectedFormat] = useState<ChessFormat | null>(null);
|
||||
const [selectedPersonality, setSelectedPersonality] = useState<Personality>(PERSONALITIES[0]);
|
||||
const [orientation, setOrientation] = useState<"white" | "black">("white");
|
||||
|
||||
const [initialFen, setInitialFen] = useState<string>(DEFAULT_START);
|
||||
const [steps, setSteps] = useState<MoveStep[]>([]);
|
||||
const [currentIndex, setCurrentIndex] = useState(0); // 0 = starting position
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const [stockfish, setStockfish] = useState<Stockfish | null>(null);
|
||||
const evaluationCache = useRef<Record<string, StockfishEvaluation>>({});
|
||||
const [evaluationVersion, setEvaluationVersion] = useState(0);
|
||||
const [stepDetails, setStepDetails] = useState<Record<number, StepDetails>>({});
|
||||
const [isCommenting, setIsCommenting] = useState(false);
|
||||
const [comments, setComments] = useState<Record<number, string>>({});
|
||||
|
||||
useEffect(() => {
|
||||
const storedKey = localStorage.getItem("gemini_api_key");
|
||||
const storedLang = localStorage.getItem("chess_tutor_language");
|
||||
if (storedKey) setApiKey(storedKey);
|
||||
if (storedLang) setLanguage(storedLang as SupportedLanguage);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const sf = new Stockfish();
|
||||
setStockfish(sf);
|
||||
return () => sf.terminate();
|
||||
}, []);
|
||||
|
||||
const currentFen = useMemo(() => {
|
||||
if (currentIndex === 0) return initialFen;
|
||||
return steps[currentIndex - 1]?.fenAfter || initialFen;
|
||||
}, [currentIndex, steps, initialFen]);
|
||||
|
||||
const openingInfo = useMemo(() => lookupOpening(currentFen), [currentFen]);
|
||||
|
||||
const handleInputChange = (value: string) => {
|
||||
setInput(value);
|
||||
setDetectedFormat(value.trim() ? detectChessFormat(value) : null);
|
||||
};
|
||||
|
||||
const ensureEvaluation = useCallback(async (fen: string) => {
|
||||
if (!stockfish) return null;
|
||||
if (evaluationCache.current[fen]) return evaluationCache.current[fen];
|
||||
const result = await stockfish.evaluate(fen, 14);
|
||||
evaluationCache.current[fen] = result;
|
||||
setEvaluationVersion(v => v + 1);
|
||||
return result;
|
||||
}, [stockfish]);
|
||||
|
||||
const handleLoadGame = () => {
|
||||
const trimmed = input.trim();
|
||||
const format = detectChessFormat(trimmed);
|
||||
|
||||
if (!trimmed || format === "invalid") {
|
||||
setError(t.analysis.importError);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsedGame = new Chess();
|
||||
const nextSteps: MoveStep[] = [];
|
||||
let startFen = DEFAULT_START;
|
||||
|
||||
if (format === "fen") {
|
||||
parsedGame.load(trimmed);
|
||||
startFen = parsedGame.fen();
|
||||
} else {
|
||||
parsedGame.loadPgn(trimmed);
|
||||
const headers = parsedGame.header();
|
||||
if (headers.FEN) {
|
||||
const base = new Chess();
|
||||
base.load(headers.FEN);
|
||||
startFen = base.fen();
|
||||
} else {
|
||||
parsedGame.reset();
|
||||
startFen = parsedGame.fen();
|
||||
}
|
||||
|
||||
const replay = new Chess();
|
||||
replay.load(startFen);
|
||||
const history = new Chess();
|
||||
history.loadPgn(trimmed);
|
||||
history.history({ verbose: true }).forEach((move, idx) => {
|
||||
const before = replay.fen();
|
||||
const applied = replay.move({ from: move.from, to: move.to, promotion: move.promotion || "q" });
|
||||
if (applied) {
|
||||
nextSteps.push({
|
||||
san: applied.san,
|
||||
color: applied.color === "w" ? "white" : "black",
|
||||
moveNumber: Math.floor(idx / 2) + 1,
|
||||
fenBefore: before,
|
||||
fenAfter: replay.fen(),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
evaluationCache.current = {};
|
||||
setEvaluationVersion(v => v + 1);
|
||||
setInitialFen(startFen);
|
||||
setSteps(nextSteps);
|
||||
setCurrentIndex(0);
|
||||
setStepDetails({});
|
||||
setComments({});
|
||||
setError(null);
|
||||
ensureEvaluation(startFen);
|
||||
} catch (e) {
|
||||
console.error("Failed to load game", e);
|
||||
setError(t.analysis.importError);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!stockfish || !currentFen) return;
|
||||
ensureEvaluation(currentFen);
|
||||
const currentStep = steps[currentIndex - 1];
|
||||
if (currentStep) {
|
||||
ensureEvaluation(currentStep.fenBefore);
|
||||
}
|
||||
}, [stockfish, currentFen, steps, currentIndex, ensureEvaluation]);
|
||||
|
||||
useEffect(() => {
|
||||
if (currentIndex === 0) return;
|
||||
const step = steps[currentIndex - 1];
|
||||
if (!step) return;
|
||||
|
||||
const evalBefore = evaluationCache.current[step.fenBefore];
|
||||
const evalAfter = evaluationCache.current[step.fenAfter];
|
||||
if (!evalBefore || !evalAfter) return;
|
||||
|
||||
setStepDetails(prev => {
|
||||
if (prev[currentIndex]?.evalBefore && prev[currentIndex]?.evalAfter) return prev;
|
||||
const cpLoss = step.color === "white"
|
||||
? evalBefore.score - evalAfter.score
|
||||
: evalAfter.score - evalBefore.score;
|
||||
const missedTactics = detectMissedTactics({
|
||||
fen: step.fenBefore,
|
||||
playerColor: step.color,
|
||||
playerMoveSan: step.san,
|
||||
bestMoveUci: evalBefore.bestMove,
|
||||
cpLoss,
|
||||
});
|
||||
const bestMoveSan = uciToSan(step.fenBefore, evalBefore.bestMove);
|
||||
return {
|
||||
...prev,
|
||||
[currentIndex]: {
|
||||
evalBefore,
|
||||
evalAfter,
|
||||
cpLoss,
|
||||
missedTactics,
|
||||
bestMoveSan,
|
||||
}
|
||||
};
|
||||
});
|
||||
}, [currentIndex, steps, evaluationVersion]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!apiKey) return;
|
||||
if (currentIndex === 0) return;
|
||||
const step = steps[currentIndex - 1];
|
||||
const details = stepDetails[currentIndex];
|
||||
if (!step || !details?.evalBefore || !details?.evalAfter) return;
|
||||
if (comments[currentIndex]) return;
|
||||
|
||||
let cancelled = false;
|
||||
setIsCommenting(true);
|
||||
const timeout = setTimeout(async () => {
|
||||
try {
|
||||
const model = getGenAIModel(apiKey, "gemini-2.5-flash");
|
||||
const delta = details.cpLoss ?? 0;
|
||||
const evalBefore = details.evalBefore.score / 100;
|
||||
const evalAfter = details.evalAfter.score / 100;
|
||||
const mateInfo = details.evalAfter.mate !== null ? `Mate in ${details.evalAfter.mate}` : "No mate detected";
|
||||
const tactics = (details.missedTactics || [])
|
||||
.filter(t => t.tactic_type !== "none")
|
||||
.map(t => `${t.tactic_type}${t.material_delta ? ` (~${(t.material_delta / 100).toFixed(1)} pawns)` : ""}`)
|
||||
.join("; ") || "None";
|
||||
|
||||
const prompt = `
|
||||
You are ${selectedPersonality.name}. Stay in character.
|
||||
Language: ${language.toUpperCase()}.
|
||||
Explain the move that was just played.
|
||||
|
||||
DATA:
|
||||
- Move number: ${step.moveNumber}
|
||||
- Side to move: ${step.color}
|
||||
- Move played (SAN): ${step.san}
|
||||
- Evaluation before move: ${evalBefore.toFixed(2)} pawns
|
||||
- Evaluation after move: ${evalAfter.toFixed(2)} pawns
|
||||
- Best move suggestion: ${details.bestMoveSan ?? details.evalBefore.bestMove}
|
||||
- Evaluation shift (centipawns): ${delta}
|
||||
- Opening context: ${openingInfo ? `${openingInfo.name} (${openingInfo.eco})` : "Unknown"}
|
||||
- Missed tactics: ${tactics}
|
||||
- Mate hint: ${mateInfo}
|
||||
|
||||
INSTRUCTIONS:
|
||||
- Be concise (3-4 sentences).
|
||||
- Mention whether the move improved or worsened the position and why.
|
||||
- Highlight any tactical ideas the player may have missed.
|
||||
- Refer to the player's side as ${step.color}.
|
||||
- Keep it educational and stay true to your personality tone.`;
|
||||
|
||||
const result = await model.generateContent(prompt);
|
||||
if (!cancelled) {
|
||||
setComments(prev => ({ ...prev, [currentIndex]: result.response.text() }));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Commentary failed", err);
|
||||
} finally {
|
||||
if (!cancelled) setIsCommenting(false);
|
||||
}
|
||||
}, 400);
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
clearTimeout(timeout);
|
||||
};
|
||||
}, [apiKey, currentIndex, stepDetails, steps, comments, selectedPersonality, language, openingInfo]);
|
||||
|
||||
const formatEval = (evaluation?: StockfishEvaluation) => {
|
||||
if (!evaluation) return t.analysis.enginePending;
|
||||
if (evaluation.mate !== null) return `#${evaluation.mate}`;
|
||||
return `${evaluation.score >= 0 ? "+" : ""}${(evaluation.score / 100).toFixed(2)}`;
|
||||
};
|
||||
|
||||
const formatCpLoss = (cp?: number) => {
|
||||
if (cp === undefined) return t.analysis.enginePending;
|
||||
const pawns = (cp / 100).toFixed(2);
|
||||
return `${cp > 0 ? "+" : ""}${pawns}`;
|
||||
};
|
||||
|
||||
const currentDetails = currentIndex > 0 ? stepDetails[currentIndex] : undefined;
|
||||
const tacticSummary = (currentDetails?.missedTactics || []).filter(t => t.tactic_type !== "none");
|
||||
|
||||
return (
|
||||
<div className="flex flex-col min-h-screen bg-gray-100 dark:bg-gray-900">
|
||||
<Header language={language} />
|
||||
<main className="flex-grow w-full flex justify-center px-4 py-8">
|
||||
<div className="w-full max-w-6xl space-y-8">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-2xl shadow-lg p-6 md:p-8 border border-gray-200 dark:border-gray-700">
|
||||
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<Brain className="text-purple-600" /> {t.analysis.modeTitle}
|
||||
</h1>
|
||||
<p className="text-gray-600 dark:text-gray-300 mt-2">{t.analysis.modeDescription}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<label className="text-sm font-medium text-gray-700 dark:text-gray-300">{t.analysis.orientation}</label>
|
||||
<select
|
||||
value={orientation}
|
||||
onChange={(e) => setOrientation(e.target.value as "white" | "black")}
|
||||
className="p-2 rounded-lg border border-gray-300 dark:border-gray-600 dark:bg-gray-700"
|
||||
>
|
||||
<option value="white">White</option>
|
||||
<option value="black">Black</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div className="space-y-4">
|
||||
<label className="block text-sm font-semibold text-gray-700 dark:text-gray-300">{t.analysis.pasteLabel}</label>
|
||||
<textarea
|
||||
value={input}
|
||||
onChange={(e) => handleInputChange(e.target.value)}
|
||||
placeholder={t.analysis.pastePlaceholder}
|
||||
className="w-full p-3 border rounded-lg dark:bg-gray-700 dark:border-gray-600 font-mono text-sm min-h-[180px]"
|
||||
/>
|
||||
{detectedFormat && (
|
||||
<p className="text-xs text-gray-500">Detected: {detectedFormat.toUpperCase()}</p>
|
||||
)}
|
||||
{error && <p className="text-sm text-red-500">{error}</p>}
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-semibold text-gray-700 dark:text-gray-300">{t.analysis.chooseCoach}</p>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{PERSONALITIES.map(p => (
|
||||
<button
|
||||
key={p.id}
|
||||
onClick={() => setSelectedPersonality(p)}
|
||||
className={`p-3 rounded-lg border flex items-center gap-2 ${selectedPersonality.id === p.id
|
||||
? "border-purple-500 bg-purple-50 dark:bg-purple-900/20"
|
||||
: "border-gray-200 dark:border-gray-700"}`}
|
||||
>
|
||||
<span className="text-xl">{p.image}</span>
|
||||
<span className="text-sm text-left text-gray-800 dark:text-gray-100">{p.name}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleLoadGame}
|
||||
className="w-full py-3 bg-purple-600 text-white rounded-xl hover:bg-purple-700 font-semibold shadow-lg"
|
||||
>
|
||||
{t.analysis.startButton}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-50 dark:bg-gray-900 rounded-xl p-4 flex flex-col items-center gap-3 border border-gray-200 dark:border-gray-700">
|
||||
<Chessboard
|
||||
position={currentFen}
|
||||
boardOrientation={orientation}
|
||||
arePiecesDraggable={false}
|
||||
customBoardStyle={{ borderRadius: "12px", boxShadow: "0 8px 30px rgba(0,0,0,0.12)" }}
|
||||
/>
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
onClick={() => setCurrentIndex(i => Math.max(0, i - 1))}
|
||||
className="px-3 py-2 rounded-lg bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50"
|
||||
disabled={currentIndex === 0}
|
||||
>
|
||||
<ChevronLeft /> {t.analysis.previous}
|
||||
</button>
|
||||
<div className="text-sm text-gray-600 dark:text-gray-300">
|
||||
{t.analysis.step} {currentIndex} / {steps.length}
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setCurrentIndex(i => Math.min(steps.length, i + 1))}
|
||||
className="px-3 py-2 rounded-lg bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50"
|
||||
disabled={currentIndex >= steps.length}
|
||||
>
|
||||
{t.analysis.next} <ChevronRight />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
<div className="lg:col-span-2 bg-white dark:bg-gray-800 rounded-2xl shadow border border-gray-200 dark:border-gray-700 p-6 space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-xl font-bold text-gray-900 dark:text-white">{t.analysis.title}</h2>
|
||||
{openingInfo && (
|
||||
<span className="text-sm text-blue-700 dark:text-blue-300">
|
||||
{t.analysis.opening}: {openingInfo.name} ({openingInfo.eco})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{currentIndex === 0 ? (
|
||||
<p className="text-gray-600 dark:text-gray-300">{t.analysis.currentPosition}</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap gap-4 text-sm text-gray-700 dark:text-gray-200">
|
||||
<div>
|
||||
<div className="font-semibold">{t.analysis.step} {currentIndex}</div>
|
||||
<div>{steps[currentIndex - 1]?.san}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-semibold">{t.analysis.evaluation}</div>
|
||||
<div>{formatEval(currentDetails?.evalAfter)}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-semibold">{t.analysis.cpLoss}</div>
|
||||
<div>{formatCpLoss(currentDetails?.cpLoss)}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-semibold">{t.analysis.bestMove}</div>
|
||||
<div>{currentDetails?.bestMoveSan || t.analysis.enginePending}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="font-semibold text-gray-800 dark:text-gray-100 mb-2">{t.analysis.missedTactics}</div>
|
||||
{tacticSummary.length === 0 && (
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">{t.analysis.none}</p>
|
||||
)}
|
||||
{tacticSummary.length > 0 && (
|
||||
<ul className="list-disc pl-5 space-y-1 text-sm text-gray-700 dark:text-gray-300">
|
||||
{tacticSummary.map((tactic, idx) => (
|
||||
<li key={`${tactic.move}-${idx}`}>
|
||||
{tactic.tactic_type}
|
||||
{tactic.material_delta ? ` (~${(tactic.material_delta / 100).toFixed(1)} pawns)` : ""}
|
||||
{tactic.affected_squares ? ` on ${tactic.affected_squares.join(", ")}` : ""}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="bg-white dark:bg-gray-800 rounded-2xl shadow border border-gray-200 dark:border-gray-700 p-6 space-y-4">
|
||||
<h2 className="text-xl font-bold text-gray-900 dark:text-white">{t.analysis.aiAnalysis}</h2>
|
||||
{!apiKey && (
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">Please add an API key in settings to receive commentary.</p>
|
||||
)}
|
||||
{currentIndex === 0 && (
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">{t.analysis.currentPosition}</p>
|
||||
)}
|
||||
{currentIndex > 0 && (
|
||||
<div className="min-h-[140px]">
|
||||
{isCommenting && (
|
||||
<div className="flex items-center gap-2 text-gray-600 dark:text-gray-300">
|
||||
<Loader2 className="animate-spin" size={18} />
|
||||
<span>{t.analysis.coachPending}</span>
|
||||
</div>
|
||||
)}
|
||||
{!isCommenting && comments[currentIndex] && (
|
||||
<div className="prose prose-sm dark:prose-invert max-w-none">
|
||||
<ReactMarkdown>{comments[currentIndex]}</ReactMarkdown>
|
||||
</div>
|
||||
)}
|
||||
{!isCommenting && !comments[currentIndex] && (
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">{t.analysis.coachPending}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+23
-28
@@ -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) {
|
||||
setGameProps({
|
||||
initialFen: data.fen,
|
||||
initialPgn: data.pgn,
|
||||
initialPersonality: data.selectedPersonality,
|
||||
initialColor: data.playerColor || 'white'
|
||||
});
|
||||
setView('game');
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to resume game:", e);
|
||||
}
|
||||
}
|
||||
const handleResumeGame = (game: SavedGame) => {
|
||||
setGameProps({
|
||||
gameId: game.id,
|
||||
initialFen: game.fen,
|
||||
initialPgn: game.pgn,
|
||||
initialPersonality: game.selectedPersonality,
|
||||
initialColor: game.playerColor || 'white'
|
||||
});
|
||||
setView('game');
|
||||
};
|
||||
|
||||
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(() => {
|
||||
|
||||
+126
-26
@@ -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 } 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-4">
|
||||
{/* Resume Option */}
|
||||
{hasSavedGame && !showNewGameOptions && (
|
||||
<div className="space-y-6">
|
||||
{hasSavedGames && (
|
||||
<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 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="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>
|
||||
<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"
|
||||
>
|
||||
{t.start.startNewGame}
|
||||
</button>
|
||||
</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"
|
||||
@@ -232,6 +319,19 @@ export default function StartScreen({ onStartGame, onResumeGame, hasSavedGame }:
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="border-t border-gray-200 dark:border-gray-700 pt-6">
|
||||
<p className="text-sm font-bold text-gray-700 dark:text-gray-300 mb-3 uppercase tracking-wide">
|
||||
{t.start.analyzeGame}
|
||||
</p>
|
||||
<button
|
||||
onClick={() => router.push("/analysis")}
|
||||
className="w-full py-4 px-4 bg-purple-600 text-white rounded-xl hover:bg-purple-700 font-semibold shadow-lg transition-transform transform hover:scale-[1.02] flex items-center justify-center gap-2"
|
||||
>
|
||||
<Brain size={18} />
|
||||
{t.start.analyzeGame}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -41,6 +41,13 @@ export interface Translations {
|
||||
playAsWhite: string;
|
||||
playAsBlack: string;
|
||||
randomColor: string;
|
||||
analyzeGame: string;
|
||||
savedGamesTitle: string;
|
||||
savedGamesEmpty: string;
|
||||
opponentLabel: string;
|
||||
evaluationLabel: string;
|
||||
noEvaluation: string;
|
||||
deleteGame: string;
|
||||
};
|
||||
|
||||
// Game
|
||||
@@ -90,6 +97,23 @@ export interface Translations {
|
||||
evaluation: string;
|
||||
bestMove: string;
|
||||
aiAnalysis: string;
|
||||
modeTitle: string;
|
||||
modeDescription: string;
|
||||
pasteLabel: string;
|
||||
pastePlaceholder: string;
|
||||
chooseCoach: string;
|
||||
orientation: string;
|
||||
startButton: string;
|
||||
next: string;
|
||||
previous: string;
|
||||
step: string;
|
||||
missedTactics: string;
|
||||
cpLoss: string;
|
||||
none: string;
|
||||
opening: string;
|
||||
enginePending: string;
|
||||
coachPending: string;
|
||||
importError: string;
|
||||
};
|
||||
|
||||
// API Key Input
|
||||
@@ -172,6 +196,13 @@ const en: Translations = {
|
||||
playAsWhite: 'Play as White',
|
||||
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',
|
||||
@@ -213,6 +244,23 @@ const en: Translations = {
|
||||
evaluation: 'Evaluation',
|
||||
bestMove: 'Best Move',
|
||||
aiAnalysis: 'AI Analysis',
|
||||
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',
|
||||
pastePlaceholder: 'Paste PGN or FEN here to review the game move by move...',
|
||||
chooseCoach: 'Choose Coach Personality',
|
||||
orientation: 'Board Orientation',
|
||||
startButton: 'Start Analysis',
|
||||
next: 'Next Move',
|
||||
previous: 'Previous Move',
|
||||
step: 'Move',
|
||||
missedTactics: 'Missed Tactics',
|
||||
cpLoss: 'Evaluation Change',
|
||||
none: 'None detected',
|
||||
opening: 'Opening',
|
||||
enginePending: 'Running engine evaluation...',
|
||||
coachPending: 'Coach is preparing feedback...',
|
||||
importError: 'Could not load that PGN or FEN. Please check the notation.',
|
||||
},
|
||||
apiKeyInput: {
|
||||
title: 'API Key Required',
|
||||
@@ -296,6 +344,13 @@ const de: Translations = {
|
||||
playAsWhite: 'Als Weiß spielen',
|
||||
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',
|
||||
@@ -337,6 +392,23 @@ const de: Translations = {
|
||||
evaluation: 'Bewertung',
|
||||
bestMove: 'Bester Zug',
|
||||
aiAnalysis: 'KI-Analyse',
|
||||
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',
|
||||
pastePlaceholder: 'PGN oder FEN hier einfügen, um die Partie Zug für Zug anzusehen...',
|
||||
chooseCoach: 'Coach-Persönlichkeit wählen',
|
||||
orientation: 'Brettausrichtung',
|
||||
startButton: 'Analyse starten',
|
||||
next: 'Nächster Zug',
|
||||
previous: 'Vorheriger Zug',
|
||||
step: 'Zug',
|
||||
missedTactics: 'Verpasste Taktiken',
|
||||
cpLoss: 'Bewertungsänderung',
|
||||
none: 'Keine erkannt',
|
||||
opening: 'Eröffnung',
|
||||
enginePending: 'Engine-Bewertung läuft...',
|
||||
coachPending: 'Coach bereitet Feedback vor...',
|
||||
importError: 'PGN oder FEN konnte nicht geladen werden. Bitte Notation prüfen.',
|
||||
},
|
||||
apiKeyInput: {
|
||||
title: 'API-Schlüssel erforderlich',
|
||||
@@ -420,6 +492,13 @@ const fr: Translations = {
|
||||
playAsWhite: 'Jouer Blancs',
|
||||
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',
|
||||
@@ -461,6 +540,23 @@ const fr: Translations = {
|
||||
evaluation: 'Évaluation',
|
||||
bestMove: 'Meilleur coup',
|
||||
aiAnalysis: 'Analyse IA',
|
||||
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',
|
||||
pastePlaceholder: 'Collez ici un PGN ou un FEN pour revoir la partie coup par coup...',
|
||||
chooseCoach: 'Choisir la personnalité du coach',
|
||||
orientation: 'Orientation de l’échiquier',
|
||||
startButton: 'Lancer l’analyse',
|
||||
next: 'Coup suivant',
|
||||
previous: 'Coup précédent',
|
||||
step: 'Coup',
|
||||
missedTactics: 'Tactiques manquées',
|
||||
cpLoss: 'Changement d’évaluation',
|
||||
none: 'Aucune détectée',
|
||||
opening: 'Ouverture',
|
||||
enginePending: 'Évaluation du moteur en cours...',
|
||||
coachPending: 'Le coach prépare son retour...',
|
||||
importError: 'Impossible de charger ce PGN ou FEN. Merci de vérifier la notation.',
|
||||
},
|
||||
apiKeyInput: {
|
||||
title: 'Clé API requise',
|
||||
@@ -544,6 +640,13 @@ const it: Translations = {
|
||||
playAsWhite: 'Gioca Bianco',
|
||||
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',
|
||||
@@ -585,6 +688,23 @@ const it: Translations = {
|
||||
evaluation: 'Valutazione',
|
||||
bestMove: 'Mossa migliore',
|
||||
aiAnalysis: 'Analisi IA',
|
||||
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',
|
||||
pastePlaceholder: 'Incolla qui PGN o FEN per rivedere la partita mossa per mossa...',
|
||||
chooseCoach: 'Scegli la personalità del coach',
|
||||
orientation: 'Orientamento della scacchiera',
|
||||
startButton: 'Avvia analisi',
|
||||
next: 'Mossa successiva',
|
||||
previous: 'Mossa precedente',
|
||||
step: 'Mossa',
|
||||
missedTactics: 'Tattiche mancate',
|
||||
cpLoss: 'Variazione di valutazione',
|
||||
none: 'Nessuna rilevata',
|
||||
opening: 'Apertura',
|
||||
enginePending: 'Valutazione del motore in corso...',
|
||||
coachPending: 'Il coach sta preparando il feedback...',
|
||||
importError: 'Impossibile caricare questo PGN o FEN. Controlla la notazione.',
|
||||
},
|
||||
apiKeyInput: {
|
||||
title: 'Chiave API richiesta',
|
||||
|
||||
@@ -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