Skip to content

PWA (JavaScript)

ChessSelfCoach

Chess Self-Coach — Training PWA.

Loads pre-generated training data (from chess-self-coach train --prepare), displays mistake positions on a chessground board, and uses SM-2 spaced repetition to schedule reviews.

Dependencies (loaded from CDN at runtime): - chessground — interactive chess board - chess.js — move validation

ChessSelfCoach~appMode : string

App mode: 'demo' (GitHub Pages) or 'app' (FastAPI backend)

Kind: inner property of ChessSelfCoach

ChessSelfCoach~appVersion : string

App version (populated from /api/status in app mode)

Kind: inner property of ChessSelfCoach

ChessSelfCoach~stockfishVersion : string

Stockfish version (populated from /api/status in app mode)

Kind: inner property of ChessSelfCoach

ChessSelfCoach~Chessground : function

Chessground constructor (loaded from CDN)

Kind: inner property of ChessSelfCoach

ChessSelfCoach~Chess : function

Chess constructor (loaded from CDN)

Kind: inner property of ChessSelfCoach

ChessSelfCoach~sfWorker : Worker

Stockfish Web Worker

Kind: inner property of ChessSelfCoach

ChessSelfCoach~sfResolve : function

Resolve callback for current bestmove promise

Kind: inner property of ChessSelfCoach

ChessSelfCoach~trainingData : Object

Parsed training_data.json

Kind: inner property of ChessSelfCoach

ChessSelfCoach~srsState : Object.<string, SRSState>

SRS state keyed by position ID

Kind: inner property of ChessSelfCoach

ChessSelfCoach~session : Array.<Object>

Positions queue for the current session

Kind: inner property of ChessSelfCoach

ChessSelfCoach~currentIndex : number

Index of the current position in the session

Kind: inner property of ChessSelfCoach

ChessSelfCoach~attempts : number

Number of attempts on the current position

Kind: inner property of ChessSelfCoach

ChessSelfCoach~sessionResults : Array.<{id: string, correct: boolean, attempts: number}>

Results for the current session

Kind: inner property of ChessSelfCoach

ChessSelfCoach~cg : Object

Current chessground instance

Kind: inner property of ChessSelfCoach

ChessSelfCoach~sessionAppearances : Map.<string, number>

Number of times each position appeared in this session

Kind: inner property of ChessSelfCoach

ChessSelfCoach~completedCount : number

Count of unique positions completed (for progress display)

Kind: inner property of ChessSelfCoach

ChessSelfCoach~sessionOriginalSize : number

Total unique positions in original session

Kind: inner property of ChessSelfCoach

ChessSelfCoach~animationTimer : number

Timer ID for the wrong-move animation sequence

Kind: inner property of ChessSelfCoach

ChessSelfCoach~playLineInterval : number

Interval ID for the play-best-line animation

Kind: inner property of ChessSelfCoach

ChessSelfCoach~appView : string

Current view: 'games' (game list), 'review', or 'training'

Kind: inner property of ChessSelfCoach

ChessSelfCoach~selectedGameIds : Set.<string>

Selected game IDs for batch analysis

Kind: inner property of ChessSelfCoach

ChessSelfCoach~analyzingGameIds : Set.<string>

Game IDs in the current analysis job

Kind: inner property of ChessSelfCoach

ChessSelfCoach~pendingGameIds : Set.<string>

Game IDs queued for the next analysis batch

Kind: inner property of ChessSelfCoach

ChessSelfCoach~analysisOffset : number

Games completed in previous batches (for unified counter)

Kind: inner property of ChessSelfCoach

ChessSelfCoach~analysisTotalAll : number

Total games across all batches

Kind: inner property of ChessSelfCoach

ChessSelfCoach~gameListLimit : number

How many games to show per page

Kind: inner property of ChessSelfCoach

ChessSelfCoach~gameListPage : number

Current page (0-based)

Kind: inner property of ChessSelfCoach

ChessSelfCoach~resultFilter : string

Active result filter: 'all', 'win', 'loss', 'draw'

Kind: inner property of ChessSelfCoach

ChessSelfCoach~colorFilter : string

Active color filter: 'all', 'white', 'black'

Kind: inner property of ChessSelfCoach

ChessSelfCoach~openingFilter : string

Active opening filter: 'all' or opening name

Kind: inner property of ChessSelfCoach

ChessSelfCoach~statusFilter : string

Active status filter: 'all', 'analyzed', 'not-analyzed'

Kind: inner property of ChessSelfCoach

ChessSelfCoach~trainingGameFilter : string

When training on a specific game, its ID; null = all positions

Kind: inner property of ChessSelfCoach

ChessSelfCoach~analysisData : Object

Parsed analysis_data.json

Kind: inner property of ChessSelfCoach

ChessSelfCoach~reviewGame : Object

Currently selected game for review

Kind: inner property of ChessSelfCoach

ChessSelfCoach~currentPly : number

Current ply in review (0 = starting position)

Kind: inner property of ChessSelfCoach

ChessSelfCoach~reviewCg : Object

Second chessground instance for review board

Kind: inner property of ChessSelfCoach

ChessSelfCoach~reviewOrientation : string

Review board orientation

Kind: inner property of ChessSelfCoach

ChessSelfCoach~autoPlayTimer : number

Auto-play interval ID

Kind: inner property of ChessSelfCoach

ChessSelfCoach~classifiedMoves : Array

Classified moves for current game

Kind: inner property of ChessSelfCoach

ChessSelfCoach~DEFAULT_SETTINGS : Object

Kind: inner constant of ChessSelfCoach

ChessSelfCoach~PIECE_VALUES

Piece values in pawns (used for sacrifice detection).

Kind: inner constant of ChessSelfCoach

ChessSelfCoach~initStockfish()

Initialize Stockfish WASM engine (lazy, first call only). Uses the lite single-threaded variant for GitHub Pages compatibility.

Kind: inner method of ChessSelfCoach

ChessSelfCoach~getBestMove(fen, [depth]) ⇒ Promise.<(string|null)>

Get Stockfish's best move for a given position.

Kind: inner method of ChessSelfCoach
Returns: Promise.<(string|null)> - Best move in UCI notation (e.g. "e2e4") or null.

Param Type Default Description
fen string Position in FEN notation.
[depth] number 12 Search depth.

ChessSelfCoach~loadSettings() ⇒ Object

Load user settings from localStorage.

Kind: inner method of ChessSelfCoach
Returns: Object - Merged settings with defaults.

ChessSelfCoach~saveSettings(s)

Save user settings to localStorage.

Kind: inner method of ChessSelfCoach

Param Type Description
s Object Settings to save.

ChessSelfCoach~populateLimitFields(limits)

Populate the limit form fields from a limits object.

Kind: inner method of ChessSelfCoach

Param Type Description
limits Object Limits keyed by bracket name.

ChessSelfCoach~readLimitFields() ⇒ Object

Read limit values from the form fields.

Kind: inner method of ChessSelfCoach
Returns: Object - Limits object keyed by bracket name.

ChessSelfCoach~detectPreset()

Detect which preset matches the current limit field values and update buttons.

Kind: inner method of ChessSelfCoach

ChessSelfCoach~wirePresets()

Wire preset buttons: click applies preset values, field changes detect preset.

Kind: inner method of ChessSelfCoach

ChessSelfCoach~openSettings()

Open the unified settings modal, populating all fields.

Kind: inner method of ChessSelfCoach

ChessSelfCoach~saveAllSettings()

Save all settings from the unified modal.

Kind: inner method of ChessSelfCoach

ChessSelfCoach~updateSRS(state, correct) ⇒ SRSState

Update SRS state using the SM-2 algorithm (Piotr Wozniak, 1987).

  • Correct: interval progresses (1d → 3d → interval*ease), ease increases
  • Wrong: interval resets to 1d, repetitions reset, ease decreases
  • Ease factor never drops below 1.3

Kind: inner method of ChessSelfCoach
Returns: SRSState - Updated SRS state.

Param Type Description
state SRSState Current SRS state for a position.
correct boolean Whether the answer was correct.

ChessSelfCoach~selectPositions(positions, count) ⇒ Array.<Object>

Select positions for a training session using SRS priority.

Priority order: overdue (past review date) → new (never seen, blunders first) → learning (interval < 7 days). Mastered or not-yet-due positions are skipped.

Kind: inner method of ChessSelfCoach
Returns: Array.<Object> - Selected positions for the session.

Param Type Description
positions Array.<Object> All available training positions.
count number Maximum positions to select.

ChessSelfCoach~getMoveLink(gameId, fen) ⇒ string

Build a deep link to the specific move position in the original game.

Kind: inner method of ChessSelfCoach
Returns: string - URL with move anchor/parameter, or original URL if format unknown.

Param Type Description
gameId string Full game URL (lichess.org or chess.com).
fen string FEN of the position (contains fullmove number and side to move).

ChessSelfCoach~getLegalDests(fen) ⇒ Map.<string, Array.<string>>

Compute legal move destinations for chessground from a FEN.

Kind: inner method of ChessSelfCoach
Returns: Map.<string, Array.<string>> - Map of source square → destination squares.

Param Type Description
fen string FEN string of the position.

ChessSelfCoach~updateMaterialBalance(fen, orientation)

Compute material balance from a FEN string and display captured pieces. Shows advantage like chess.com/Lichess: captured pieces + point difference.

Kind: inner method of ChessSelfCoach

Param Type Description
fen string FEN position string.
orientation string Board orientation ("white" or "black").

ChessSelfCoach~formatClock(seconds) ⇒ string

Format seconds into MM:SS display.

Kind: inner method of ChessSelfCoach
Returns: string - Formatted time string (e.g. "09:00").

Param Type Description
seconds number Time in seconds.

ChessSelfCoach~updateClocks(position)

Update clock displays for a position. Top clock = opponent, bottom clock = player (matches board orientation). Hides clocks if position.clock is absent.

Kind: inner method of ChessSelfCoach

Param Type Description
position Object Training position with optional clock field.

ChessSelfCoach~animateWrongMove(position)

Animate the player's wrong move on the board, show annotation, then reset. Sequence: 500ms wait → animate move + show badge → 1500ms wait → reset + enable. If chess.move() fails (bad SAN), skips animation and falls back to text prompt.

Kind: inner method of ChessSelfCoach

Param Type Description
position Object Training position.

ChessSelfCoach~setupBoard(position)

Initialize the chessground board for a training position. Destroys any existing board, sets orientation to the player's color, and configures legal move destinations.

Kind: inner method of ChessSelfCoach

Param Type Description
position Object Training position from training_data.json.

ChessSelfCoach~showThinking()

Show the "Analyzing..." thinking indicator.

Kind: inner method of ChessSelfCoach

ChessSelfCoach~hideThinking()

Hide the thinking indicator.

Kind: inner method of ChessSelfCoach

ChessSelfCoach~getStockfishBestMove(fen) ⇒ Promise.<(string|null)>

Get Stockfish's best move, using backend API in [app] mode or WASM in [demo]. Falls back to WASM if the API call fails (e.g. server restarted).

Kind: inner method of ChessSelfCoach
Returns: Promise.<(string|null)> - Best move in UCI notation or null.

Param Type Description
fen string Position in FEN notation.

ChessSelfCoach~handleMove(orig, dest)

Handle a move made on the board. Validates with chess.js, compares to acceptable moves, and shows feedback. Player can retry until correct or dismiss.

Kind: inner method of ChessSelfCoach

Param Type Description
orig string Source square (e.g. "e2").
dest string Destination square (e.g. "e4").

ChessSelfCoach~_showSeeMovesLink(position)

Show the "See moves" deep link for a position.

Kind: inner method of ChessSelfCoach

Param Type Description
position Object Training position with game.id and fen.

ChessSelfCoach~showFeedback(correct, position, [gaveUp])

Display feedback after an answer (correct, wrong, or gave up). Shows the explanation and, on failure, plays the best move on the board.

Kind: inner method of ChessSelfCoach

Param Type Default Description
correct boolean Whether the answer was correct.
position Object Current training position.
[gaveUp] boolean false True if the player exhausted all attempts.

ChessSelfCoach~showRetryButton(position)

Show the Retry button after a punishment move. Clicking resets the board.

Kind: inner method of ChessSelfCoach

Param Type Description
position Object The current training position.

ChessSelfCoach~recordResult(correct)

Record the result of a position attempt. Updates SRS state and saves to localStorage.

Kind: inner method of ChessSelfCoach

Param Type Description
correct boolean Whether the answer was correct.

ChessSelfCoach~dismissPosition()

Permanently dismiss a position — it will never appear again. Sets an extremely long SRS interval so it's never selected.

Kind: inner method of ChessSelfCoach

ChessSelfCoach~skipPosition()

Skip a position — reinsert it later in the session for another try. Does not affect SRS state.

Kind: inner method of ChessSelfCoach

ChessSelfCoach~showAnswer()

Show the answer after 3+ failed attempts. Displays the same feedback as a correct answer but records a failure in SRS.

Kind: inner method of ChessSelfCoach

ChessSelfCoach~showPosition(index)

Display a position in the session. Sets up the board, prompt, and game info. If index exceeds session length, shows the session summary.

Kind: inner method of ChessSelfCoach

Param Type Description
index number Position index in the session array.

ChessSelfCoach~startSession()

Start a new training session. Selects positions via SRS priority, resets session state, and shows the first position.

Kind: inner method of ChessSelfCoach

ChessSelfCoach~showAnalysisProgress(jobId)

Display analysis job progress in the refresh modal.

Kind: inner method of ChessSelfCoach

Param Type Description
jobId string The job ID to track.

ChessSelfCoach~showGameList()

Show the game list view (default main view).

Kind: inner method of ChessSelfCoach

ChessSelfCoach~showTrainingView(gameId)

Show the training view, optionally scoped to one game.

Kind: inner method of ChessSelfCoach

Param Type Default Description
gameId string null If set, train only on positions from this game.

ChessSelfCoach~loadTrainingData()

Load training_data.json from server or static file.

Kind: inner method of ChessSelfCoach

ChessSelfCoach~loadAnalysisData()

Load analysis_data.json from server or static file.

Kind: inner method of ChessSelfCoach

ChessSelfCoach~winProb(cp) ⇒ number

Compute win probability from centipawn score (chess.com model).

Kind: inner method of ChessSelfCoach
Returns: number - Win probability for the side (0-1).

Param Type Description
cp number Centipawn score from white's perspective.

ChessSelfCoach~isSacrifice(move) ⇒ boolean

Detect whether a move is a sacrifice or tactical trap. Simulates the full PV recapture chain on the destination square. Returns true for: - Genuine sacrifice: full chain loses material (e.g. Nxf7, Rxf7 → net -2) - Tactical trap: first move appears to sacrifice, but full chain gains more than the apparent sacrifice (e.g. Rxe3 chain → apparent -2, net +3)

Kind: inner method of ChessSelfCoach
Returns: boolean - True if the move is a sacrifice or tactical trap.

Param Type Description
move Object Move data with fen_before, move_san, move_uci, eval_before.

ChessSelfCoach~isMissedCapture(move) ⇒ boolean

Check if the engine's best move was a capture winning material (missed opportunity). Simulates the best move and follows the PV up to 8 plies, tracking all captures on any square (an exchange can remove a defender, enabling a capture elsewhere).

Kind: inner method of ChessSelfCoach
Returns: boolean - True if best move was a capture with net material gain.

Param Type Description
move Object Move data (must have fen_before, move_uci, eval_before with PV).

ChessSelfCoach~classifyMove(move, playerColor) ⇒ Object

Classify a move based on expected points lost.

Kind: inner method of ChessSelfCoach

Param Type Description
move Object Move data from analysis_data.json.
playerColor string 'white' or 'black'.

ChessSelfCoach~classifyAllMoves(moves, playerColor) ⇒ Array

Classify all moves in a game for both players.

Kind: inner method of ChessSelfCoach
Returns: Array - Array of classification objects (one per move, null if unclassifiable).

Param Type Description
moves Array Array of move objects.
playerColor string Player's color.

ChessSelfCoach~computeAccuracy(moves, classifications, color) ⇒ number

Compute accuracy percentage for a color.

Kind: inner method of ChessSelfCoach
Returns: number - Accuracy 0-100.

Param Type Description
moves Array All moves.
classifications Array Classification for each move.
color string 'white' or 'black'.

ChessSelfCoach~updateAnalyzeButton()

Update the "Analyze selected (N)" button text and disabled state.

Kind: inner method of ChessSelfCoach

ChessSelfCoach~_buildPagination(totalPages, totalGames) ⇒ HTMLDivElement

Build pagination controls element.

Kind: inner method of ChessSelfCoach

Param Type Description
totalPages number Total number of pages.
totalGames number Total number of filtered games.

ChessSelfCoach~showGameSelector()

Render the game selector list with checkboxes and analysis status.

Kind: inner method of ChessSelfCoach

ChessSelfCoach~selectGame(gameId)

Select a game for review.

Kind: inner method of ChessSelfCoach

Param Type Description
gameId string Game URL key.

ChessSelfCoach~getOpeningName() ⇒ string

Find the opening name from the game moves.

Kind: inner method of ChessSelfCoach
Returns: string - Opening name or empty string.

ChessSelfCoach~renderGameSummary()

Render the game summary (player names).

Kind: inner method of ChessSelfCoach

ChessSelfCoach~renderOpeningInfo()

Render opening info.

Kind: inner method of ChessSelfCoach

ChessSelfCoach~renderMoveList()

Render the two-column move list.

Kind: inner method of ChessSelfCoach

ChessSelfCoach~createMoveCell(idx, move, cls, theoryDep) ⇒ HTMLElement

Create a move cell element for the move list.

Kind: inner method of ChessSelfCoach

Param Type Description
idx number Move index in the moves array.
move Object Move data.
cls Object Classification data.
theoryDep number Index of theory departure.

ChessSelfCoach~goToMove(ply)

Navigate to a specific ply in the review.

Kind: inner method of ChessSelfCoach

Param Type Description
ply number Move ply (0 = starting position).

ChessSelfCoach~setupReviewBoard()

Set up the review board (second Chessground instance).

Kind: inner method of ChessSelfCoach

ChessSelfCoach~updateEvalBar(ply)

Update the eval bar for a given ply.

Kind: inner method of ChessSelfCoach

Param Type Description
ply number Current ply.

ChessSelfCoach~updateBoardArrows(ply)

Update board arrows showing best move and played move.

Kind: inner method of ChessSelfCoach

Param Type Description
ply number Current ply.

ChessSelfCoach~updatePvLine(ply)

Update the PV line display.

Kind: inner method of ChessSelfCoach

Param Type Description
ply number Current ply.

ChessSelfCoach~renderScoreChart()

Render the score chart.

Kind: inner method of ChessSelfCoach

renderScoreChart~getEval(move) ⇒ number

Get eval value for a move, clamped.

Kind: inner method of renderScoreChart
Returns: number - cp value, clamped.

Param Type
move Object

ChessSelfCoach~updateChartCursor()

Update the score chart cursor for current ply.

Kind: inner method of ChessSelfCoach

ChessSelfCoach~renderScoreChartBase(ctx, w, h)

Render the score chart base (without cursor). Used for cursor updates.

Kind: inner method of ChessSelfCoach

Param Type Description
ctx CanvasRenderingContext2D
w number Canvas logical width.
h number Canvas logical height.

ChessSelfCoach~init()

Initialize the PWA. Loads dependencies from CDN, fetches training data, restores SRS state from localStorage, wires up UI controls, registers the service worker, and starts the first session.

Kind: inner method of ChessSelfCoach

init~wireNavItem(navId, showFn, [modalId])

Wire a nav menu item: click → disabled check → closeMenu → show function. Optionally wire the modal's close button.

Kind: inner method of init

Param Type Description
navId string ID of the nav
  • element.
  • showFn function Function to call when clicked.
    [modalId] string Modal ID; derives close button as "close-{name}".

    ChessSelfCoach~reconnectToRunningJob()

    Check for a running analysis job on the server and reconnect to its SSE stream. Called at startup so the progress counter reappears after page refresh.

    Kind: inner method of ChessSelfCoach

    ChessSelfCoach~autoFetchGames()

    Auto-fetch games from Lichess/chess.com at startup. Falls back to analysis_data.json on error.

    Kind: inner method of ChessSelfCoach

    ChessSelfCoach~doFetchGames(maxGames)

    Fetch games with a specific max_games parameter. Updates the modal status.

    Kind: inner method of ChessSelfCoach

    Param Type Description
    maxGames number Maximum number of games to fetch per source.

    ChessSelfCoach~analyzeSelectedGames()

    Analyze the selected games (send game_ids to analysis API).

    Kind: inner method of ChessSelfCoach

    ChessSelfCoach~startAnalysisJob(ids)

    Start an analysis job for the given game IDs (internal helper for queue continuation).

    Kind: inner method of ChessSelfCoach

    Param Type Description
    ids Array.<string> Game IDs to analyze.

    ChessSelfCoach~SRSState : Object

    Kind: inner typedef of ChessSelfCoach
    Properties

    Name Type Description
    interval number Days until next review
    ease number Ease factor (minimum 1.3)
    repetitions number Consecutive correct answers
    next_review string ISO date string (YYYY-MM-DD)
    history Array.<{date: string, correct: boolean}> Review history