All files / app/component/chess chess.component.ts

26% Statements 65/250
20.22% Branches 36/178
20.45% Functions 9/44
25% Lines 57/228

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 44568x                                                                         68x 1x         1x   1x   1x   1x   1x     1x 1x 1x 1x 1x   1x 1x       1x   1x 1x       1x     1x 1x 1x 1x   1x 1x                       1x 1x                                                                                                                                   1x 1x 1x 1x                                                                                             1x 1x 1x 1x                   64x 32x 2x 2x 4x 4x 4x 16x   32x 32x 2x 2x 4x 4x 4x 16x                         384x 384x 384x       128x 128x 128x                                                                                                                                                                                                                                                                                                                                                                                
import { CdkDrag, CdkDragDrop, CdkDropList, CdkDropListGroup } from '@angular/cdk/drag-drop';
import {
  Component,
  ElementRef,
  EventEmitter,
  HostBinding,
  HostListener,
  Input,
  OnChanges,
  OnDestroy,
  OnInit,
  Output,
  SimpleChanges
} from '@angular/core';
import { Chess, Square } from 'chess.js';
import { defer, delay, flatten, without } from 'lodash-es';
import { autorun, IReactionDisposer } from 'mobx';
import { catchError, Observable, of, Subscription, throwError } from 'rxjs';
import { Ref } from '../../model/ref';
import { ActionService } from '../../service/action.service';
import { ConfigService } from '../../service/config.service';
import { Store } from '../../store/store';
 
export type PieceType = 'p' | 'n' | 'b' | 'r' | 'q' | 'k';
export type PieceColor = 'b' | 'w';
 
type Piece = { type: PieceType, color: PieceColor, square: Square, };
type AnimationState = { from: Square; to: Square; capture?: { square: Square; piece: Piece }; piece: Piece; boardState: (Piece | null)[], turnState: PieceColor, movesState: Square[] };
 
@Component({
  selector: 'app-chess',
  templateUrl: './chess.component.html',
  styleUrls: ['./chess.component.scss'],
  hostDirectives: [CdkDropListGroup],
  host: { 'class': 'chess-board' },
  imports: [CdkDropList, CdkDrag]
})
export class ChessComponent implements OnInit, OnChanges, OnDestroy {
  private disposers: IReactionDisposer[] = [];
 
  @Input()
  ref?: Ref;
  @Input()
  text? = '';
  @Input()
  white = true; // TODO: Save in local storage
  @Output()
  comment = new EventEmitter<string>();
  @Output()
  copied = new EventEmitter<string>();
 
  turn: PieceColor = 'w';
  from?: Square;
  to?: Square;
  moves: Square[] = [];
  chess = new Chess();
  pieces: (Piece | null)[] = flatten(this.chess.board());
  writeAccess = false;
  translate: string[] = [];
  lastMoveTo?: Square;
  animating = false;
  animationQueue: AnimationState[] = [];
  movingPiece?: { piece: Piece; from: Square; to: Square };
  capturedPiece?: { piece: Piece; square: Square };
  @HostBinding('class.flip')
  flip = false;
 
  private resizeObserver = window.ResizeObserver && new ResizeObserver(() => this.onResize()) || undefined;
  private fen = '';
  private watch?: Subscription;
  private append$!: (value: string) => Observable<string>;
  private board?: string;
  private retry: string[] = [];
 
  constructor(
    public config: ConfigService,
    private actions: ActionService,
    private store: Store,
    private el: ElementRef<HTMLDivElement>,
  ) {
    this.disposers.push(autorun(() => {
      Iif (this.store.eventBus.event === 'flip' && this.store.eventBus.ref?.url === this.ref?.url) {
        this.flip = true;
        delay(() => {
          this.flip = false;
          this.white = !this.white;
        }, 1000);
        defer(() => this.store.eventBus.fire('flip-done'));
      }
    }));
  }
 
  ngOnInit(): void {
    this.resizeObserver?.observe(this.el.nativeElement);
    this.onResize();
  }
 
  init() {
    this.reset(this.ref?.comment || this.text);
    if (!this.watch && this.ref) {
      const watch = this.actions.append(this.ref);
      this.append$ = watch.append$;
      this.watch = watch.updates$.pipe(
        catchError(err => {
          if (err.url) {
            // Game history rewritten
            alert($localize`Game History Rewritten!\n\nPlease Reload.`);
          }
          return of();
        }),
      ).subscribe(move => {
        try {
          this.chess.move(move);
          this.check();
          if (this.retry.length) {
            if (this.retry[0] === move) {
              // TODO: also check move number?
              this.retry.shift();
              return;
            } else {
              this.retrySave();
            }
          }
          const boardState = flatten(this.chess.board());
          const turnState = this.chess.turn();
          const movesState = this.chess.moves({ verbose: true }).map(m => m.to);
          const moveObj = this.chess.history({ verbose: true }).pop();
          if (moveObj) {
            const capturedPieceInfo = moveObj.captured ? {
              square: moveObj.to,
              piece: { type: moveObj.captured, color: moveObj.color === 'w' ? 'b' : 'w', square: moveObj.to } as Piece
            } : undefined;
            this.queueAnimation({
              from: moveObj.from,
              to: moveObj.to,
              capture: capturedPieceInfo,
              piece: { type: moveObj.piece, color: moveObj.color, square: moveObj.to },
              boardState,
              turnState,
              movesState
            });
          }
        } catch (e) {
          this.clearErrors();
        }
      });
    }
  }
 
  ngOnChanges(changes: SimpleChanges) {
    if (changes.ref || changes.text) {
      const newRef = changes.ref?.firstChange || changes.ref?.previousValue?.url !== changes.ref?.currentValue?.url;
      if (!this.ref || newRef) {
        this.watch?.unsubscribe();
        if (this.ref || this.text != null) this.init();
      }
    }
  }
 
  ngOnDestroy() {
    for (const dispose of this.disposers) dispose();
    this.disposers.length = 0;
    this.resizeObserver?.disconnect();
    this.watch?.unsubscribe();
  }
 
  clearErrors() {
    if (this.ref) {
      this.actions.comment(this.history, this.ref!);
    } else {
      this.text = this.history;
    }
  }
 
  reset(board?: string) {
    if (this.board === board) return;
    this.board = board;
    this.chess.clear();
    try {
      if (board) {
        const lines = board.trim().split('\n');
        this.chess.load(lines[0]);
        this.fen = this.chess.fen();
        lines.shift();
        for (const l of lines) {
          if (!l.trim()) continue;
          try {
            this.chess.move(l);
          } catch (e) {
            console.log(e);
          }
        }
      } else {
        this.chess.loadPgn('');
      }
    } catch (e) {
      try {
        this.chess.loadPgn(board || '');
      } catch (e) {
        console.error(e);
      }
    }
    this.render();
    if (!this.ref || (this.ref.comment || '') !== this.history) {
      this.clearErrors();
    }
  }
 
  @HostListener('window:resize')
  onResize() {
    const dim = Math.floor(this.el.nativeElement.offsetWidth / 8);
    const fontSize = Math.floor(0.75 * dim);
    this.el.nativeElement.style.setProperty('--dim', dim + 'px');
    this.el.nativeElement.style.setProperty('--piece-size', fontSize + 'px');
  }
 
  setPieceSize() {
    const dim = Math.floor(this.el.nativeElement.offsetWidth / 8);
    const fontSize = Math.floor(0.75 * dim);
    document.body.style.setProperty('--drag-piece-size', fontSize + 'px');
  }
 
  drawPiece(p?: Piece | null) {
    if (p?.color === 'w') {
      switch (p.type) {
        case 'k': return $localize`♔`;
        case 'q': return $localize`♕`;
        case 'r': return $localize`♖`;
        case 'b': return $localize`♗`;
        case 'n': return $localize`♘`;
        case 'p': return $localize`♙`;
      }
    E} else if (p?.color === 'b') {
      switch (p.type) {
        case 'k': return $localize`♚`;
        case 'q': return $localize`♛`;
        case 'r': return $localize`♜`;
        case 'b': return $localize`♝`;
        case 'n': return $localize`♞`;
        case 'p': return $localize`♟︎`;
      }
    }
    return ' ';
  }
 
  getIndex(place: string) {
    const col = place[0].toLowerCase().charCodeAt(0) - 'a'.charCodeAt(0);
    const row = 9 - parseInt(place[1]);
    return row * 8 + col;
  }
 
  getCoord(index: number): Square {
    const col = index % 8;
    const row = 8 - Math.floor(index / 8);
    return String.fromCharCode('a'.charCodeAt(0) + col) + row as Square;
  }
 
  color(index: number) {
    const col = (index % 8) % 2;
    const row = Math.floor(index / 8) % 2;
    return col === row ?  'light' : 'dark';
  }
 
  drop(event: CdkDragDrop<number, number, Piece>) {
    const from = this.getCoord(event.previousContainer.data);
    const to = this.getCoord(event.container.data);
    if (from === to) return;
    this.move(from, to);
  }
 
  move(from: Square, to: Square) {
    if (from === to) return;
    const isPromotion = !!this.chess.moves({ verbose: true }).find((move) => move.from === from && move.to === to && move.flags.includes('p'));
    const move = this.chess.move({from, to, promotion: isPromotion ? confirm($localize`Promote to Queen:`) ? 'q' : prompt($localize`Promotion:`) as Exclude<PieceType, 'p' | 'k'> : undefined});
    if (move) {
      this.render();
      this.check();
      this.save(move.san);
    }
  }
 
  render() {
    this.pieces = flatten(this.chess.board());
    this.lastMoveTo = this.chess.history({ verbose: true }).pop()?.to;
    this.turn = this.chess.turn();
    this.moves = this.chess.moves({ verbose: true }).map(m => m.to);
  }
 
  check() {
    if (this.chess.isGameOver()) {
      defer(() => {
        if (this.chess.isCheckmate()) {
          alert($localize`Checkmate!`);
        } else if (this.chess.isStalemate()) {
          alert($localize`Stalemate!`);
        } else if (this.chess.isThreefoldRepetition()) {
          alert($localize`Threefold Repetition!`);
        } else if (this.chess.isInsufficientMaterial()) {
          alert($localize`Insufficient Material!`);
        } else if (this.chess.isDraw()) {
          alert($localize`Draw!`);
        } else {
          alert($localize`Game Over!`);
        }
      });
    }
    delete this.from;
    delete this.to;
  }
 
  get history() {
    return (this.fen ? this.fen + '\n\n' : '') + this.chess.history().join('  \n');
  }
 
  save(move: string) {
    this.comment.emit(this.history);
    this.append$(move).pipe(
      catchError(err => {
        this.retry.push(move);
        delay(() => {
          if (this.retry.length) {
            this.clearErrors();
          }
        }, 1000);
        return throwError(() => err);
      }),
    ).subscribe();
  }
 
  retrySave() {
    if (!this.retry.length) return;
    const move = this.retry.shift()!;
    if (this.chess.moves().includes(move)) {
      this.append$(move).pipe(
        catchError(err => {
          this.retry.unshift(move);
          return throwError(() => err);
        }),
      ).subscribe();
    } else {
      this.retry.length = 0;
    }
  }
 
  clickSquare(index: number) {
    const square = this.getCoord(index);
    const p = this.chess.get(square);
    if (this.from === square) {
      delete this.from;
      this.moves = this.chess.moves({ verbose: true }).map(m => m.to);
    } else if (this.turn === p?.color) {
      this.from = square;
      this.moves = this.chess.moves({ square, verbose: true }).map(m => m.to);
    } else if (this.from) {
      this.to = square;
      this.move(this.from, square);
    }
  }
 
  private getMoveCoord(move: string, turn: PieceColor): Square {
    if (move === 'O-O') {
      return turn === 'w' ? 'g1' : 'g8';
    } else if (move === 'O-O-O') {
      return turn === 'w' ? 'c1' : 'c8';
    } else {
      return move.replace(/[^a-h1-8]/g, '') as Square;
    }
  }
 
  queueAnimation(state: AnimationState) {
    this.animationQueue.push(state);
    if (!this.animating) {
      this.processAnimationQueue();
    }
  }
 
  processAnimationQueue() {
    if (this.animationQueue.length === 0) {
      this.animating = false;
      delete this.movingPiece;
      delete this.capturedPiece;
      this.render();
      this.check();
      return;
    }
 
    this.animating = true;
    const animation = this.animationQueue.shift()!;
    this.pieces = animation.boardState;
    this.turn = animation.turnState;
    this.moves = animation.movesState;
    this.lastMoveTo = animation.to;
    this.movingPiece = { piece: animation.piece, from: animation.from, to: animation.to };
    if (animation.capture) {
      this.capturedPiece = animation.capture;
    }
 
    // Calculate coordinates for CSS animation
    const fromIndex = this.getIndex(animation.from);
    const toIndex = this.getIndex(animation.to);
    const fromCol = fromIndex % 8;
    const fromRow = Math.floor(fromIndex / 8);
    const toCol = toIndex % 8;
    const toRow = Math.floor(toIndex / 8);
 
    // Calculate deltas - the piece at destination needs to animate FROM source position
    // So we need the negative offset from destination back to source
    const xFrom = this.white ? -(toCol - fromCol) : -(fromCol - toCol);
    const yFrom = this.white ? -(toRow - fromRow) : -(fromRow - toRow);
    const xTo = 0;
    const yTo = 0;
 
    // Set CSS variables on the host element
    this.el.nativeElement.style.setProperty('--xFrom', xFrom.toString());
    this.el.nativeElement.style.setProperty('--yFrom', yFrom.toString());
    this.el.nativeElement.style.setProperty('--xTo', xTo.toString());
    this.el.nativeElement.style.setProperty('--yTo', yTo.toString());
 
    // Animate the piece moving to its destination with translation
    const movingPiece = animation.to;
    this.translate.push(movingPiece);
 
    // Remove captured piece animation after it completes (delay + duration)
    // Capture animation: 1.0s delay + 0.8s animation = 1.8s total
    if (animation.capture) {
      delay(() => {
        delete this.capturedPiece;
      }, 1800);
    }
 
    // Remove animation after completion (wait for capture to finish if present)
    const totalDuration = animation.capture ? 1900 : 1600;
    delay(() => {
      this.translate = without(this.translate, movingPiece);
      delete this.movingPiece;
      // capturedPiece already deleted above if it existed
      if (!animation.capture) {
        delete this.capturedPiece;
      }
      // Process next animation after current one completes
      this.processAnimationQueue();
    }, totalDuration);
  }
}