fix: NCWF-2 bugs and desing fixes (#7)
Co-authored-by: Lala, Shahd <Shahd.Lala@sybit.de> Reviewed-on: #7
This commit was merged in pull request #7.
This commit is contained in:
@@ -1,52 +1,115 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, DestroyRef, OnDestroy, OnInit, inject } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { ActivatedRoute, RouterLink } from '@angular/router';
|
||||
import { BoardActionsBarComponent } from '../../components/board-actions-bar/board-actions-bar.component';
|
||||
import { ChessBoardComponent } from '../../components/chess-board/chess-board.component';
|
||||
import { InputCardComponent } from '../../components/input-card/input-card.component';
|
||||
import { ExportPanelComponent } from '../../components/export-panel/export-panel.component';
|
||||
import { MoveHistoryComponent, MoveNavDirection } from '../../components/move-history/move-history.component';
|
||||
import { PlayerCardComponent } from '../../components/player-card/player-card.component';
|
||||
import { PromotionDialogComponent } from '../../components/promotion-dialog/promotion-dialog.component';
|
||||
import { GameFacade } from './game.facade';
|
||||
|
||||
type TimerTurn = 'white' | 'black';
|
||||
type BoardTheme = 'arabian' | 'classic';
|
||||
|
||||
interface TimerSnapshot {
|
||||
whiteSeconds: number;
|
||||
blackSeconds: number;
|
||||
turn: TimerTurn;
|
||||
savedAt: number;
|
||||
}
|
||||
const LOW_TIME_THRESHOLD_MS = 60_000;
|
||||
const BOARD_THEME_KEY = 'nowchess.boardTheme';
|
||||
|
||||
@Component({
|
||||
selector: 'app-game',
|
||||
standalone: true,
|
||||
imports: [CommonModule, FormsModule, RouterLink, ChessBoardComponent, InputCardComponent, PromotionDialogComponent],
|
||||
imports: [
|
||||
RouterLink,
|
||||
ChessBoardComponent,
|
||||
PromotionDialogComponent,
|
||||
PlayerCardComponent,
|
||||
MoveHistoryComponent,
|
||||
ExportPanelComponent,
|
||||
BoardActionsBarComponent,
|
||||
],
|
||||
providers: [GameFacade],
|
||||
templateUrl: './game.component.html',
|
||||
styleUrl: './game.component.css'
|
||||
})
|
||||
export class GameComponent implements OnInit, OnDestroy {
|
||||
private static readonly TIMER_START_SECONDS = 10 * 60;
|
||||
private static readonly BOARD_THEME_STORAGE_KEY = 'nowchess.boardTheme';
|
||||
private readonly route = inject(ActivatedRoute);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
readonly facade = inject(GameFacade);
|
||||
whiteTimerSeconds = GameComponent.TIMER_START_SECONDS;
|
||||
blackTimerSeconds = GameComponent.TIMER_START_SECONDS;
|
||||
exportType: 'fen' | 'pgn' = 'fen';
|
||||
boardTheme: BoardTheme = 'arabian';
|
||||
isDarkMode = false;
|
||||
exportValue = '';
|
||||
exportNotice = '';
|
||||
private timerIntervalId: number | null = null;
|
||||
private activeGameId = '';
|
||||
|
||||
whiteTimerMs: number | null = null;
|
||||
blackTimerMs: number | null = null;
|
||||
boardTheme: BoardTheme = 'arabian';
|
||||
flipped = false;
|
||||
toastMessage = '';
|
||||
|
||||
private timerIntervalId: number | null = null;
|
||||
private toastTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
// ── Player display ──────────────────────────────────────────
|
||||
get whitePlayerName(): string {
|
||||
return this.facade.game?.white.displayName ?? 'White';
|
||||
}
|
||||
|
||||
get blackPlayerName(): string {
|
||||
return this.facade.game?.black.displayName ?? 'Black';
|
||||
}
|
||||
|
||||
get whitePlayerInitial(): string {
|
||||
return this.whitePlayerName.charAt(0).toUpperCase();
|
||||
}
|
||||
|
||||
get blackPlayerInitial(): string {
|
||||
return this.blackPlayerName.charAt(0).toUpperCase();
|
||||
}
|
||||
|
||||
// ── Clocks ──────────────────────────────────────────────────
|
||||
get whiteClock(): string {
|
||||
return this.formatTimer(this.whiteTimerMs);
|
||||
}
|
||||
|
||||
get blackClock(): string {
|
||||
return this.formatTimer(this.blackTimerMs);
|
||||
}
|
||||
|
||||
get isLowTimeWhite(): boolean {
|
||||
return this.whiteTimerMs !== null && this.whiteTimerMs < LOW_TIME_THRESHOLD_MS;
|
||||
}
|
||||
|
||||
get isLowTimeBlack(): boolean {
|
||||
return this.blackTimerMs !== null && this.blackTimerMs < LOW_TIME_THRESHOLD_MS;
|
||||
}
|
||||
|
||||
// ── Status message ───────────────────────────────────────────
|
||||
get statusMessage(): string {
|
||||
const state = this.facade.state;
|
||||
if (!state) return '';
|
||||
|
||||
if (state.status === 'check') {
|
||||
const who = state.turn === 'white' ? 'White' : 'Black';
|
||||
return `<b>${who}</b> is in check`;
|
||||
}
|
||||
|
||||
if (state.status === 'drawOffered') {
|
||||
return 'Draw offer pending';
|
||||
}
|
||||
|
||||
const last = state.moves.length > 0 ? state.moves[state.moves.length - 1] : null;
|
||||
if (last) {
|
||||
const mover = state.turn === 'white' ? this.blackPlayerName : this.whitePlayerName;
|
||||
return `${mover} played <b>${last}</b>`;
|
||||
}
|
||||
|
||||
return 'Game started';
|
||||
}
|
||||
|
||||
// ── Move number ──────────────────────────────────────────────
|
||||
get moveNumber(): number {
|
||||
return Math.ceil((this.facade.state?.moves.length ?? 0) / 2);
|
||||
}
|
||||
|
||||
// ── Lifecycle ────────────────────────────────────────────────
|
||||
ngOnInit(): void {
|
||||
this.applyIncomingTheme();
|
||||
this.syncThemeFromDocument();
|
||||
this.boardTheme = this.resolveStoredBoardTheme();
|
||||
this.startDummyTimers();
|
||||
this.startClock();
|
||||
|
||||
this.route.paramMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((paramMap) => {
|
||||
const id = paramMap.get('gameId');
|
||||
@@ -55,11 +118,7 @@ export class GameComponent implements OnInit, OnDestroy {
|
||||
this.facade.loading = false;
|
||||
return;
|
||||
}
|
||||
|
||||
this.activeGameId = id;
|
||||
this.restoreTimers(id);
|
||||
this.facade.setGameId(id);
|
||||
this.syncExportValue();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -67,192 +126,91 @@ export class GameComponent implements OnInit, OnDestroy {
|
||||
if (this.timerIntervalId !== null) {
|
||||
window.clearInterval(this.timerIntervalId);
|
||||
}
|
||||
|
||||
this.persistTimers(this.resolveCurrentTurn());
|
||||
}
|
||||
|
||||
private syncThemeFromDocument(): void {
|
||||
this.isDarkMode = document.documentElement.getAttribute('data-theme') === 'dark';
|
||||
}
|
||||
|
||||
private applyIncomingTheme(): void {
|
||||
const incomingTheme = window.history.state?.theme;
|
||||
if (incomingTheme === 'dark') {
|
||||
document.documentElement.setAttribute('data-theme', 'dark');
|
||||
localStorage.setItem('theme', 'dark');
|
||||
return;
|
||||
}
|
||||
|
||||
if (incomingTheme === 'light') {
|
||||
document.documentElement.removeAttribute('data-theme');
|
||||
localStorage.removeItem('theme');
|
||||
}
|
||||
}
|
||||
|
||||
setExportType(type: 'fen' | 'pgn'): void {
|
||||
this.exportType = type;
|
||||
this.exportNotice = '';
|
||||
this.syncExportValue();
|
||||
}
|
||||
|
||||
// ── Board theme ──────────────────────────────────────────────
|
||||
setBoardTheme(theme: BoardTheme): void {
|
||||
this.boardTheme = theme;
|
||||
localStorage.setItem(GameComponent.BOARD_THEME_STORAGE_KEY, theme);
|
||||
localStorage.setItem(BOARD_THEME_KEY, theme);
|
||||
}
|
||||
|
||||
completeExport(): void {
|
||||
this.syncExportValue();
|
||||
if (!this.exportValue.trim()) {
|
||||
this.exportNotice = 'Nothing to export yet.';
|
||||
return;
|
||||
}
|
||||
|
||||
if (!navigator.clipboard?.writeText) {
|
||||
this.exportNotice = 'Export is ready in the text box.';
|
||||
return;
|
||||
}
|
||||
|
||||
void navigator.clipboard
|
||||
.writeText(this.exportValue)
|
||||
.then(() => {
|
||||
this.exportNotice = 'Copied to clipboard.';
|
||||
})
|
||||
.catch(() => {
|
||||
this.exportNotice = 'Export is ready in the text box.';
|
||||
});
|
||||
// ── Board flip ───────────────────────────────────────────────
|
||||
flipBoard(): void {
|
||||
this.flipped = !this.flipped;
|
||||
}
|
||||
|
||||
formatTimer(totalSeconds: number): string {
|
||||
const safeSeconds = Math.max(0, totalSeconds);
|
||||
const minutes = Math.floor(safeSeconds / 60)
|
||||
.toString()
|
||||
.padStart(2, '0');
|
||||
const seconds = (safeSeconds % 60).toString().padStart(2, '0');
|
||||
// ── Copy helpers ─────────────────────────────────────────────
|
||||
copyGameId(): void {
|
||||
void navigator.clipboard?.writeText(this.facade.gameId).then(() => this.showToast('Game ID copied'));
|
||||
}
|
||||
|
||||
copyUrl(): void {
|
||||
void navigator.clipboard?.writeText(window.location.href).then(() => this.showToast('Link copied'));
|
||||
}
|
||||
|
||||
// ── Board actions ─────────────────────────────────────────────
|
||||
onTakeback(): void {
|
||||
this.showToast('Takeback requested');
|
||||
}
|
||||
|
||||
onOfferDraw(): void {
|
||||
this.showToast('Draw offered');
|
||||
}
|
||||
|
||||
onResign(): void {
|
||||
this.showToast('Resigned');
|
||||
}
|
||||
|
||||
// ── Move history navigation ───────────────────────────────────
|
||||
onMoveNavigate(_direction: MoveNavDirection): void {
|
||||
// Visual-only for now; board always reflects live position.
|
||||
}
|
||||
|
||||
// ── Timer helpers ─────────────────────────────────────────────
|
||||
private formatTimer(ms: number | null): string {
|
||||
if (ms === null) return '--:--';
|
||||
if (ms < 0) return '—';
|
||||
const totalSeconds = Math.floor(ms / 1000);
|
||||
const minutes = Math.floor(totalSeconds / 60).toString().padStart(2, '0');
|
||||
const seconds = (totalSeconds % 60).toString().padStart(2, '0');
|
||||
return `${minutes}:${seconds}`;
|
||||
}
|
||||
|
||||
private startDummyTimers(): void {
|
||||
if (this.timerIntervalId !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.timerIntervalId = window.setInterval(() => {
|
||||
this.tickDummyTimers();
|
||||
this.syncExportValue();
|
||||
}, 1000);
|
||||
// ── Private ───────────────────────────────────────────────────
|
||||
private startClock(): void {
|
||||
if (this.timerIntervalId !== null) return;
|
||||
this.timerIntervalId = window.setInterval(() => this.tickClock(), 200);
|
||||
}
|
||||
|
||||
private tickDummyTimers(): void {
|
||||
private tickClock(): void {
|
||||
const state = this.facade.state;
|
||||
if (!state || this.facade.loading || this.facade.isGameFinished) {
|
||||
const clock = state?.clock;
|
||||
if (!clock || this.facade.isGameFinished) {
|
||||
this.whiteTimerMs = null;
|
||||
this.blackTimerMs = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (state.turn === 'white') {
|
||||
this.whiteTimerSeconds = Math.max(0, this.whiteTimerSeconds - 1);
|
||||
this.persistTimers('white');
|
||||
return;
|
||||
}
|
||||
|
||||
this.blackTimerSeconds = Math.max(0, this.blackTimerSeconds - 1);
|
||||
this.persistTimers('black');
|
||||
const elapsed = Math.max(0, Date.now() - this.facade.clockSyncedAt);
|
||||
const activeIsWhite = state!.turn === 'white';
|
||||
this.whiteTimerMs = clock.whiteRemainingMs < 0
|
||||
? -1
|
||||
: Math.max(0, clock.whiteRemainingMs - (activeIsWhite ? elapsed : 0));
|
||||
this.blackTimerMs = clock.blackRemainingMs < 0
|
||||
? -1
|
||||
: Math.max(0, clock.blackRemainingMs - (!activeIsWhite ? elapsed : 0));
|
||||
}
|
||||
|
||||
private syncExportValue(): void {
|
||||
const state = this.facade.state;
|
||||
if (!state) {
|
||||
this.exportValue = '';
|
||||
return;
|
||||
}
|
||||
|
||||
this.exportValue = this.exportType === 'fen' ? state.fen : state.pgn;
|
||||
}
|
||||
|
||||
private restoreTimers(gameId: string): void {
|
||||
const fallbackTurn = this.resolveCurrentTurn();
|
||||
const rawSnapshot = localStorage.getItem(this.getTimerStorageKey(gameId));
|
||||
if (!rawSnapshot) {
|
||||
this.resetTimers();
|
||||
this.persistTimers(fallbackTurn);
|
||||
return;
|
||||
}
|
||||
|
||||
const snapshot = this.parseSnapshot(rawSnapshot);
|
||||
if (!snapshot) {
|
||||
this.resetTimers();
|
||||
this.persistTimers(fallbackTurn);
|
||||
return;
|
||||
}
|
||||
|
||||
this.applySnapshot(snapshot);
|
||||
this.persistTimers(snapshot.turn);
|
||||
}
|
||||
|
||||
private parseSnapshot(rawSnapshot: string): TimerSnapshot | null {
|
||||
try {
|
||||
const parsed = JSON.parse(rawSnapshot) as Partial<TimerSnapshot>;
|
||||
if (
|
||||
typeof parsed.whiteSeconds !== 'number' ||
|
||||
typeof parsed.blackSeconds !== 'number' ||
|
||||
(parsed.turn !== 'white' && parsed.turn !== 'black') ||
|
||||
typeof parsed.savedAt !== 'number'
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
whiteSeconds: Math.max(0, Math.floor(parsed.whiteSeconds)),
|
||||
blackSeconds: Math.max(0, Math.floor(parsed.blackSeconds)),
|
||||
turn: parsed.turn,
|
||||
savedAt: parsed.savedAt
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private applySnapshot(snapshot: TimerSnapshot): void {
|
||||
const elapsedSeconds = Math.max(0, Math.floor((Date.now() - snapshot.savedAt) / 1000));
|
||||
this.whiteTimerSeconds = snapshot.whiteSeconds;
|
||||
this.blackTimerSeconds = snapshot.blackSeconds;
|
||||
|
||||
if (snapshot.turn === 'white') {
|
||||
this.whiteTimerSeconds = Math.max(0, this.whiteTimerSeconds - elapsedSeconds);
|
||||
return;
|
||||
}
|
||||
|
||||
this.blackTimerSeconds = Math.max(0, this.blackTimerSeconds - elapsedSeconds);
|
||||
}
|
||||
|
||||
private persistTimers(turn: TimerTurn): void {
|
||||
if (!this.activeGameId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const snapshot: TimerSnapshot = {
|
||||
whiteSeconds: this.whiteTimerSeconds,
|
||||
blackSeconds: this.blackTimerSeconds,
|
||||
turn,
|
||||
savedAt: Date.now()
|
||||
};
|
||||
localStorage.setItem(this.getTimerStorageKey(this.activeGameId), JSON.stringify(snapshot));
|
||||
}
|
||||
|
||||
private resolveCurrentTurn(): TimerTurn {
|
||||
return this.facade.state?.turn ?? 'white';
|
||||
}
|
||||
|
||||
private resetTimers(): void {
|
||||
this.whiteTimerSeconds = GameComponent.TIMER_START_SECONDS;
|
||||
this.blackTimerSeconds = GameComponent.TIMER_START_SECONDS;
|
||||
}
|
||||
|
||||
private getTimerStorageKey(gameId: string): string {
|
||||
return `nowchess.timer.${gameId}`;
|
||||
private showToast(msg: string): void {
|
||||
this.toastMessage = msg;
|
||||
if (this.toastTimer !== null) clearTimeout(this.toastTimer);
|
||||
this.toastTimer = setTimeout(() => {
|
||||
this.toastMessage = '';
|
||||
}, 1800);
|
||||
}
|
||||
|
||||
private resolveStoredBoardTheme(): BoardTheme {
|
||||
const stored = localStorage.getItem(GameComponent.BOARD_THEME_STORAGE_KEY);
|
||||
const stored = localStorage.getItem(BOARD_THEME_KEY);
|
||||
return stored === 'classic' ? 'classic' : 'arabian';
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user