Skip to content

game.js holds ten responsibilities in one 1,855-line scope #89

Closed

Description

@TMHSDigital

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:

  1. js/notation.js: pgnMoveTokens and a pure SAN writer.
  2. js/saved-game.js: isValidCoords, isValidBoard, cleanClock, findKingPositions, validateSavedGame.
  3. js/clock.js: newClock, clockRemaining, formatClock, canDeliverMate, taking the clock and the side to move as arguments.
  4. js/engine-bridge.js: getAIWorker, askEngine.
  5. Split updateStatusDisplay into a status-text function and a controls function, then move the DOM renderers and the import dialog to js/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.js is 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, then npm 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

  1. added
    tech-debt
    severity: medium
    on Nov 15, 2026
  2. TMHSDigital commented on Nov 15, 2026

    @TMHSDigital
    OwnerAuthor

    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:

    1. js/notation.js: pgnMoveTokens and the other PGN text functions, and a pure SAN writer. writeSAN(move, positionBefore, positionAfter) replaces generateNotationWithDisambiguation, which read currentPlayer and boardState for the + and #.
    2. js/saved-game.js: isValidCoords, isValidBoard, cleanClock, findKingPositions, cleanSnapshot, validateSavedGame, with SAVED_GAME_VERSION and STANDARD_START.
    3. js/clock.js: makeClock(controlKey), timeLeft(clock, color, playerToMove, now) and formatClock. canDeliverMate went to rules.js with Leftover code and drifted duplicates across the js/ modules #107. game.js keeps one-line newClock() and clockRemaining(color) that pass its own state in.
    4. js/engine-bridge.js: the worker, the request counter, askEngine, dropEngineRequests and isLatestEngineRequest. game.js no longer holds aiWorker or aiRequestId.

    Each file is in index.html, APP_FILES in sw.js, appGlobals in eslint.config.mjs and tests/helpers/load-game.js, and the docs list them. Nothing was converted to ES modules.

    Against the acceptance criteria:

    • "The pure functions listed can be loaded and tested without a DOM": yes. tests/unit/no-dom.test.js loads notation.js, saved-game.js and clock.js with no document or window defined and uses pgnMoveTokens, writeSAN, validateSavedGame, makeClock, timeLeft and formatClock.
    • "All existing tests pass after each step": the full suite (445 tests), lint and the format check pass after the four steps together; no existing test was changed except the script list in the page test.
    • "game.js is 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 updateStatusDisplay into a status-text function and a controls function, then move the DOM renderers and the import dialog to js/game-ui.js. Those functions read and write the module-level state of game.js directly, so that step needs the state reachable from another file first.

  3. TMHSDigital commented on Nov 15, 2026

    @TMHSDigital
    OwnerAuthor

    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 before game.js:

    • The lookups of the page's elements, and the connecting of the controls (bindControls(handlers)).
    • The renderers, which now take plain values instead of reading the game: 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().
    • The Load dialog and the list of past games in it. It calls back into importPGN(), importFEN() and readArchive().

    updateStatusDisplay is split as asked: statusText() says what the line reads and controlsView() 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:

    • "The pure functions listed can be loaded and tested without a DOM": yes, since the earlier commit.
    • "All existing tests pass after each step": yes. All 468 passed unchanged apart from the script list in the page test; 8 new tests in tests/unit/game-ui.test.js load the new file without game.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.js is 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, and importPGN() / 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 validateSavedGame already takes it) and the PGN and FEN text building.

  4. TMHSDigital commented on Nov 15, 2026

    @TMHSDigital
    OwnerAuthor

    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) and readFEN(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() and timeoutResult().

    In game.js, buildPGN(), importPGN(), importFEN(), saveGameState(), loadGameState(), archiveCurrentGame(), tickClock() and moveCost() are now a few lines each: they hand the state to one of those functions, or apply what comes back.

    game.js is 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:

    • "The pure functions listed can be loaded and tested without a DOM": yes, and more than were listed. tests/unit/no-dom.test.js has 21 tests with no document; 14 are new.
    • "All existing tests pass after each step": yes. No existing test was changed except the script list in the page test. 491 tests, lint and format check pass. In Chromium I finished a game and saw it marked and exported, opened it again from the past games, loaded a PGN with a FEN tag and a bad PGN through the dialog, reloaded the page and found the game there, and undid a move, with no error.
    • "game.js is 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.md now 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.js still names six buttons, for the questions and notices it puts on them, and it still connects the board's click handler itself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    severity: mediumtech-debt

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions