diff --git a/README.md b/README.md index 986663a..1d4eed7 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Lightweight Lichess-style chess server and Stockfish analysis web app built with ## Features -- **Simple, sharp, old-device-friendly UI**: Dark & Light themes, 4 board color palettes, inline SVG Staunton pieces, tap-to-move, 25-move premove queue, Web Audio sounds (ES2017 / Safari 12+ compatible). +- **Simple, sharp, old-device-friendly UI**: Dark & Light themes, 4 board color palettes, inline SVG Staunton pieces, tap-to-move, single premove, Web Audio sounds (ES2017 / Safari 12+ compatible). - **Accounts (no email required)**: Username + password registration (`crypto.scrypt` + `HttpOnly` session cookies). - **Glicko-2 Ratings**: Separate ratings for Bullet, Blitz, Rapid, and Classical, with rating history charts and leaderboards. - **Multiplayer & Social**: Live Open Lobby seeks, shareable invite links (`/invite/`), mutual friends, live online/in-game status, direct challenges, head-to-head records, live spectating, and in-game chat. diff --git a/src/client/components/board.ts b/src/client/components/board.ts index 9b21361..4330a95 100644 --- a/src/client/components/board.ts +++ b/src/client/components/board.ts @@ -1,11 +1,5 @@ import { Chess, algToSq, sqToAlg } from '../../shared/chess'; -import { - MAX_PREMOVES, - type QueuedPremove, - applyPremoveQueueToBoard, - computePremoveTargets, - resolveQueuedPremove -} from '../../shared/premove'; +import { type QueuedPremove, computePremoveTargets, resolveQueuedPremove } from '../../shared/premove'; import type { Color, Piece, PromotionPiece } from '../../shared/types'; import { createPieceNode } from '../pieces'; import { clearNode, el } from '../dom'; @@ -23,11 +17,7 @@ export interface BoardOptions { mode?: BoardMode; playerColor?: Color; onMove?: (uci: string) => void; - onPremoveChange?: (premoveQueueUci: string[]) => void; -} - -function premoveToUci(pm: QueuedPremove): string { - return sqToAlg(pm.from) + sqToAlg(pm.to) + (pm.promotion || ''); + onPremoveChange?: (premoveUci: string | null) => void; } export class ChessBoard { @@ -44,13 +34,13 @@ export class ChessBoard { private mode: BoardMode = 'readonly'; private playerColor: Color = 'w'; private onMoveCallback?: (uci: string) => void; - private onPremoveChangeCallback?: (premoveQueueUci: string[]) => void; + private onPremoveChangeCallback?: (premoveUci: string | null) => void; private selectedSq: number = -1; private legalTargets = new Map(); private lastMoveFrom: number = -1; private lastMoveTo: number = -1; - private premoveQueue: QueuedPremove[] = []; + private premove: QueuedPremove | null = null; private arrows: BoardArrow[] = []; private pendingPromotion: { from: number; to: number; isPremove: boolean; color: Color } | null = null; @@ -89,13 +79,7 @@ export class ChessBoard { this.grid.addEventListener('contextmenu', (e) => { e.preventDefault(); - if (this.selectedSq >= 0) { - this.selectedSq = -1; - this.legalTargets.clear(); - this.render(); - } else { - this.clearSelectionAndPremove(); - } + this.clearSelectionAndPremove(); }); this.render(); @@ -105,35 +89,17 @@ export class ChessBoard { // No global listeners to clean up in tap-tap mode } - getPremoveQueueUci(): string[] { - return this.premoveQueue.map(premoveToUci); + getPremoveUci(): string | null { + if (!this.premove) return null; + return sqToAlg(this.premove.from) + sqToAlg(this.premove.to) + (this.premove.promotion || ''); } - private setPremoveQueue(next: QueuedPremove[]): void { - const prevKey = this.premoveQueue.map(premoveToUci).join(','); - this.premoveQueue = next.slice(0, MAX_PREMOVES); - const nextList = this.getPremoveQueueUci(); - if (prevKey !== nextList.join(',') && this.onPremoveChangeCallback) { - this.onPremoveChangeCallback(nextList); - } - } - - popPremove(): void { - if (this.premoveQueue.length === 0) return; - this.selectedSq = -1; - this.legalTargets.clear(); - this.pendingPromotion = null; - this.renderPromotionPicker(); - this.setPremoveQueue(this.premoveQueue.slice(0, this.premoveQueue.length - 1)); - this.render(); - } - - clearPremove(): void { - if (this.premoveQueue.length > 0) { - this.selectedSq = -1; - this.legalTargets.clear(); - this.setPremoveQueue([]); - this.render(); + private setPremove(next: QueuedPremove | null): void { + const prevUci = this.getPremoveUci(); + this.premove = next; + const nextUci = this.getPremoveUci(); + if (prevUci !== nextUci && this.onPremoveChangeCallback) { + this.onPremoveChangeCallback(nextUci); } } @@ -149,7 +115,7 @@ export class ChessBoard { this.pendingPromotion = null; this.renderPromotionPicker(); if (mode !== 'play') { - this.setPremoveQueue([]); + this.setPremove(null); } this.render(); } @@ -174,12 +140,19 @@ export class ChessBoard { this.renderArrows(); } + clearPremove(): void { + if (this.premove) { + this.setPremove(null); + this.render(); + } + } + private clearSelectionAndPremove(): void { this.selectedSq = -1; this.legalTargets.clear(); this.pendingPromotion = null; this.renderPromotionPicker(); - this.setPremoveQueue([]); + this.setPremove(null); this.render(); } @@ -205,28 +178,18 @@ export class ChessBoard { this.pendingPromotion = null; this.renderPromotionPicker(); - // Auto-execute first queued premove when our turn arrives in play mode - if (this.mode === 'play' && this.premoveQueue.length > 0 && this.chess.turn() === this.playerColor) { - const nextPm = this.premoveQueue[0]!; - const remaining = this.premoveQueue.slice(1); - const uci = resolveQueuedPremove(this.chess, nextPm); + // Auto-execute queued premove if it's now our turn in play mode + if (this.mode === 'play' && this.premove && this.chess.turn() === this.playerColor) { + const pm = this.premove; + this.setPremove(null); + const uci = resolveQueuedPremove(this.chess, pm); if (uci) { - const applied = this.chess.moveUci(uci); - if (applied) { - this.currentFen = this.chess.fen(); - this.lastMoveFrom = applied.from; - this.lastMoveTo = applied.to; - } - this.setPremoveQueue(remaining); this.render(); if (this.onMoveCallback) { this.onMoveCallback(uci); } return; } - - // First premove became illegal -> cancel remaining queue - this.setPremoveQueue([]); } this.render(); @@ -249,13 +212,6 @@ export class ChessBoard { }; } - private getDisplayBoard(): Array { - if (this.premoveQueue.length > 0) { - return applyPremoveQueueToBoard(this.chess.board(), this.premoveQueue); - } - return this.chess.board(); - } - private isPieceInteractive(piece: Piece | null): boolean { if (!piece || this.mode === 'readonly') return false; if (this.mode === 'analyze') { @@ -270,19 +226,9 @@ export class ChessBoard { private computeTargetsForSquare(fromSq: number): Map { const map = new Map(); - - if (this.isPremoveTurn()) { - if (this.premoveQueue.length >= MAX_PREMOVES) { - return map; - } - const projected = this.getDisplayBoard(); - const piece = projected[fromSq] ?? null; - if (!piece || piece.color !== this.playerColor) return map; - return computePremoveTargets(this.chess, fromSq, this.premoveQueue); - } - const piece = this.chess.get(fromSq); if (!piece) return map; + if (this.mode === 'analyze' || this.chess.turn() === piece.color) { const legal = this.chess.legalMoves(fromSq); for (let i = 0; i < legal.length; i++) { @@ -293,47 +239,34 @@ export class ChessBoard { } map.set(m.to, list); } + return map; + } + + if (this.mode === 'play' && piece.color === this.playerColor) { + return computePremoveTargets(this.chess, fromSq); } return map; } private selectSquare(sq: number): void { - const piece = this.getDisplayBoard()[sq] ?? null; + const piece = this.chess.get(sq); if (!this.isPieceInteractive(piece)) { this.selectedSq = -1; this.legalTargets.clear(); this.render(); return; } - if (this.isPremoveTurn() && this.premoveQueue.length >= MAX_PREMOVES) { - return; - } this.selectedSq = sq; this.legalTargets = this.computeTargetsForSquare(sq); this.render(); } - private commitOwnLiveMove(uci: string): void { - const applied = this.chess.moveUci(uci); - if (applied) { - this.currentFen = this.chess.fen(); - this.lastMoveFrom = applied.from; - this.lastMoveTo = applied.to; - } - this.selectedSq = -1; - this.legalTargets.clear(); - this.render(); - if (this.onMoveCallback) { - this.onMoveCallback(uci); - } - } - private tryMoveTo(fromSq: number, toSq: number): boolean { const targets = this.computeTargetsForSquare(fromSq); if (!targets.has(toSq)) return false; - const piece = this.getDisplayBoard()[fromSq] ?? null; + const piece = this.chess.get(fromSq); if (!piece) return false; const isPremove = this.isPremoveTurn(); const promos = targets.get(toSq) || []; @@ -348,25 +281,26 @@ export class ChessBoard { } if (isPremove) { - if (this.premoveQueue.length >= MAX_PREMOVES) return false; this.selectedSq = -1; this.legalTargets.clear(); - this.setPremoveQueue(this.premoveQueue.concat([{ from: fromSq, to: toSq }])); + this.setPremove({ from: fromSq, to: toSq }); this.render(); return true; } const uci = sqToAlg(fromSq) + sqToAlg(toSq); - this.commitOwnLiveMove(uci); + this.selectedSq = -1; + this.legalTargets.clear(); + this.render(); + if (this.onMoveCallback) { + this.onMoveCallback(uci); + } return true; } private handleSquareTap(sq: number): void { if (this.mode === 'readonly' || this.pendingPromotion !== null) return; - const displayBoard = this.getDisplayBoard(); - const tappedPiece = displayBoard[sq] ?? null; - if (this.selectedSq >= 0) { if (sq === this.selectedSq) { this.selectedSq = -1; @@ -378,19 +312,19 @@ export class ChessBoard { this.tryMoveTo(this.selectedSq, sq); return; } - if (this.isPieceInteractive(tappedPiece)) { + if (this.isPieceInteractive(this.chess.get(sq))) { + this.setPremove(null); this.selectSquare(sq); return; } - this.selectedSq = -1; - this.legalTargets.clear(); - this.render(); + this.clearSelectionAndPremove(); return; } - if (this.isPieceInteractive(tappedPiece)) { + if (this.isPieceInteractive(this.chess.get(sq))) { + this.setPremove(null); this.selectSquare(sq); - } else if (this.premoveQueue.length > 0) { + } else if (this.premove) { this.clearPremove(); } } @@ -414,15 +348,12 @@ export class ChessBoard { this.pendingPromotion = null; this.promoOverlay.className = 'promo-overlay hidden'; if (pending.isPremove) { - if (this.premoveQueue.length < MAX_PREMOVES) { - this.setPremoveQueue( - this.premoveQueue.concat([{ from: pending.from, to: pending.to, promotion: pt }]) - ); - } + this.setPremove({ from: pending.from, to: pending.to, promotion: pt }); this.render(); } else { const uci = sqToAlg(pending.from) + sqToAlg(pending.to) + pt; - this.commitOwnLiveMove(uci); + this.render(); + if (this.onMoveCallback) this.onMoveCallback(uci); } }); box.appendChild(btn); @@ -445,13 +376,6 @@ export class ChessBoard { const turnInCheck = this.chess.inCheck(); const checkKingSq = turnInCheck ? this.chess.kingSquare(this.chess.turn()) : -1; const premoveTurn = this.isPremoveTurn(); - const displayBoard = this.getDisplayBoard(); - - const premoveSquares = new Set(); - for (let i = 0; i < this.premoveQueue.length; i++) { - premoveSquares.add(this.premoveQueue[i]!.from); - premoveSquares.add(this.premoveQueue[i]!.to); - } for (let vi = 0; vi < 64; vi++) { const sq = this.visualIndexToSq(vi); @@ -460,10 +384,9 @@ export class ChessBoard { const vr = vi >> 3; const vc = vi & 7; - const piece = displayBoard[sq] ?? null; + const piece = this.chess.get(sq); const isTarget = this.legalTargets.has(sq); - const isInteractive = - this.isPieceInteractive(piece) && (!premoveTurn || this.premoveQueue.length < MAX_PREMOVES); + const isInteractive = this.isPieceInteractive(piece); const isLight = ((r + c) & 1) === 0; const sqEl = this.squareEls[vi]!; @@ -474,7 +397,7 @@ export class ChessBoard { cls += premoveTurn ? ' sq-premove-selected' : ' sq-selected'; } if (sq === checkKingSq) cls += ' sq-check'; - if (premoveSquares.has(sq)) cls += ' sq-premove'; + if (this.premove && (sq === this.premove.from || sq === this.premove.to)) cls += ' sq-premove'; if (isInteractive) cls += ' sq-interactive'; if (isTarget) cls += ' sq-target'; @@ -516,11 +439,10 @@ export class ChessBoard { } const allArrows = this.arrows.slice(); - for (let i = 0; i < this.premoveQueue.length; i++) { - const pm = this.premoveQueue[i]!; + if (this.premove) { allArrows.push({ - from: sqToAlg(pm.from), - to: sqToAlg(pm.to), + from: sqToAlg(this.premove.from), + to: sqToAlg(this.premove.to), color: '#2979ff' }); } diff --git a/src/client/components/navbar.ts b/src/client/components/navbar.ts index 1cfecc2..a629552 100644 --- a/src/client/components/navbar.ts +++ b/src/client/components/navbar.ts @@ -75,14 +75,7 @@ export class Navbar { badge: state.friendBadgeCount > 0 ? state.friendBadgeCount : undefined, match: (p) => p.indexOf('/friends') === 0 }, - { href: '/leaderboard', label: 'Leaderboard', match: (p) => p.indexOf('/leaderboard') === 0 }, - { - href: state.user ? `/u/${encodeURIComponent(state.user.username)}` : '/profile', - label: 'Profile', - match: (p) => - p === '/profile' || - (state.user !== null && p.toLowerCase() === `/u/${encodeURIComponent(state.user.username)}`.toLowerCase()) - } + { href: '/leaderboard', label: 'Leaderboard', match: (p) => p.indexOf('/leaderboard') === 0 } ]; for (const item of navItems) { @@ -136,7 +129,7 @@ export class Navbar { if (state.user) { const profileLink = el( 'a', - { href: `/u/${encodeURIComponent(state.user.username)}`, className: 'btn btn-sm nav-user-link' }, + { href: `/u/${encodeURIComponent(state.user.username)}`, className: 'nav-user-link' }, state.user.username ); profileLink.addEventListener('click', (e) => { diff --git a/src/client/main.ts b/src/client/main.ts index eddaef1..b0156d3 100644 --- a/src/client/main.ts +++ b/src/client/main.ts @@ -150,12 +150,6 @@ class App { this.activeView = mountFriendsView(this.mainEl, this.ctx); } else if (pathname === '/leaderboard') { this.activeView = mountLeaderboardView(this.mainEl, this.ctx); - } else if (pathname === '/profile') { - if (this.user) { - this.activeView = mountProfileView(this.mainEl, this.ctx, this.user.username); - } else { - this.navigate('/login?next=/profile', true); - } } else if (pathname === '/analysis') { this.activeView = mountAnalysisView(this.mainEl, this.ctx); } else if (pathname.indexOf('/analysis/') === 0) { diff --git a/src/client/styles.css b/src/client/styles.css index dc642ca..da79275 100644 --- a/src/client/styles.css +++ b/src/client/styles.css @@ -222,15 +222,12 @@ a { .nav-user-link { font-weight: 600; - font-size: 12px; - max-width: 140px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + font-size: 13px; + padding: 4px 6px; } .nav-user-link:hover { - border-color: var(--accent); + text-decoration: underline; } /* Main container */ @@ -759,16 +756,8 @@ a { align-items: center; } -.profile-id { - min-width: 0; - max-width: 100%; - overflow-wrap: break-word; - margin-bottom: 6px; -} - .profile-title-row { display: flex; - flex-wrap: wrap; align-items: center; margin-bottom: 4px; } @@ -776,22 +765,6 @@ a { .profile-username { margin: 0 8px 0 0; font-size: 20px; - word-break: break-word; -} - -.table-scroll-wrap { - width: 100%; - overflow-x: auto; - -webkit-overflow-scrolling: touch; -} - -.mobile-game-meta { - display: none; -} - -.game-players-text { - overflow-wrap: break-word; - word-break: break-word; } .h2h-line { @@ -1295,12 +1268,6 @@ a { .premove-banner { border-left: 3px solid #2979ff; - flex-wrap: wrap; -} - -.premove-text { - margin-right: 8px; - word-break: break-word; } .game-meta-line { @@ -1683,33 +1650,8 @@ a { } .rating-card { - width: 48.5%; - margin-right: 3%; - } - - .rating-card:nth-child(2n) { - margin-right: 0; - } - - .rating-big { - font-size: 16px; - } - - .filter-bar > .select { - flex: 1 1 46%; - min-width: 0; - } - - .filter-bar > .filter-opp { - flex: 1 1 140px; - width: auto; - min-width: 0; - } - - .inline-pw-form > .input { - width: 100%; - flex: 1 1 100%; - margin-right: 0; + width: 49%; + margin-right: 1%; } .bot-level-card { @@ -1717,31 +1659,3 @@ a { margin-right: 0; } } - -@media (max-width: 600px) { - .profile-games-table .col-time, - .profile-games-table .col-date { - display: none; - } - - .mobile-game-meta { - display: block; - margin-top: 2px; - } - - .profile-games-table th, - .profile-games-table td { - padding: 7px 8px; - } - - .profile-games-table .col-actions .btn { - display: block; - width: 100%; - margin-left: 0; - margin-bottom: 4px; - } - - .profile-games-table .col-actions .btn:last-child { - margin-bottom: 0; - } -} diff --git a/src/client/views/analysisView.ts b/src/client/views/analysisView.ts index 6cc1cad..5a9d9db 100644 --- a/src/client/views/analysisView.ts +++ b/src/client/views/analysisView.ts @@ -37,7 +37,6 @@ export function mountAnalysisView( gameId?: string ): ViewHandle { let storedGame: StoredGame | null = null; - let unsavedAborted = false; let report: GameAnalysisReport | null = null; let loadError = ''; @@ -464,18 +463,6 @@ export function mountAnalysisView( ); const body = el('div', { className: 'card-body compact' }); - if (unsavedAborted) { - body.appendChild( - el( - 'div', - { className: 'small-text muted' }, - 'Aborted games (< 2 plies) are not saved for post-game reports, but you can explore lines with the Live Engine above.' - ) - ); - analysisControlEl.appendChild(body); - return; - } - if (!report || report.status === 'error') { if (report?.status === 'error') { body.appendChild(el('div', { className: 'alert alert-error' }, 'Previous analysis encountered an error.')); @@ -762,20 +749,7 @@ export function mountAnalysisView( .then((resp) => { if (destroyed) return; if (resp.kind === 'active') { - if (!resp.game.finished) { - loadError = 'This game is still in progress. Watch it live first!'; - updateAll(); - return; - } - unsavedAborted = true; - initialFen = resp.game.initialFen; - mainUci = resp.game.movesUci.slice(); - mainSan = resp.game.movesSan.slice(); - mainPly = mainUci.length; - rebuildMainFens(); - renderHeader(); - renderAnalysisControl(); - renderPgnPanel(); + loadError = 'This game is still in progress. Watch it live first!'; updateAll(); return; } diff --git a/src/client/views/gameView.ts b/src/client/views/gameView.ts index 5aeaa6c..c236e1e 100644 --- a/src/client/views/gameView.ts +++ b/src/client/views/gameView.ts @@ -1,5 +1,4 @@ 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'; @@ -52,8 +51,8 @@ export function mountGameView(container: HTMLElement, ctx: AppContext, gameId: s onMove(uci) { wsClient.send({ type: 'game:move', gameId, uci }); }, - onPremoveChange(premoveQueueUci) { - renderPremoveBanner(premoveQueueUci); + onPremoveChange(premoveUci) { + renderPremoveBanner(premoveUci); } }); @@ -213,37 +212,20 @@ export function mountGameView(container: HTMLElement, ctx: AppContext, gameId: s 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 { + function renderPremoveBanner(premoveUci: string | null): void { clearNode(premoveBannerEl); - if (!queueUci || queueUci.length === 0) { + if (!premoveUci || premoveUci.length < 4) { 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` : ''; + const from = premoveUci.slice(0, 2); + const to = premoveUci.slice(2, 4); + const promo = premoveUci.length === 5 ? `=${premoveUci.charAt(4).toUpperCase()}` : ''; 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); + premoveBannerEl.appendChild(el('span', null, `Premove queued: ${from} → ${to}${promo}`)); + const cancelBtn = el('button', { type: 'button', className: 'btn btn-xs' }, 'Cancel'); + cancelBtn.addEventListener('click', () => board.clearPremove()); + premoveBannerEl.appendChild(cancelBtn); } function updateDynamicHeaderBars(g: ActiveGameState): void { diff --git a/src/client/views/profileView.ts b/src/client/views/profileView.ts index 111d067..3c00eee 100644 --- a/src/client/views/profileView.ts +++ b/src/client/views/profileView.ts @@ -363,15 +363,14 @@ export function mountProfileView(container: HTMLElement, ctx: AppContext, userna if (games.length === 0) { histBody.appendChild(el('div', { className: 'empty-state' }, 'No games match the current filters.')); } else { - const tableWrap = el('div', { className: 'table-scroll-wrap' }); - const table = el('table', { className: 'data-table profile-games-table' }); + const table = el('table', { className: 'data-table' }); const thead = el('thead'); const hr = el('tr'); hr.appendChild(el('th', null, 'Players')); - hr.appendChild(el('th', { className: 'col-time' }, 'Time')); + hr.appendChild(el('th', null, 'Time')); hr.appendChild(el('th', null, 'Result')); - hr.appendChild(el('th', { className: 'col-date' }, 'Date')); - hr.appendChild(el('th', { className: 'col-right col-actions' }, 'Open')); + hr.appendChild(el('th', null, 'Date')); + hr.appendChild(el('th', { className: 'col-right' }, 'Open')); thead.appendChild(hr); table.appendChild(thead); @@ -386,31 +385,22 @@ export function mountProfileView(container: HTMLElement, ctx: AppContext, userna ? 'win' : 'loss'; - const playersTd = el('td', { className: 'col-players' }); + const playersTd = el('td'); playersTd.appendChild( el( 'div', - { className: 'game-players-text' }, + null, `${g.whiteUsername}${g.whiteRatingBefore ? ` (${g.whiteRatingBefore})` : ''} vs ${ g.blackUsername }${g.blackRatingBefore ? ` (${g.blackRatingBefore})` : ''}` ) ); - playersTd.appendChild( - el( - 'div', - { className: 'mobile-game-meta small-text muted' }, - `${formatTimeControl(g.initialMs, g.incrementMs)} · ${ - g.botLevel ? 'Bot' : g.rated ? 'Rated' : 'Casual' - } · ${formatRelativeDate(g.endedAt)}` - ) - ); tr.appendChild(playersTd); tr.appendChild( el( 'td', - { className: 'col-time' }, + null, `${formatTimeControl(g.initialMs, g.incrementMs)} · ${g.botLevel ? 'Bot' : g.rated ? 'Rated' : 'Casual'}` ) ); @@ -426,9 +416,9 @@ export function mountProfileView(container: HTMLElement, ctx: AppContext, userna resTd.appendChild(el('span', { className: 'small-text muted' }, ` ${g.termination}`)); tr.appendChild(resTd); - tr.appendChild(el('td', { className: 'small-text muted col-date' }, formatRelativeDate(g.endedAt))); + tr.appendChild(el('td', { className: 'small-text muted' }, formatRelativeDate(g.endedAt))); - const actTd = el('td', { className: 'col-right col-actions' }); + const actTd = el('td', { className: 'col-right' }); const viewBtn = el('button', { type: 'button', className: 'btn btn-xs' }, 'View'); const analyzeBtn = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Analyze'); viewBtn.addEventListener('click', () => ctx.navigate(`/game/${g.id}`)); @@ -440,8 +430,7 @@ export function mountProfileView(container: HTMLElement, ctx: AppContext, userna tbody.appendChild(tr); } table.appendChild(tbody); - tableWrap.appendChild(table); - histBody.appendChild(tableWrap); + histBody.appendChild(table); } const totalPages = Math.max(1, Math.ceil(totalGames / limit)); diff --git a/src/server/httpApi.ts b/src/server/httpApi.ts index 565705e..a7aae50 100644 --- a/src/server/httpApi.ts +++ b/src/server/httpApi.ts @@ -578,21 +578,17 @@ export function createHttpHandler(deps: { if (gameId && !segments[2] && method === 'GET') { const active = gameManager.getGameState(gameId); - if (active && !active.finished) { - sendJson(res, 200, { kind: 'active', game: active }); - return; - } - const stored = db.getGameById(gameId); - if (stored) { - const analysis = db.getAnalysis(gameId); - sendJson(res, 200, { kind: 'stored', game: stored, analysis }); - return; - } if (active) { sendJson(res, 200, { kind: 'active', game: active }); return; } - sendJson(res, 404, { error: 'Game not found.' }); + const stored = db.getGameById(gameId); + if (!stored) { + sendJson(res, 404, { error: 'Game not found.' }); + return; + } + const analysis = db.getAnalysis(gameId); + sendJson(res, 200, { kind: 'stored', game: stored, analysis }); return; } } diff --git a/src/shared/premove.ts b/src/shared/premove.ts index 88cb37c..836cbd5 100644 --- a/src/shared/premove.ts +++ b/src/shared/premove.ts @@ -1,7 +1,5 @@ import { Chess, sqToAlg } from './chess'; -import type { Piece, PromotionPiece } from './types'; - -export const MAX_PREMOVES = 25; +import type { PromotionPiece } from './types'; export interface QueuedPremove { from: number; @@ -11,59 +9,9 @@ export interface QueuedPremove { const PROMO_LIST: PromotionPiece[] = ['q', 'r', 'b', 'n']; -export function applyPremoveQueueToBoard( - baseBoard: ReadonlyArray, - queue: ReadonlyArray -): Array { - const board: Array = new Array(64); - for (let i = 0; i < 64; i++) { - const p = baseBoard[i]; - board[i] = p ? { color: p.color, type: p.type } : null; - } - - for (let i = 0; i < queue.length; i++) { - const pm = queue[i]!; - const moving = board[pm.from]; - if (!moving) break; - - if (moving.type === 'k' && Math.abs((pm.to & 7) - (pm.from & 7)) === 2) { - if (pm.from === 60 && pm.to === 62 && board[63]?.color === moving.color && board[63]?.type === 'r') { - board[61] = board[63]!; - board[63] = null; - } else if (pm.from === 60 && pm.to === 58 && board[56]?.color === moving.color && board[56]?.type === 'r') { - board[59] = board[56]!; - board[56] = null; - } else if (pm.from === 4 && pm.to === 6 && board[7]?.color === moving.color && board[7]?.type === 'r') { - board[5] = board[7]!; - board[7] = null; - } else if (pm.from === 4 && pm.to === 2 && board[0]?.color === moving.color && board[0]?.type === 'r') { - board[3] = board[0]!; - board[0] = null; - } - } - - board[pm.to] = pm.promotion ? { color: moving.color, type: pm.promotion } : moving; - board[pm.from] = null; - } - - return board; -} - -function hasMovedInQueue(queue: ReadonlyArray, sq: number): boolean { - for (let i = 0; i < queue.length; i++) { - if (queue[i]!.from === sq || queue[i]!.to === sq) return true; - } - return false; -} - -export function computePremoveTargets( - chess: Chess, - fromSq: number, - queue: ReadonlyArray = [] -): Map { +export function computePremoveTargets(chess: Chess, fromSq: number): Map { const map = new Map(); - const projected = queue.length > 0 ? applyPremoveQueueToBoard(chess.board(), queue) : chess.board(); - const piece = projected[fromSq]; + const piece = chess.get(fromSq); if (!piece) return map; const r = fromSq >> 3; @@ -102,12 +50,12 @@ export function computePremoveTargets( if (adr <= 1 && adc <= 1) { ok = true; } else if (dr === 0 && adc === 2) { - if (piece.color === 'w' && r === 7 && c === 4 && !hasMovedInQueue(queue, 60)) { - if (tc === 6 && castlingField.indexOf('K') >= 0 && !hasMovedInQueue(queue, 63)) ok = true; - if (tc === 2 && castlingField.indexOf('Q') >= 0 && !hasMovedInQueue(queue, 56)) ok = true; - } else if (piece.color === 'b' && r === 0 && c === 4 && !hasMovedInQueue(queue, 4)) { - if (tc === 6 && castlingField.indexOf('k') >= 0 && !hasMovedInQueue(queue, 7)) ok = true; - if (tc === 2 && castlingField.indexOf('q') >= 0 && !hasMovedInQueue(queue, 0)) ok = true; + if (piece.color === 'w' && r === 7 && c === 4) { + if (tc === 6 && castlingField.indexOf('K') >= 0) ok = true; + if (tc === 2 && castlingField.indexOf('Q') >= 0) ok = true; + } else if (piece.color === 'b' && r === 0 && c === 4) { + if (tc === 6 && castlingField.indexOf('k') >= 0) ok = true; + if (tc === 2 && castlingField.indexOf('q') >= 0) ok = true; } } } diff --git a/tests/premove.test.ts b/tests/premove.test.ts index 3292b8d..00b2187 100644 --- a/tests/premove.test.ts +++ b/tests/premove.test.ts @@ -1,17 +1,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { Chess, algToSq } from '../src/shared/chess'; -import { - MAX_PREMOVES, - type QueuedPremove, - applyPremoveQueueToBoard, - computePremoveTargets, - resolveQueuedPremove -} from '../src/shared/premove'; - -test('MAX_PREMOVES is 25', () => { - assert.equal(MAX_PREMOVES, 25); -}); +import { computePremoveTargets, resolveQueuedPremove } from '../src/shared/premove'; test('Pawn premove targets include 1-step, 2-step from start, diagonal captures, and promotions', () => { const c = new Chess('rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1'); @@ -29,30 +19,11 @@ test('Pawn premove targets include 1-step, 2-step from start, diagonal captures, assert.deepEqual(c7Targets.get(algToSq('d8')), ['q', 'r', 'b', 'n']); }); -test('Chained multi-premove targets project board state across consecutive moves', () => { - const c = new Chess('rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1'); - const queue: QueuedPremove[] = [ - { from: algToSq('d2'), to: algToSq('d4') }, - { from: algToSq('d4'), to: algToSq('d5') } - ]; - - // After queueing d2->d4 and d4->d5, pawn is projected at d5 and d2 is empty - const projected = applyPremoveQueueToBoard(c.board(), queue); - assert.equal(projected[algToSq('d2')], null); - assert.deepEqual(projected[algToSq('d5')], { color: 'w', type: 'p' }); - - // From d5, pawn can premove d6 (1-step), c6, e6 — NOT d7 (2-step only from start rank) - const d5Targets = computePremoveTargets(c, algToSq('d5'), queue); - assert.equal(d5Targets.has(algToSq('d6')), true); - assert.equal(d5Targets.has(algToSq('c6')), true); - assert.equal(d5Targets.has(algToSq('e6')), true); - assert.equal(d5Targets.has(algToSq('d7')), false); -}); - test('Slider premove targets ignore blockers and resolve recapture when turn returns', () => { // Black to move: Black bishop on g4 can take White knight on f3; White queen on d1 premoves Qxf3 const c = new Chess('r2qkbnr/ppp2ppp/2np4/4p3/4P1b1/3P1N2/PPP2PPP/RNBQKB1R b KQkq - 0 4'); const qTargets = computePremoveTargets(c, algToSq('d1')); + // Even though f3 is currently occupied by own knight and e2 is occupied by own pawn, queen can premove d1->f3 and d1->h5 assert.equal(qTargets.has(algToSq('f3')), true); assert.equal(qTargets.has(algToSq('h5')), true); @@ -68,31 +39,12 @@ test('Slider premove targets ignore blockers and resolve recapture when turn ret assert.equal(dropped, null); }); -test('King castling in premove queue moves rook on projected board and disables repeat castling', () => { +test('King castling premove targets respect FEN castling rights and check resolution', () => { const withRights = new Chess('r3k2r/8/8/8/8/8/8/R3K2R b KQkq - 0 1'); const kTargets = computePremoveTargets(withRights, algToSq('e1')); assert.equal(kTargets.has(algToSq('g1')), true); assert.equal(kTargets.has(algToSq('c1')), true); - // Queue O-O (e1->g1): projected board places White king on g1 and White rook on f1 - const queueAfterCastle: QueuedPremove[] = [{ from: algToSq('e1'), to: algToSq('g1') }]; - const projected = applyPremoveQueueToBoard(withRights.board(), queueAfterCastle); - assert.deepEqual(projected[algToSq('g1')], { color: 'w', type: 'k' }); - assert.deepEqual(projected[algToSq('f1')], { color: 'w', type: 'r' }); - assert.equal(projected[algToSq('h1')], null); - - // Rook on f1 can now premove along the f-file - const f1Targets = computePremoveTargets(withRights, algToSq('f1'), queueAfterCastle); - assert.equal(f1Targets.has(algToSq('f8')), true); - - // Once king moves in queue, e1->c1 castling is no longer offered even if projected back - const movedBackQueue: QueuedPremove[] = [ - { from: algToSq('e1'), to: algToSq('f1') }, - { from: algToSq('f1'), to: algToSq('e1') } - ]; - const e1AfterMove = computePremoveTargets(withRights, algToSq('e1'), movedBackQueue); - assert.equal(e1AfterMove.has(algToSq('g1')), false); - const noRights = new Chess('r3k2r/8/8/8/8/8/8/R3K2R b - - 0 1'); const kNoTargets = computePremoveTargets(noRights, algToSq('e1')); assert.equal(kNoTargets.has(algToSq('g1')), false); @@ -102,23 +54,3 @@ test('King castling in premove queue moves rook on projected board and disables const checkGame = new Chess('4k3/8/8/8/8/8/4P3/4K2r w - - 0 1'); assert.equal(resolveQueuedPremove(checkGame, { from: algToSq('e2'), to: algToSq('e4') }), null); }); - -test('Multi-premove queue can queue 25 moves and executes sequentially until completion or illegality', () => { - const c = new Chess('4k3/8/8/8/8/8/R7/4K3 b - - 0 1'); - const queue: QueuedPremove[] = []; - for (let i = 0; i < MAX_PREMOVES; i++) { - queue.push(i % 2 === 0 ? { from: algToSq('a2'), to: algToSq('a3') } : { from: algToSq('a3'), to: algToSq('a2') }); - } - assert.equal(queue.length, 25); - - // Black plays Ke7 -> White executes premove 0 (a2->a3) -> Black plays Kd7 -> White executes premove 1 (a3->a2) - assert.ok(c.moveSan('Ke7')); - const uci0 = resolveQueuedPremove(c, queue[0]!); - assert.equal(uci0, 'a2a3'); - assert.ok(c.moveUci(uci0!)); - - assert.ok(c.moveSan('Kd7')); - const uci1 = resolveQueuedPremove(c, queue[1]!); - assert.equal(uci1, 'a3a2'); - assert.ok(c.moveUci(uci1!)); -}); diff --git a/tests/server.test.ts b/tests/server.test.ts index 8d4fd83..a41449f 100644 --- a/tests/server.test.ts +++ b/tests/server.test.ts @@ -259,7 +259,6 @@ test('ChessUp full server E2E: auth, lobby, PvP, Glicko-2, Stockfish analysis, b // Check REST history, PGN, leaderboard const storedRes = await alice.req<{ kind: string; game: { result: string } }>(`/api/games/${pvpGameId}`); assert.equal(storedRes.status, 200); - assert.equal(storedRes.data.kind, 'stored'); assert.equal(storedRes.data.game.result, '1-0'); const pgnRes = await alice.req(`/api/games/${pvpGameId}/pgn`);