ChessUp/src/client/views/gameView.ts

706 lines
26 KiB
TypeScript

import { Chess } from '../../shared/chess';
import { MAX_PREMOVES } from '../../shared/premove';
import { categoryLabel, formatTimeControl } from '../../shared/timeControl';
import type { ActiveGameState, Color, ServerWsMessage } from '../../shared/types';
import { apiRequest, wsClient } from '../api';
import { ChessBoard } from '../components/board';
import { ClockWidget } from '../components/clock';
import { MoveList } from '../components/moveList';
import { clearNode, el } from '../dom';
import { sound } from '../sound';
import type { AppContext, ViewHandle } from './context';
function terminationLabel(term: string | null): string {
switch (term) {
case 'checkmate':
return 'Checkmate';
case 'resign':
return 'Resignation';
case 'timeout':
return 'Time out';
case 'abandonment':
return 'Abandonment (60s disconnect)';
case 'stalemate':
return 'Stalemate';
case 'draw_agreement':
return 'Draw by agreement';
case 'repetition':
return 'Threefold repetition';
case 'fifty_move':
return '50-move rule';
case 'insufficient_material':
return 'Insufficient material';
case 'aborted':
return 'Game aborted';
default:
return 'Finished';
}
}
export function mountGameView(container: HTMLElement, ctx: AppContext, gameId: string): ViewHandle {
let game: ActiveGameState | null = null;
let errorMsg = '';
let viewPly = 0;
let orientationOverride: Color | null = null;
let confirmResign = false;
let confirmResignTimer: number | null = null;
let destroyed = false;
let lastNotifiedMovesLen = -1;
const board = new ChessBoard({
mode: 'readonly',
onMove(uci) {
wsClient.send({ type: 'game:move', gameId, uci });
},
onPremoveChange(premoveQueueUci) {
renderPremoveBanner(premoveQueueUci);
}
});
const topClock = new ClockWidget();
const bottomClock = new ClockWidget();
const moveList = new MoveList({
onSelectPly(ply) {
viewPly = ply;
syncBoardAndControls();
},
onFlip() {
const current = board.getOrientation();
orientationOverride = current === 'w' ? 'b' : 'w';
board.setOrientation(orientationOverride);
if (game) updateDynamicHeaderBars(game);
}
});
// Dynamic UI refs updated without tearing down Board / Clocks
const topPlayerBar = el('div', { className: 'player-bar' });
const bottomPlayerBar = el('div', { className: 'player-bar' });
const premoveBannerEl = el('div', { className: 'premove-banner hidden' });
const liveNoticeEl = el('div', { className: 'live-notice hidden' });
const statusBannerEl = el('div', { className: 'game-status-banner hidden' });
const actionsEl = el('div', { className: 'game-actions' });
const chatMessagesEl = el('div', { className: 'chat-messages' });
const chatForm = el('form', { className: 'chat-form' });
const chatInput = el('input', {
type: 'text',
className: 'input input-sm',
placeholder: 'Send a message...',
maxlength: '300'
}) as HTMLInputElement;
const chatSendBtn = el('button', { type: 'submit', className: 'btn btn-sm' }, 'Send');
chatForm.appendChild(chatInput);
chatForm.appendChild(chatSendBtn);
chatForm.addEventListener('submit', (e) => {
e.preventDefault();
const txt = chatInput.value.trim();
if (!txt) return;
wsClient.send({ type: 'game:chat', gameId, text: txt });
chatInput.value = '';
});
const specBadgeEl = el('span', { className: 'muted small-text' });
const headerMetaEl = el('div', { className: 'game-meta-line' });
function buildSkeleton(): void {
clearNode(container);
const page = el('div', { className: 'page-container game-page' });
const layout = el('div', { className: 'game-layout' });
const boardCol = el('div', { className: 'board-col' });
boardCol.appendChild(topPlayerBar);
boardCol.appendChild(board.root);
boardCol.appendChild(bottomPlayerBar);
boardCol.appendChild(premoveBannerEl);
boardCol.appendChild(liveNoticeEl);
layout.appendChild(boardCol);
const sideCol = el('div', { className: 'game-side-col' });
const infoCard = el('div', { className: 'card' });
const infoBody = el('div', { className: 'card-body compact' });
infoBody.appendChild(headerMetaEl);
infoBody.appendChild(statusBannerEl);
infoCard.appendChild(infoBody);
sideCol.appendChild(infoCard);
const movesCard = el('div', { className: 'card moves-card' });
movesCard.appendChild(moveList.root);
movesCard.appendChild(actionsEl);
sideCol.appendChild(movesCard);
const chatCard = el('div', { className: 'card chat-card' });
const chatHead = el('div', { className: 'card-header' });
chatHead.appendChild(el('span', { className: 'card-title-sm' }, 'Chat'));
chatHead.appendChild(specBadgeEl);
chatCard.appendChild(chatHead);
chatCard.appendChild(chatMessagesEl);
chatCard.appendChild(chatForm);
sideCol.appendChild(chatCard);
layout.appendChild(sideCol);
page.appendChild(layout);
container.appendChild(page);
}
function myColor(g: ActiveGameState): Color | null {
const u = ctx.getUser();
if (!u) return null;
if (g.white.userId === u.id) return 'w';
if (g.black.userId === u.id) return 'b';
return null;
}
function effectiveOrientation(g: ActiveGameState): Color {
if (orientationOverride) return orientationOverride;
return myColor(g) || 'w';
}
function renderPlayerBar(
target: HTMLElement,
clock: ClockWidget,
g: ActiveGameState,
color: Color
): void {
clearNode(target);
const p = color === 'w' ? g.white : g.black;
const isTurn = !g.finished && g.turn === color;
target.className = isTurn ? 'player-bar player-turn' : 'player-bar';
const left = el('div', { className: 'player-info' });
const dotClass = p.isBot
? 'dot dot-bot'
: p.connected
? 'dot dot-online'
: 'dot dot-offline';
left.appendChild(el('span', { className: dotClass, title: p.connected ? 'Connected' : 'Disconnected' }));
if (p.userId !== null && !p.isBot) {
const nameLink = el(
'a',
{ href: `/u/${encodeURIComponent(p.username)}`, className: 'player-name' },
p.username
);
nameLink.addEventListener('click', (e) => {
e.preventDefault();
ctx.navigate(`/u/${encodeURIComponent(p.username)}`);
});
left.appendChild(nameLink);
} else {
left.appendChild(el('span', { className: 'player-name' }, p.username));
}
if (p.rating !== null) {
left.appendChild(el('span', { className: 'rating-chip' }, ` (${p.rating}${p.provisional ? '?' : ''})`));
}
const diff = color === 'w' ? g.whiteRatingDiff : g.blackRatingDiff;
if (g.finished && diff !== null) {
const sign = diff >= 0 ? '+' : '';
const cls = diff > 0 ? 'diff-pos' : diff < 0 ? 'diff-neg' : 'muted';
left.appendChild(el('span', { className: `rating-diff ${cls}` }, ` ${sign}${diff}`));
}
if (!g.finished && p.disconnectDeadlineMs && !p.connected) {
const secs = Math.max(0, Math.ceil((p.disconnectDeadlineMs - Date.now()) / 1000));
left.appendChild(el('span', { className: 'disconnect-badge' }, `Forfeit in ${secs}s`));
}
target.appendChild(left);
target.appendChild(clock.root);
const ms = color === 'w' ? g.whiteTimeMs : g.blackTimeMs;
clock.update(ms, g.clockRunning && isTurn, g.category === 'unlimited');
}
function formatPremoveStep(uci: string): string {
const from = uci.slice(0, 2);
const to = uci.slice(2, 4);
const promo = uci.length === 5 ? `=${uci.charAt(4).toUpperCase()}` : '';
return `${from}→${to}${promo}`;
}
function renderPremoveBanner(queueUci: string[]): void {
clearNode(premoveBannerEl);
if (!queueUci || queueUci.length === 0) {
premoveBannerEl.className = 'premove-banner hidden';
return;
}
const maxPreview = 5;
const formatted = queueUci.slice(0, maxPreview).map(formatPremoveStep).join(', ');
const suffix = queueUci.length > maxPreview ? `, +${queueUci.length - maxPreview} more` : '';
premoveBannerEl.className = 'premove-banner';
premoveBannerEl.appendChild(
el('span', { className: 'premove-text' }, `Premoves (${queueUci.length}/${MAX_PREMOVES}): ${formatted}${suffix}`)
);
const btns = el('div', { className: 'btn-row' });
if (queueUci.length > 1) {
const undoBtn = el('button', { type: 'button', className: 'btn btn-xs' }, 'Undo');
undoBtn.addEventListener('click', () => board.popPremove());
btns.appendChild(undoBtn);
}
const clearBtn = el('button', { type: 'button', className: 'btn btn-xs' }, 'Clear');
clearBtn.addEventListener('click', () => board.clearPremove());
btns.appendChild(clearBtn);
premoveBannerEl.appendChild(btns);
}
function updateDynamicHeaderBars(g: ActiveGameState): void {
const orient = effectiveOrientation(g);
const topColor: Color = orient === 'w' ? 'b' : 'w';
const bottomColor: Color = orient;
board.setOrientation(orient);
renderPlayerBar(topPlayerBar, topClock, g, topColor);
renderPlayerBar(bottomPlayerBar, bottomClock, g, bottomColor);
headerMetaEl.textContent = `${formatTimeControl(g.initialMs, g.incrementMs)} · ${categoryLabel(g.category)} · ${
g.botLevel ? `Stockfish Lv ${g.botLevel}` : g.rated ? 'Rated' : 'Casual'
}`;
specBadgeEl.textContent = g.spectatorCount > 0 ? `${g.spectatorCount} watching` : '';
// Status / Result banner
clearNode(statusBannerEl);
if (g.finished) {
statusBannerEl.className = 'game-status-banner finished';
const title =
g.result === '1-0'
? 'White wins (1-0)'
: g.result === '0-1'
? 'Black wins (0-1)'
: g.result === '1/2-1/2'
? 'Draw (1/2-1/2)'
: 'Game Aborted';
statusBannerEl.appendChild(el('strong', null, title));
statusBannerEl.appendChild(el('div', { className: 'small-text muted' }, terminationLabel(g.termination)));
} else if (g.abortDeadlineMs && g.movesUci.length < 2) {
const secs = Math.max(0, Math.ceil((g.abortDeadlineMs - Date.now()) / 1000));
statusBannerEl.className = 'game-status-banner';
statusBannerEl.textContent = `Waiting for first moves · auto-abort in ${secs}s`;
} else {
statusBannerEl.className = 'game-status-banner hidden';
}
}
function renderLayout(): void {
if (destroyed) return;
if (errorMsg) {
clearNode(container);
const errPage = el('div', { className: 'page-container narrow-page' });
const card = el('div', { className: 'card' });
const body = el('div', { className: 'card-body' });
body.appendChild(el('div', { className: 'alert alert-error' }, errorMsg));
const back = el('button', { type: 'button', className: 'btn' }, 'Back to Lobby');
back.addEventListener('click', () => ctx.navigate('/'));
body.appendChild(back);
card.appendChild(body);
errPage.appendChild(card);
container.appendChild(errPage);
return;
}
if (!game) return;
const g = game;
updateDynamicHeaderBars(g);
// Action buttons
renderActions(g);
renderChat(g);
syncBoardAndControls();
}
function syncBoardAndControls(): void {
if (!game) return;
const g = game;
const mc = myColor(g);
const isLive = viewPly === g.movesUci.length;
if (mc && !g.finished && isLive) {
board.setMode('play', mc);
} else {
board.setMode('readonly');
}
if (isLive) {
const lastUci = g.movesUci.length > 0 ? g.movesUci[g.movesUci.length - 1] : null;
board.setPosition(g.fen, lastUci);
liveNoticeEl.className = 'live-notice hidden';
} else {
const temp = new Chess(g.initialFen);
for (let i = 0; i < viewPly && i < g.movesUci.length; i++) {
temp.moveUci(g.movesUci[i]!);
}
const lastUci = viewPly > 0 ? g.movesUci[viewPly - 1] : null;
board.setPosition(temp.fen(), lastUci);
clearNode(liveNoticeEl);
liveNoticeEl.className = 'live-notice';
liveNoticeEl.appendChild(el('span', null, `Viewing move ${viewPly} of ${g.movesUci.length} `));
const jumpBtn = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Jump to live');
jumpBtn.addEventListener('click', () => {
viewPly = g.movesUci.length;
syncBoardAndControls();
});
liveNoticeEl.appendChild(jumpBtn);
}
moveList.render(g.movesSan, viewPly);
}
function renderActions(g: ActiveGameState): void {
clearNode(actionsEl);
const mc = myColor(g);
if (g.finished) {
const row = el('div', { className: 'action-row' });
if (g.saved) {
const analyzeBtn = el('button', { type: 'button', className: 'btn btn-primary btn-sm' }, 'Analyze Game');
analyzeBtn.addEventListener('click', () => ctx.navigate(`/analysis/${g.id}`));
row.appendChild(analyzeBtn);
const pgnLink = el(
'a',
{ href: `/api/games/${g.id}/pgn`, className: 'btn btn-sm', target: '_blank' },
'PGN'
);
row.appendChild(pgnLink);
}
if (mc) {
if (g.rematchGameId) {
const goBtn = el('button', { type: 'button', className: 'btn btn-primary btn-sm' }, 'Open Rematch');
goBtn.addEventListener('click', () => ctx.navigate(`/game/${g.rematchGameId}`));
row.appendChild(goBtn);
} else if (g.rematchOfferFrom && g.rematchOfferFrom !== mc) {
const accBtn = el('button', { type: 'button', className: 'btn btn-primary btn-sm' }, 'Accept Rematch');
const decBtn = el('button', { type: 'button', className: 'btn btn-sm' }, 'Decline');
accBtn.addEventListener('click', () => wsClient.send({ type: 'game:rematch_respond', gameId: g.id, accept: true }));
decBtn.addEventListener('click', () => wsClient.send({ type: 'game:rematch_respond', gameId: g.id, accept: false }));
row.appendChild(accBtn);
row.appendChild(decBtn);
} else {
const remBtn = el(
'button',
{
type: 'button',
className: 'btn btn-sm',
disabled: g.rematchOfferFrom === mc
},
g.rematchOfferFrom === mc ? 'Rematch Sent...' : 'Rematch'
);
remBtn.addEventListener('click', () => wsClient.send({ type: 'game:rematch_offer', gameId: g.id }));
row.appendChild(remBtn);
}
}
const lobbyBtn = el('button', { type: 'button', className: 'btn btn-sm' }, 'Lobby');
lobbyBtn.addEventListener('click', () => ctx.navigate('/'));
row.appendChild(lobbyBtn);
actionsEl.appendChild(row);
return;
}
if (!mc) {
actionsEl.appendChild(el('div', { className: 'muted small-text center-text' }, 'Spectating live game'));
return;
}
// Incoming draw offer banner
if (g.drawOfferFrom && g.drawOfferFrom !== mc) {
const offerBar = el('div', { className: 'offer-bar' });
offerBar.appendChild(el('span', null, 'Opponent offers a draw'));
const acc = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Accept');
const dec = el('button', { type: 'button', className: 'btn btn-xs' }, 'Decline');
acc.addEventListener('click', () => wsClient.send({ type: 'game:draw_respond', gameId: g.id, accept: true }));
dec.addEventListener('click', () => wsClient.send({ type: 'game:draw_respond', gameId: g.id, accept: false }));
offerBar.appendChild(acc);
offerBar.appendChild(dec);
actionsEl.appendChild(offerBar);
}
// Incoming takeback offer banner
if (g.takebackOfferFrom && g.takebackOfferFrom !== mc) {
const offerBar = el('div', { className: 'offer-bar' });
offerBar.appendChild(el('span', null, 'Opponent requests a takeback'));
const acc = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Allow');
const dec = el('button', { type: 'button', className: 'btn btn-xs' }, 'Decline');
acc.addEventListener('click', () => wsClient.send({ type: 'game:takeback_respond', gameId: g.id, accept: true }));
dec.addEventListener('click', () => wsClient.send({ type: 'game:takeback_respond', gameId: g.id, accept: false }));
offerBar.appendChild(acc);
offerBar.appendChild(dec);
actionsEl.appendChild(offerBar);
}
const row = el('div', { className: 'action-row' });
if (g.movesUci.length < 2) {
const abortBtn = el('button', { type: 'button', className: 'btn btn-sm btn-danger' }, 'Abort');
abortBtn.addEventListener('click', () => wsClient.send({ type: 'game:abort', gameId: g.id }));
row.appendChild(abortBtn);
} else {
const resignBtn = el(
'button',
{ type: 'button', className: confirmResign ? 'btn btn-sm btn-danger' : 'btn btn-sm' },
confirmResign ? 'Confirm Resign?' : 'Resign'
);
resignBtn.addEventListener('click', () => {
if (!confirmResign) {
confirmResign = true;
renderActions(g);
if (confirmResignTimer !== null) window.clearTimeout(confirmResignTimer);
confirmResignTimer = window.setTimeout(() => {
confirmResign = false;
if (game) renderActions(game);
}, 3500);
} else {
confirmResign = false;
wsClient.send({ type: 'game:resign', gameId: g.id });
}
});
row.appendChild(resignBtn);
if (g.botLevel === null) {
const drawBtn = el(
'button',
{ type: 'button', className: 'btn btn-sm', disabled: g.drawOfferFrom === mc },
g.drawOfferFrom === mc ? 'Draw Offered' : 'Offer Draw'
);
drawBtn.addEventListener('click', () => wsClient.send({ type: 'game:draw_offer', gameId: g.id }));
row.appendChild(drawBtn);
}
}
if (!g.rated && g.movesUci.length >= 1) {
const tbBtn = el(
'button',
{ type: 'button', className: 'btn btn-sm', disabled: g.takebackOfferFrom === mc },
g.takebackOfferFrom === mc ? 'Takeback Sent' : 'Takeback'
);
tbBtn.addEventListener('click', () => wsClient.send({ type: 'game:takeback_offer', gameId: g.id }));
row.appendChild(tbBtn);
}
actionsEl.appendChild(row);
}
function renderChat(g: ActiveGameState): void {
clearNode(chatMessagesEl);
if (g.chat.length === 0) {
chatMessagesEl.appendChild(el('div', { className: 'muted small-text chat-empty' }, 'No messages yet'));
} else {
for (const m of g.chat) {
const line = el('div', { className: 'chat-line' });
line.appendChild(el('strong', { className: 'chat-author' }, `${m.username}: `));
line.appendChild(el('span', null, m.text));
chatMessagesEl.appendChild(line);
}
chatMessagesEl.scrollTop = chatMessagesEl.scrollHeight;
}
const loggedIn = ctx.getUser() !== null;
chatInput.disabled = !loggedIn;
chatSendBtn.disabled = !loggedIn;
chatInput.placeholder = loggedIn ? 'Send a message...' : 'Sign in to chat';
}
function playSoundForLastMove(g: ActiveGameState): void {
if (lastNotifiedMovesLen < 0) {
lastNotifiedMovesLen = g.movesSan.length;
return;
}
if (g.movesSan.length <= lastNotifiedMovesLen) {
lastNotifiedMovesLen = g.movesSan.length;
return;
}
lastNotifiedMovesLen = g.movesSan.length;
const san = g.movesSan[g.movesSan.length - 1] || '';
if (san.indexOf('+') >= 0 || san.indexOf('#') >= 0) {
sound.play('check');
} else if (san.indexOf('O-O') === 0) {
sound.play('castle');
} else if (san.indexOf('x') >= 0) {
sound.play('capture');
} else {
sound.play('move');
}
}
// Countdown tick for disconnect / abort banners (updates header bars without disturbing board selection/premoves)
const countdownTimer = window.setInterval(() => {
if (!game || game.finished) return;
if (game.white.disconnectDeadlineMs || game.black.disconnectDeadlineMs || (game.abortDeadlineMs && game.movesUci.length < 2)) {
updateDynamicHeaderBars(game);
}
}, 1000);
const unsub = wsClient.onMessage((msg: ServerWsMessage) => {
if (msg.type === 'game:state' && msg.game.id === gameId) {
const wasInit = game === null;
game = msg.game;
if (wasInit || viewPly >= game.movesUci.length - 1) {
viewPly = game.movesUci.length;
}
lastNotifiedMovesLen = game.movesSan.length;
if (!game.finished && myColor(game) !== null) {
ctx.setActiveGameId(game.id);
} else if (game.finished && ctx.getActiveGameId() === game.id) {
ctx.setActiveGameId(null);
}
renderLayout();
} else if (msg.type === 'game:move' && game && msg.gameId === gameId) {
const wasAtLive = viewPly === game.movesUci.length;
game.movesUci.push(msg.uci);
game.movesSan.push(msg.san);
game.moveTimesMs.push(msg.moveTimeMs);
game.fen = msg.fen;
game.turn = msg.turn;
game.whiteTimeMs = msg.whiteTimeMs;
game.blackTimeMs = msg.blackTimeMs;
game.clockRunning = msg.clockRunning;
game.abortDeadlineMs = msg.abortDeadlineMs;
if (wasAtLive) {
viewPly = game.movesUci.length;
}
playSoundForLastMove(game);
renderLayout();
} else if (msg.type === 'game:takeback' && msg.gameId === gameId) {
game = msg.game;
viewPly = game.movesUci.length;
lastNotifiedMovesLen = game.movesSan.length;
board.clearPremove();
sound.play('notify');
renderLayout();
} else if (msg.type === 'game:offers' && game && msg.gameId === gameId) {
game.drawOfferFrom = msg.drawOfferFrom;
game.takebackOfferFrom = msg.takebackOfferFrom;
game.rematchOfferFrom = msg.rematchOfferFrom;
sound.play('notify');
renderActions(game);
} else if (msg.type === 'game:presence' && game && msg.gameId === gameId) {
game.white.connected = msg.whiteConnected;
game.white.disconnectDeadlineMs = msg.whiteDisconnectDeadlineMs;
game.black.connected = msg.blackConnected;
game.black.disconnectDeadlineMs = msg.blackDisconnectDeadlineMs;
game.spectatorCount = msg.spectatorCount;
updateDynamicHeaderBars(game);
} else if (msg.type === 'game:chat' && game && msg.gameId === gameId) {
game.chat.push(msg.message);
renderChat(game);
} else if (msg.type === 'game:over' && game && msg.gameId === gameId) {
game.finished = true;
game.result = msg.result;
game.termination = msg.termination;
game.clockRunning = false;
game.abortDeadlineMs = null;
game.whiteRatingBefore = msg.whiteRatingBefore;
game.blackRatingBefore = msg.blackRatingBefore;
game.whiteRatingDiff = msg.whiteRatingDiff;
game.blackRatingDiff = msg.blackRatingDiff;
game.saved = msg.saved;
game.pgn = msg.pgn;
board.clearPremove();
if (ctx.getActiveGameId() === game.id) {
ctx.setActiveGameId(null);
}
sound.play('gameEnd');
renderLayout();
if (msg.whiteRatingDiff !== null || msg.blackRatingDiff !== null) {
ctx.refreshSession();
}
} else if (msg.type === 'game:rematch_started' && msg.oldGameId === gameId) {
ctx.setActiveGameId(msg.newGameId);
ctx.navigate(`/game/${msg.newGameId}`);
}
});
buildSkeleton();
wsClient.send({ type: 'game:subscribe', gameId });
apiRequest<
| { kind: 'active'; game: ActiveGameState }
| { kind: 'stored'; game: import('../../shared/types').StoredGame }
>(`/api/games/${encodeURIComponent(gameId)}`)
.then((resp) => {
if (destroyed || game !== null) return;
if (resp.kind === 'active') {
game = resp.game;
} else {
const s = resp.game;
game = {
id: s.id,
white: {
userId: s.whiteUserId,
username: s.whiteUsername,
rating: s.whiteRatingBefore,
provisional: false,
isBot: s.botColor === 'w',
botLevel: s.botColor === 'w' ? s.botLevel : null,
connected: false,
disconnectDeadlineMs: null
},
black: {
userId: s.blackUserId,
username: s.blackUsername,
rating: s.blackRatingBefore,
provisional: false,
isBot: s.botColor === 'b',
botLevel: s.botColor === 'b' ? s.botLevel : null,
connected: false,
disconnectDeadlineMs: null
},
initialFen: s.initialFen,
fen: s.finalFen,
movesUci: s.movesUci,
movesSan: s.movesSan,
moveTimesMs: s.moveTimesMs,
turn: s.movesUci.length % 2 === 0 ? 'w' : 'b',
initialMs: s.initialMs,
incrementMs: s.incrementMs,
category: s.category,
rated: s.rated,
botLevel: s.botLevel,
whiteTimeMs: 0,
blackTimeMs: 0,
serverTimeMs: Date.now(),
clockRunning: false,
abortDeadlineMs: null,
drawOfferFrom: null,
takebackOfferFrom: null,
rematchOfferFrom: null,
rematchGameId: null,
spectatorCount: 0,
chat: [],
finished: true,
result: s.result,
termination: s.termination,
whiteRatingBefore: s.whiteRatingBefore,
blackRatingBefore: s.blackRatingBefore,
whiteRatingDiff: s.whiteRatingDiff,
blackRatingDiff: s.blackRatingDiff,
saved: true,
pgn: s.pgn
};
}
viewPly = game.movesUci.length;
lastNotifiedMovesLen = game.movesSan.length;
renderLayout();
})
.catch((err) => {
if (destroyed || game !== null) return;
errorMsg = err instanceof Error ? err.message : 'Game not found.';
renderLayout();
});
return {
destroy() {
destroyed = true;
window.clearInterval(countdownTimer);
if (confirmResignTimer !== null) window.clearTimeout(confirmResignTimer);
unsub();
wsClient.send({ type: 'game:unsubscribe', gameId });
board.destroy();
topClock.destroy();
bottomClock.destroy();
moveList.destroy();
}
};
}