Repository navigation
Description
Summary
js/game.js is 1,855 lines and holds about ten separate jobs in one scope with about 30 shared module-level variables. It is the most-changed code file in the repository (31 of the last 200 commits).
Where
js/game.js:73(startup and listener wiring),js/game.js:384(move flow and undo),js/game.js:552(confirm buttons, resign, draw),js/game.js:680(engine bridge and worker),js/game.js:802(clock),js/game.js:924(hints),js/game.js:1065(saved-game validation and storage),js/game.js:1287(rendering of the move list, captured pieces and status),js/game.js:1502(PGN and FEN export),js/game.js:1598(PGN import and its dialog),js/game.js:1715(SAN writing)
Details
Pure functions that need no DOM (pgnMoveTokens, formatClock, canDeliverMate, validateSavedGame, isValidBoard, the SAN writer) cannot be loaded without a document that has #move-history and the other elements, because the DOM lookups sit at the top of the file. updateStatusDisplay sets the status text and also the disabled state and labels of five unrelated buttons and the clocks, and is called from 12 places for different reasons.
Impact
Every change (clock, import, announcements, persistence) is a diff in the same file, and each feature adds another group of variables to the shared scope.
Suggested fix
The app uses plain script tags, so each extraction is "move functions to a new file loaded before game.js". Each new file must be added to index.html, the APP_FILES list in sw.js (checked by tests/unit/offline.test.js), appGlobals in eslint.config.mjs and tests/helpers/load-game.js. Least coupled first:
js/notation.js:pgnMoveTokensand a pure SAN writer.js/saved-game.js:isValidCoords,isValidBoard,cleanClock,findKingPositions,validateSavedGame.js/clock.js:newClock,clockRemaining,formatClock,canDeliverMate, taking the clock and the side to move as arguments.js/engine-bridge.js:getAIWorker,askEngine.- Split
updateStatusDisplayinto a status-text function and a controls function, then move the DOM renderers and the import dialog tojs/game-ui.js.
Do not convert to ES modules in the same change: the worker (importScripts) and the fallback for pages opened from a file depend on classic scripts. Run the suite after every step; it is the safety net.
Acceptance criteria
- The pure functions listed can be loaded and tested without a DOM.
-
game.jsis left with state, the move flow, undo, end of game and the computer's turn. - All existing tests pass after each step.
Getting started
- Relevant files:
js/game.js,index.html,sw.js,eslint.config.mjs,tests/helpers/load-game.js - How to run tests:
npm ci, thennpm test - Related docs:
docs/ARCHITECTURE.md,.github/CONTRIBUTING.md
Filed by repo-audit/full-audit at ac3afa3. Severity: medium. Effort: L. audit-key: tech-debt|js/game.js|file
Activity
TMHSDigital commentedon Nov 15, 2026
Steps 1 to 4 of the suggested fix are in ("Move what needs no page out of game.js"). Step 5 is not, so I am leaving this issue open.
What moved, each into a file loaded before
game.js:js/notation.js:pgnMoveTokensand the other PGN text functions, and a pure SAN writer.writeSAN(move, positionBefore, positionAfter)replacesgenerateNotationWithDisambiguation, which readcurrentPlayerandboardStatefor the+and#.js/saved-game.js:isValidCoords,isValidBoard,cleanClock,findKingPositions,cleanSnapshot,validateSavedGame, withSAVED_GAME_VERSIONandSTANDARD_START.js/clock.js:makeClock(controlKey),timeLeft(clock, color, playerToMove, now)andformatClock.canDeliverMatewent torules.jswith Leftover code and drifted duplicates across the js/ modules #107.game.jskeeps one-linenewClock()andclockRemaining(color)that pass its own state in.js/engine-bridge.js: the worker, the request counter,askEngine,dropEngineRequestsandisLatestEngineRequest.game.jsno longer holdsaiWorkeroraiRequestId.Each file is in
index.html,APP_FILESinsw.js,appGlobalsineslint.config.mjsandtests/helpers/load-game.js, and the docs list them. Nothing was converted to ES modules.Against the acceptance criteria:
tests/unit/no-dom.test.jsloadsnotation.js,saved-game.jsandclock.jswith nodocumentorwindowdefined and usespgnMoveTokens,writeSAN,validateSavedGame,makeClock,timeLeftandformatClock.game.jsis left with state, the move flow, undo, end of game and the computer's turn": not yet. It went from 2,456 to 2,020 lines and still holds the renderers (move list, captured pieces, status and controls, clock display), the confirm buttons, past games, PGN and FEN export, and the Load dialog.What remains is step 5: split
updateStatusDisplayinto a status-text function and a controls function, then move the DOM renderers and the import dialog tojs/game-ui.js. Those functions read and write the module-level state ofgame.jsdirectly, so that step needs the state reachable from another file first.Move what needs no page out of game.js (#89)
Move the page updates and the Load dialog out of game.js (#89)
TMHSDigital commentedon Nov 15, 2026
Step 5 of the suggested fix is in ("Move the page updates and the Load dialog out of game.js"), so all five steps are done. I am leaving the issue open because the second acceptance criterion is only partly met; details below.
What moved into
js/game-ui.js, loaded beforegame.js:bindControls(handlers)).renderStatus(text),renderControls(view),renderClocks(clocks),renderMoveList(moves, view),renderCaptured(taken, lead),renderHint(move),renderReviewScore(text).announce(), the buttons that ask twice (confirmSecondClick()and its two companions),flashButton(),copyOrDownload(),downloadText().importPGN(),importFEN()andreadArchive().updateStatusDisplayis split as asked:statusText()says what the line reads andcontrolsView()what the buttons depend on;updateStatusDisplay()hands both to the renderers.Plain values were needed, not only a move of the functions: the tests load each file as a module, so another file cannot read the variables of
game.js. That is what my earlier comment meant by the state having to be reachable first.Against the acceptance criteria:
tests/unit/game-ui.test.jsload the new file withoutgame.js. Lint and format check pass. In Chromium I played moves, asked for a hint, looked back, resigned and undid it, copied the FEN, loaded a position through the dialog (with a bad text, an empty box and the confirmation), played on a clock and against the computer, with no error.game.jsis left with state, the move flow, undo, end of game and the computer's turn": partly. It went from 2,199 to 1,728 lines and no longer draws anything but the board calls it already made. It still holds, next to those five things: the running of the clock, hints and the review of a finished game, saving and the past games, building PGN and FEN, andimportPGN()/importFEN(). It also still names six buttons, for the questions and notices it puts on them.If that remainder is acceptable as "state", this can be closed as it is. If not, the next candidates are the past games with saving (they need the state passed in as a snapshot, as
validateSavedGamealready takes it) and the PGN and FEN text building.TMHSDigital commentedon Nov 15, 2026
Closed by the commit "Move what needs no game state out of game.js". This comment says what was done since the last one and what is deliberately left.
What moved out this time, all of it logic that reads no state of the game:
js/notation.js:writePGN(game)writes a game as PGN from plain values,readPGN(text)andreadFEN(text)read text into moves that have been checked,moveNumber(index, start)numbers moves,importSizeError(length)gives the too-long message.js/game-store.js(new):storeGame(),readStoredGame(),clearStoredGame(),readArchive(),addToArchive(). The saved game and the past games, each checked when read back.js/review.js(new):scoreText(),scoreDrop(),scoreDropText(). The engine's scores in words, and what a move cost.js/clock.js:lowTimeLevel()andtimeoutResult().In
game.js,buildPGN(),importPGN(),importFEN(),saveGameState(),loadGameState(),archiveCurrentGame(),tickClock()andmoveCost()are now a few lines each: they hand the state to one of those functions, or apply what comes back.game.jsis 1,558 lines. It was 1,855 when this issue was filed and had grown to 2,456 when work on it began.Against the acceptance criteria:
tests/unit/no-dom.test.jshas 21 tests with no document; 14 are new.game.jsis left with state, the move flow, undo, end of game and the computer's turn": yes for everything that can be separated from the state. What is left beside those five is the code that reads or changes the state for the clock, hints, review, saving and loading: starting and stopping the clock interval, asking the engine and keeping its answer, choosing which position is on screen, and applying a loaded game move by move.Why I stopped there: the scripts share one global scope in the browser, but the tests load each file as a module, so a second file cannot read or assign the variables of
game.js. Moving that remaining code would mean putting the state into an object that several files share. That is a design change with its own risks, it is not among the steps this issue lists, and the issue rules out the neighbouring change to ES modules.docs/ROADMAP.mdnow says this under "Splitting game.js". If you want it, it deserves an issue of its own.Two smaller things left as they are:
game.jsstill names six buttons, for the questions and notices it puts on them, and it still connects the board's click handler itself.Move what needs no game state out of game.js (TMHSDigital#89)