Compare commits

..

No commits in common. "14263d3c32d9f8d0c5c245e55ab7877ed4b8b04f" and "02b8bafb1ec8f9cf4d735a744d189ff61238eaf9" have entirely different histories.

12 changed files with 107 additions and 464 deletions

View file

@ -4,7 +4,7 @@ Lightweight Lichess-style chess server and Stockfish analysis web app built with
## Features ## 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). - **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. - **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/<token>`), mutual friends, live online/in-game status, direct challenges, head-to-head records, live spectating, and in-game chat. - **Multiplayer & Social**: Live Open Lobby seeks, shareable invite links (`/invite/<token>`), mutual friends, live online/in-game status, direct challenges, head-to-head records, live spectating, and in-game chat.

View file

@ -1,11 +1,5 @@
import { Chess, algToSq, sqToAlg } from '../../shared/chess'; import { Chess, algToSq, sqToAlg } from '../../shared/chess';
import { import { type QueuedPremove, computePremoveTargets, resolveQueuedPremove } from '../../shared/premove';
MAX_PREMOVES,
type QueuedPremove,
applyPremoveQueueToBoard,
computePremoveTargets,
resolveQueuedPremove
} from '../../shared/premove';
import type { Color, Piece, PromotionPiece } from '../../shared/types'; import type { Color, Piece, PromotionPiece } from '../../shared/types';
import { createPieceNode } from '../pieces'; import { createPieceNode } from '../pieces';
import { clearNode, el } from '../dom'; import { clearNode, el } from '../dom';
@ -23,11 +17,7 @@ export interface BoardOptions {
mode?: BoardMode; mode?: BoardMode;
playerColor?: Color; playerColor?: Color;
onMove?: (uci: string) => void; onMove?: (uci: string) => void;
onPremoveChange?: (premoveQueueUci: string[]) => void; onPremoveChange?: (premoveUci: string | null) => void;
}
function premoveToUci(pm: QueuedPremove): string {
return sqToAlg(pm.from) + sqToAlg(pm.to) + (pm.promotion || '');
} }
export class ChessBoard { export class ChessBoard {
@ -44,13 +34,13 @@ export class ChessBoard {
private mode: BoardMode = 'readonly'; private mode: BoardMode = 'readonly';
private playerColor: Color = 'w'; private playerColor: Color = 'w';
private onMoveCallback?: (uci: string) => void; private onMoveCallback?: (uci: string) => void;
private onPremoveChangeCallback?: (premoveQueueUci: string[]) => void; private onPremoveChangeCallback?: (premoveUci: string | null) => void;
private selectedSq: number = -1; private selectedSq: number = -1;
private legalTargets = new Map<number, PromotionPiece[]>(); private legalTargets = new Map<number, PromotionPiece[]>();
private lastMoveFrom: number = -1; private lastMoveFrom: number = -1;
private lastMoveTo: number = -1; private lastMoveTo: number = -1;
private premoveQueue: QueuedPremove[] = []; private premove: QueuedPremove | null = null;
private arrows: BoardArrow[] = []; private arrows: BoardArrow[] = [];
private pendingPromotion: { from: number; to: number; isPremove: boolean; color: Color } | null = null; private pendingPromotion: { from: number; to: number; isPremove: boolean; color: Color } | null = null;
@ -89,13 +79,7 @@ export class ChessBoard {
this.grid.addEventListener('contextmenu', (e) => { this.grid.addEventListener('contextmenu', (e) => {
e.preventDefault(); e.preventDefault();
if (this.selectedSq >= 0) { this.clearSelectionAndPremove();
this.selectedSq = -1;
this.legalTargets.clear();
this.render();
} else {
this.clearSelectionAndPremove();
}
}); });
this.render(); this.render();
@ -105,35 +89,17 @@ export class ChessBoard {
// No global listeners to clean up in tap-tap mode // No global listeners to clean up in tap-tap mode
} }
getPremoveQueueUci(): string[] { getPremoveUci(): string | null {
return this.premoveQueue.map(premoveToUci); if (!this.premove) return null;
return sqToAlg(this.premove.from) + sqToAlg(this.premove.to) + (this.premove.promotion || '');
} }
private setPremoveQueue(next: QueuedPremove[]): void { private setPremove(next: QueuedPremove | null): void {
const prevKey = this.premoveQueue.map(premoveToUci).join(','); const prevUci = this.getPremoveUci();
this.premoveQueue = next.slice(0, MAX_PREMOVES); this.premove = next;
const nextList = this.getPremoveQueueUci(); const nextUci = this.getPremoveUci();
if (prevKey !== nextList.join(',') && this.onPremoveChangeCallback) { if (prevUci !== nextUci && this.onPremoveChangeCallback) {
this.onPremoveChangeCallback(nextList); this.onPremoveChangeCallback(nextUci);
}
}
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();
} }
} }
@ -149,7 +115,7 @@ export class ChessBoard {
this.pendingPromotion = null; this.pendingPromotion = null;
this.renderPromotionPicker(); this.renderPromotionPicker();
if (mode !== 'play') { if (mode !== 'play') {
this.setPremoveQueue([]); this.setPremove(null);
} }
this.render(); this.render();
} }
@ -174,12 +140,19 @@ export class ChessBoard {
this.renderArrows(); this.renderArrows();
} }
clearPremove(): void {
if (this.premove) {
this.setPremove(null);
this.render();
}
}
private clearSelectionAndPremove(): void { private clearSelectionAndPremove(): void {
this.selectedSq = -1; this.selectedSq = -1;
this.legalTargets.clear(); this.legalTargets.clear();
this.pendingPromotion = null; this.pendingPromotion = null;
this.renderPromotionPicker(); this.renderPromotionPicker();
this.setPremoveQueue([]); this.setPremove(null);
this.render(); this.render();
} }
@ -205,28 +178,18 @@ export class ChessBoard {
this.pendingPromotion = null; this.pendingPromotion = null;
this.renderPromotionPicker(); this.renderPromotionPicker();
// Auto-execute first queued premove when our turn arrives in play mode // Auto-execute queued premove if it's now our turn in play mode
if (this.mode === 'play' && this.premoveQueue.length > 0 && this.chess.turn() === this.playerColor) { if (this.mode === 'play' && this.premove && this.chess.turn() === this.playerColor) {
const nextPm = this.premoveQueue[0]!; const pm = this.premove;
const remaining = this.premoveQueue.slice(1); this.setPremove(null);
const uci = resolveQueuedPremove(this.chess, nextPm); const uci = resolveQueuedPremove(this.chess, pm);
if (uci) { 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(); this.render();
if (this.onMoveCallback) { if (this.onMoveCallback) {
this.onMoveCallback(uci); this.onMoveCallback(uci);
} }
return; return;
} }
// First premove became illegal -> cancel remaining queue
this.setPremoveQueue([]);
} }
this.render(); this.render();
@ -249,13 +212,6 @@ export class ChessBoard {
}; };
} }
private getDisplayBoard(): Array<Piece | null> {
if (this.premoveQueue.length > 0) {
return applyPremoveQueueToBoard(this.chess.board(), this.premoveQueue);
}
return this.chess.board();
}
private isPieceInteractive(piece: Piece | null): boolean { private isPieceInteractive(piece: Piece | null): boolean {
if (!piece || this.mode === 'readonly') return false; if (!piece || this.mode === 'readonly') return false;
if (this.mode === 'analyze') { if (this.mode === 'analyze') {
@ -270,19 +226,9 @@ export class ChessBoard {
private computeTargetsForSquare(fromSq: number): Map<number, PromotionPiece[]> { private computeTargetsForSquare(fromSq: number): Map<number, PromotionPiece[]> {
const map = new Map<number, PromotionPiece[]>(); const map = new Map<number, PromotionPiece[]>();
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); const piece = this.chess.get(fromSq);
if (!piece) return map; if (!piece) return map;
if (this.mode === 'analyze' || this.chess.turn() === piece.color) { if (this.mode === 'analyze' || this.chess.turn() === piece.color) {
const legal = this.chess.legalMoves(fromSq); const legal = this.chess.legalMoves(fromSq);
for (let i = 0; i < legal.length; i++) { for (let i = 0; i < legal.length; i++) {
@ -293,47 +239,34 @@ export class ChessBoard {
} }
map.set(m.to, list); map.set(m.to, list);
} }
return map;
}
if (this.mode === 'play' && piece.color === this.playerColor) {
return computePremoveTargets(this.chess, fromSq);
} }
return map; return map;
} }
private selectSquare(sq: number): void { private selectSquare(sq: number): void {
const piece = this.getDisplayBoard()[sq] ?? null; const piece = this.chess.get(sq);
if (!this.isPieceInteractive(piece)) { if (!this.isPieceInteractive(piece)) {
this.selectedSq = -1; this.selectedSq = -1;
this.legalTargets.clear(); this.legalTargets.clear();
this.render(); this.render();
return; return;
} }
if (this.isPremoveTurn() && this.premoveQueue.length >= MAX_PREMOVES) {
return;
}
this.selectedSq = sq; this.selectedSq = sq;
this.legalTargets = this.computeTargetsForSquare(sq); this.legalTargets = this.computeTargetsForSquare(sq);
this.render(); 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 { private tryMoveTo(fromSq: number, toSq: number): boolean {
const targets = this.computeTargetsForSquare(fromSq); const targets = this.computeTargetsForSquare(fromSq);
if (!targets.has(toSq)) return false; if (!targets.has(toSq)) return false;
const piece = this.getDisplayBoard()[fromSq] ?? null; const piece = this.chess.get(fromSq);
if (!piece) return false; if (!piece) return false;
const isPremove = this.isPremoveTurn(); const isPremove = this.isPremoveTurn();
const promos = targets.get(toSq) || []; const promos = targets.get(toSq) || [];
@ -348,25 +281,26 @@ export class ChessBoard {
} }
if (isPremove) { if (isPremove) {
if (this.premoveQueue.length >= MAX_PREMOVES) return false;
this.selectedSq = -1; this.selectedSq = -1;
this.legalTargets.clear(); this.legalTargets.clear();
this.setPremoveQueue(this.premoveQueue.concat([{ from: fromSq, to: toSq }])); this.setPremove({ from: fromSq, to: toSq });
this.render(); this.render();
return true; return true;
} }
const uci = sqToAlg(fromSq) + sqToAlg(toSq); 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; return true;
} }
private handleSquareTap(sq: number): void { private handleSquareTap(sq: number): void {
if (this.mode === 'readonly' || this.pendingPromotion !== null) return; if (this.mode === 'readonly' || this.pendingPromotion !== null) return;
const displayBoard = this.getDisplayBoard();
const tappedPiece = displayBoard[sq] ?? null;
if (this.selectedSq >= 0) { if (this.selectedSq >= 0) {
if (sq === this.selectedSq) { if (sq === this.selectedSq) {
this.selectedSq = -1; this.selectedSq = -1;
@ -378,19 +312,19 @@ export class ChessBoard {
this.tryMoveTo(this.selectedSq, sq); this.tryMoveTo(this.selectedSq, sq);
return; return;
} }
if (this.isPieceInteractive(tappedPiece)) { if (this.isPieceInteractive(this.chess.get(sq))) {
this.setPremove(null);
this.selectSquare(sq); this.selectSquare(sq);
return; return;
} }
this.selectedSq = -1; this.clearSelectionAndPremove();
this.legalTargets.clear();
this.render();
return; return;
} }
if (this.isPieceInteractive(tappedPiece)) { if (this.isPieceInteractive(this.chess.get(sq))) {
this.setPremove(null);
this.selectSquare(sq); this.selectSquare(sq);
} else if (this.premoveQueue.length > 0) { } else if (this.premove) {
this.clearPremove(); this.clearPremove();
} }
} }
@ -414,15 +348,12 @@ export class ChessBoard {
this.pendingPromotion = null; this.pendingPromotion = null;
this.promoOverlay.className = 'promo-overlay hidden'; this.promoOverlay.className = 'promo-overlay hidden';
if (pending.isPremove) { if (pending.isPremove) {
if (this.premoveQueue.length < MAX_PREMOVES) { this.setPremove({ from: pending.from, to: pending.to, promotion: pt });
this.setPremoveQueue(
this.premoveQueue.concat([{ from: pending.from, to: pending.to, promotion: pt }])
);
}
this.render(); this.render();
} else { } else {
const uci = sqToAlg(pending.from) + sqToAlg(pending.to) + pt; const uci = sqToAlg(pending.from) + sqToAlg(pending.to) + pt;
this.commitOwnLiveMove(uci); this.render();
if (this.onMoveCallback) this.onMoveCallback(uci);
} }
}); });
box.appendChild(btn); box.appendChild(btn);
@ -445,13 +376,6 @@ export class ChessBoard {
const turnInCheck = this.chess.inCheck(); const turnInCheck = this.chess.inCheck();
const checkKingSq = turnInCheck ? this.chess.kingSquare(this.chess.turn()) : -1; const checkKingSq = turnInCheck ? this.chess.kingSquare(this.chess.turn()) : -1;
const premoveTurn = this.isPremoveTurn(); const premoveTurn = this.isPremoveTurn();
const displayBoard = this.getDisplayBoard();
const premoveSquares = new Set<number>();
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++) { for (let vi = 0; vi < 64; vi++) {
const sq = this.visualIndexToSq(vi); const sq = this.visualIndexToSq(vi);
@ -460,10 +384,9 @@ export class ChessBoard {
const vr = vi >> 3; const vr = vi >> 3;
const vc = vi & 7; const vc = vi & 7;
const piece = displayBoard[sq] ?? null; const piece = this.chess.get(sq);
const isTarget = this.legalTargets.has(sq); const isTarget = this.legalTargets.has(sq);
const isInteractive = const isInteractive = this.isPieceInteractive(piece);
this.isPieceInteractive(piece) && (!premoveTurn || this.premoveQueue.length < MAX_PREMOVES);
const isLight = ((r + c) & 1) === 0; const isLight = ((r + c) & 1) === 0;
const sqEl = this.squareEls[vi]!; const sqEl = this.squareEls[vi]!;
@ -474,7 +397,7 @@ export class ChessBoard {
cls += premoveTurn ? ' sq-premove-selected' : ' sq-selected'; cls += premoveTurn ? ' sq-premove-selected' : ' sq-selected';
} }
if (sq === checkKingSq) cls += ' sq-check'; 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 (isInteractive) cls += ' sq-interactive';
if (isTarget) cls += ' sq-target'; if (isTarget) cls += ' sq-target';
@ -516,11 +439,10 @@ export class ChessBoard {
} }
const allArrows = this.arrows.slice(); const allArrows = this.arrows.slice();
for (let i = 0; i < this.premoveQueue.length; i++) { if (this.premove) {
const pm = this.premoveQueue[i]!;
allArrows.push({ allArrows.push({
from: sqToAlg(pm.from), from: sqToAlg(this.premove.from),
to: sqToAlg(pm.to), to: sqToAlg(this.premove.to),
color: '#2979ff' color: '#2979ff'
}); });
} }

View file

@ -75,14 +75,7 @@ export class Navbar {
badge: state.friendBadgeCount > 0 ? state.friendBadgeCount : undefined, badge: state.friendBadgeCount > 0 ? state.friendBadgeCount : undefined,
match: (p) => p.indexOf('/friends') === 0 match: (p) => p.indexOf('/friends') === 0
}, },
{ href: '/leaderboard', label: 'Leaderboard', match: (p) => p.indexOf('/leaderboard') === 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())
}
]; ];
for (const item of navItems) { for (const item of navItems) {
@ -136,7 +129,7 @@ export class Navbar {
if (state.user) { if (state.user) {
const profileLink = el( const profileLink = el(
'a', '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 state.user.username
); );
profileLink.addEventListener('click', (e) => { profileLink.addEventListener('click', (e) => {

View file

@ -150,12 +150,6 @@ class App {
this.activeView = mountFriendsView(this.mainEl, this.ctx); this.activeView = mountFriendsView(this.mainEl, this.ctx);
} else if (pathname === '/leaderboard') { } else if (pathname === '/leaderboard') {
this.activeView = mountLeaderboardView(this.mainEl, this.ctx); 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') { } else if (pathname === '/analysis') {
this.activeView = mountAnalysisView(this.mainEl, this.ctx); this.activeView = mountAnalysisView(this.mainEl, this.ctx);
} else if (pathname.indexOf('/analysis/') === 0) { } else if (pathname.indexOf('/analysis/') === 0) {

View file

@ -222,15 +222,12 @@ a {
.nav-user-link { .nav-user-link {
font-weight: 600; font-weight: 600;
font-size: 12px; font-size: 13px;
max-width: 140px; padding: 4px 6px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
} }
.nav-user-link:hover { .nav-user-link:hover {
border-color: var(--accent); text-decoration: underline;
} }
/* Main container */ /* Main container */
@ -759,16 +756,8 @@ a {
align-items: center; align-items: center;
} }
.profile-id {
min-width: 0;
max-width: 100%;
overflow-wrap: break-word;
margin-bottom: 6px;
}
.profile-title-row { .profile-title-row {
display: flex; display: flex;
flex-wrap: wrap;
align-items: center; align-items: center;
margin-bottom: 4px; margin-bottom: 4px;
} }
@ -776,22 +765,6 @@ a {
.profile-username { .profile-username {
margin: 0 8px 0 0; margin: 0 8px 0 0;
font-size: 20px; 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 { .h2h-line {
@ -1295,12 +1268,6 @@ a {
.premove-banner { .premove-banner {
border-left: 3px solid #2979ff; border-left: 3px solid #2979ff;
flex-wrap: wrap;
}
.premove-text {
margin-right: 8px;
word-break: break-word;
} }
.game-meta-line { .game-meta-line {
@ -1683,33 +1650,8 @@ a {
} }
.rating-card { .rating-card {
width: 48.5%; width: 49%;
margin-right: 3%; margin-right: 1%;
}
.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;
} }
.bot-level-card { .bot-level-card {
@ -1717,31 +1659,3 @@ a {
margin-right: 0; 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;
}
}

View file

@ -37,7 +37,6 @@ export function mountAnalysisView(
gameId?: string gameId?: string
): ViewHandle { ): ViewHandle {
let storedGame: StoredGame | null = null; let storedGame: StoredGame | null = null;
let unsavedAborted = false;
let report: GameAnalysisReport | null = null; let report: GameAnalysisReport | null = null;
let loadError = ''; let loadError = '';
@ -464,18 +463,6 @@ export function mountAnalysisView(
); );
const body = el('div', { className: 'card-body compact' }); 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 || report.status === 'error') {
if (report?.status === 'error') { if (report?.status === 'error') {
body.appendChild(el('div', { className: 'alert alert-error' }, 'Previous analysis encountered an error.')); body.appendChild(el('div', { className: 'alert alert-error' }, 'Previous analysis encountered an error.'));
@ -762,20 +749,7 @@ export function mountAnalysisView(
.then((resp) => { .then((resp) => {
if (destroyed) return; if (destroyed) return;
if (resp.kind === 'active') { if (resp.kind === 'active') {
if (!resp.game.finished) { loadError = 'This game is still in progress. Watch it live first!';
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();
updateAll(); updateAll();
return; return;
} }

View file

@ -1,5 +1,4 @@
import { Chess } from '../../shared/chess'; import { Chess } from '../../shared/chess';
import { MAX_PREMOVES } from '../../shared/premove';
import { categoryLabel, formatTimeControl } from '../../shared/timeControl'; import { categoryLabel, formatTimeControl } from '../../shared/timeControl';
import type { ActiveGameState, Color, ServerWsMessage } from '../../shared/types'; import type { ActiveGameState, Color, ServerWsMessage } from '../../shared/types';
import { apiRequest, wsClient } from '../api'; import { apiRequest, wsClient } from '../api';
@ -52,8 +51,8 @@ export function mountGameView(container: HTMLElement, ctx: AppContext, gameId: s
onMove(uci) { onMove(uci) {
wsClient.send({ type: 'game:move', gameId, uci }); wsClient.send({ type: 'game:move', gameId, uci });
}, },
onPremoveChange(premoveQueueUci) { onPremoveChange(premoveUci) {
renderPremoveBanner(premoveQueueUci); renderPremoveBanner(premoveUci);
} }
}); });
@ -213,37 +212,20 @@ export function mountGameView(container: HTMLElement, ctx: AppContext, gameId: s
clock.update(ms, g.clockRunning && isTurn, g.category === 'unlimited'); clock.update(ms, g.clockRunning && isTurn, g.category === 'unlimited');
} }
function formatPremoveStep(uci: string): string { function renderPremoveBanner(premoveUci: string | null): void {
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); clearNode(premoveBannerEl);
if (!queueUci || queueUci.length === 0) { if (!premoveUci || premoveUci.length < 4) {
premoveBannerEl.className = 'premove-banner hidden'; premoveBannerEl.className = 'premove-banner hidden';
return; return;
} }
const maxPreview = 5; const from = premoveUci.slice(0, 2);
const formatted = queueUci.slice(0, maxPreview).map(formatPremoveStep).join(', '); const to = premoveUci.slice(2, 4);
const suffix = queueUci.length > maxPreview ? `, +${queueUci.length - maxPreview} more` : ''; const promo = premoveUci.length === 5 ? `=${premoveUci.charAt(4).toUpperCase()}` : '';
premoveBannerEl.className = 'premove-banner'; premoveBannerEl.className = 'premove-banner';
premoveBannerEl.appendChild( premoveBannerEl.appendChild(el('span', null, `Premove queued: ${from} → ${to}${promo}`));
el('span', { className: 'premove-text' }, `Premoves (${queueUci.length}/${MAX_PREMOVES}): ${formatted}${suffix}`) const cancelBtn = el('button', { type: 'button', className: 'btn btn-xs' }, 'Cancel');
); cancelBtn.addEventListener('click', () => board.clearPremove());
premoveBannerEl.appendChild(cancelBtn);
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 { function updateDynamicHeaderBars(g: ActiveGameState): void {

View file

@ -363,15 +363,14 @@ export function mountProfileView(container: HTMLElement, ctx: AppContext, userna
if (games.length === 0) { if (games.length === 0) {
histBody.appendChild(el('div', { className: 'empty-state' }, 'No games match the current filters.')); histBody.appendChild(el('div', { className: 'empty-state' }, 'No games match the current filters.'));
} else { } else {
const tableWrap = el('div', { className: 'table-scroll-wrap' }); const table = el('table', { className: 'data-table' });
const table = el('table', { className: 'data-table profile-games-table' });
const thead = el('thead'); const thead = el('thead');
const hr = el('tr'); const hr = el('tr');
hr.appendChild(el('th', null, 'Players')); 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', null, 'Result'));
hr.appendChild(el('th', { className: 'col-date' }, 'Date')); hr.appendChild(el('th', null, 'Date'));
hr.appendChild(el('th', { className: 'col-right col-actions' }, 'Open')); hr.appendChild(el('th', { className: 'col-right' }, 'Open'));
thead.appendChild(hr); thead.appendChild(hr);
table.appendChild(thead); table.appendChild(thead);
@ -386,31 +385,22 @@ export function mountProfileView(container: HTMLElement, ctx: AppContext, userna
? 'win' ? 'win'
: 'loss'; : 'loss';
const playersTd = el('td', { className: 'col-players' }); const playersTd = el('td');
playersTd.appendChild( playersTd.appendChild(
el( el(
'div', 'div',
{ className: 'game-players-text' }, null,
`${g.whiteUsername}${g.whiteRatingBefore ? ` (${g.whiteRatingBefore})` : ''} vs ${ `${g.whiteUsername}${g.whiteRatingBefore ? ` (${g.whiteRatingBefore})` : ''} vs ${
g.blackUsername g.blackUsername
}${g.blackRatingBefore ? ` (${g.blackRatingBefore})` : ''}` }${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(playersTd);
tr.appendChild( tr.appendChild(
el( el(
'td', 'td',
{ className: 'col-time' }, null,
`${formatTimeControl(g.initialMs, g.incrementMs)} · ${g.botLevel ? 'Bot' : g.rated ? 'Rated' : 'Casual'}` `${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}`)); resTd.appendChild(el('span', { className: 'small-text muted' }, ` ${g.termination}`));
tr.appendChild(resTd); 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 viewBtn = el('button', { type: 'button', className: 'btn btn-xs' }, 'View');
const analyzeBtn = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Analyze'); const analyzeBtn = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Analyze');
viewBtn.addEventListener('click', () => ctx.navigate(`/game/${g.id}`)); viewBtn.addEventListener('click', () => ctx.navigate(`/game/${g.id}`));
@ -440,8 +430,7 @@ export function mountProfileView(container: HTMLElement, ctx: AppContext, userna
tbody.appendChild(tr); tbody.appendChild(tr);
} }
table.appendChild(tbody); table.appendChild(tbody);
tableWrap.appendChild(table); histBody.appendChild(table);
histBody.appendChild(tableWrap);
} }
const totalPages = Math.max(1, Math.ceil(totalGames / limit)); const totalPages = Math.max(1, Math.ceil(totalGames / limit));

View file

@ -578,21 +578,17 @@ export function createHttpHandler(deps: {
if (gameId && !segments[2] && method === 'GET') { if (gameId && !segments[2] && method === 'GET') {
const active = gameManager.getGameState(gameId); 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) { if (active) {
sendJson(res, 200, { kind: 'active', game: active }); sendJson(res, 200, { kind: 'active', game: active });
return; 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; return;
} }
} }

View file

@ -1,7 +1,5 @@
import { Chess, sqToAlg } from './chess'; import { Chess, sqToAlg } from './chess';
import type { Piece, PromotionPiece } from './types'; import type { PromotionPiece } from './types';
export const MAX_PREMOVES = 25;
export interface QueuedPremove { export interface QueuedPremove {
from: number; from: number;
@ -11,59 +9,9 @@ export interface QueuedPremove {
const PROMO_LIST: PromotionPiece[] = ['q', 'r', 'b', 'n']; const PROMO_LIST: PromotionPiece[] = ['q', 'r', 'b', 'n'];
export function applyPremoveQueueToBoard( export function computePremoveTargets(chess: Chess, fromSq: number): Map<number, PromotionPiece[]> {
baseBoard: ReadonlyArray<Piece | null>,
queue: ReadonlyArray<QueuedPremove>
): Array<Piece | null> {
const board: Array<Piece | null> = 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<QueuedPremove>, 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<QueuedPremove> = []
): Map<number, PromotionPiece[]> {
const map = new Map<number, PromotionPiece[]>(); const map = new Map<number, PromotionPiece[]>();
const projected = queue.length > 0 ? applyPremoveQueueToBoard(chess.board(), queue) : chess.board(); const piece = chess.get(fromSq);
const piece = projected[fromSq];
if (!piece) return map; if (!piece) return map;
const r = fromSq >> 3; const r = fromSq >> 3;
@ -102,12 +50,12 @@ export function computePremoveTargets(
if (adr <= 1 && adc <= 1) { if (adr <= 1 && adc <= 1) {
ok = true; ok = true;
} else if (dr === 0 && adc === 2) { } else if (dr === 0 && adc === 2) {
if (piece.color === 'w' && r === 7 && c === 4 && !hasMovedInQueue(queue, 60)) { if (piece.color === 'w' && r === 7 && c === 4) {
if (tc === 6 && castlingField.indexOf('K') >= 0 && !hasMovedInQueue(queue, 63)) ok = true; if (tc === 6 && castlingField.indexOf('K') >= 0) ok = true;
if (tc === 2 && castlingField.indexOf('Q') >= 0 && !hasMovedInQueue(queue, 56)) ok = true; if (tc === 2 && castlingField.indexOf('Q') >= 0) ok = true;
} else if (piece.color === 'b' && r === 0 && c === 4 && !hasMovedInQueue(queue, 4)) { } else if (piece.color === 'b' && r === 0 && c === 4) {
if (tc === 6 && castlingField.indexOf('k') >= 0 && !hasMovedInQueue(queue, 7)) ok = true; if (tc === 6 && castlingField.indexOf('k') >= 0) ok = true;
if (tc === 2 && castlingField.indexOf('q') >= 0 && !hasMovedInQueue(queue, 0)) ok = true; if (tc === 2 && castlingField.indexOf('q') >= 0) ok = true;
} }
} }
} }

View file

@ -1,17 +1,7 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import test from 'node:test'; import test from 'node:test';
import { Chess, algToSq } from '../src/shared/chess'; import { Chess, algToSq } from '../src/shared/chess';
import { import { computePremoveTargets, resolveQueuedPremove } from '../src/shared/premove';
MAX_PREMOVES,
type QueuedPremove,
applyPremoveQueueToBoard,
computePremoveTargets,
resolveQueuedPremove
} from '../src/shared/premove';
test('MAX_PREMOVES is 25', () => {
assert.equal(MAX_PREMOVES, 25);
});
test('Pawn premove targets include 1-step, 2-step from start, diagonal captures, and promotions', () => { 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'); 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']); 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', () => { 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 // 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 c = new Chess('r2qkbnr/ppp2ppp/2np4/4p3/4P1b1/3P1N2/PPP2PPP/RNBQKB1R b KQkq - 0 4');
const qTargets = computePremoveTargets(c, algToSq('d1')); 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('f3')), true);
assert.equal(qTargets.has(algToSq('h5')), 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); 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 withRights = new Chess('r3k2r/8/8/8/8/8/8/R3K2R b KQkq - 0 1');
const kTargets = computePremoveTargets(withRights, algToSq('e1')); const kTargets = computePremoveTargets(withRights, algToSq('e1'));
assert.equal(kTargets.has(algToSq('g1')), true); assert.equal(kTargets.has(algToSq('g1')), true);
assert.equal(kTargets.has(algToSq('c1')), 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 noRights = new Chess('r3k2r/8/8/8/8/8/8/R3K2R b - - 0 1');
const kNoTargets = computePremoveTargets(noRights, algToSq('e1')); const kNoTargets = computePremoveTargets(noRights, algToSq('e1'));
assert.equal(kNoTargets.has(algToSq('g1')), false); 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'); 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); 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!));
});

View file

@ -259,7 +259,6 @@ test('ChessUp full server E2E: auth, lobby, PvP, Glicko-2, Stockfish analysis, b
// Check REST history, PGN, leaderboard // Check REST history, PGN, leaderboard
const storedRes = await alice.req<{ kind: string; game: { result: string } }>(`/api/games/${pvpGameId}`); const storedRes = await alice.req<{ kind: string; game: { result: string } }>(`/api/games/${pvpGameId}`);
assert.equal(storedRes.status, 200); assert.equal(storedRes.status, 200);
assert.equal(storedRes.data.kind, 'stored');
assert.equal(storedRes.data.game.result, '1-0'); assert.equal(storedRes.data.game.result, '1-0');
const pgnRes = await alice.req<string>(`/api/games/${pvpGameId}/pgn`); const pgnRes = await alice.req<string>(`/api/games/${pvpGameId}/pgn`);