@react-chess-tools/react-chess-game 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,196 @@
1
+ /* eslint-disable */
2
+ var addSorting = (function() {
3
+ 'use strict';
4
+ var cols,
5
+ currentSort = {
6
+ index: 0,
7
+ desc: false
8
+ };
9
+
10
+ // returns the summary table element
11
+ function getTable() {
12
+ return document.querySelector('.coverage-summary');
13
+ }
14
+ // returns the thead element of the summary table
15
+ function getTableHeader() {
16
+ return getTable().querySelector('thead tr');
17
+ }
18
+ // returns the tbody element of the summary table
19
+ function getTableBody() {
20
+ return getTable().querySelector('tbody');
21
+ }
22
+ // returns the th element for nth column
23
+ function getNthColumn(n) {
24
+ return getTableHeader().querySelectorAll('th')[n];
25
+ }
26
+
27
+ function onFilterInput() {
28
+ const searchValue = document.getElementById('fileSearch').value;
29
+ const rows = document.getElementsByTagName('tbody')[0].children;
30
+ for (let i = 0; i < rows.length; i++) {
31
+ const row = rows[i];
32
+ if (
33
+ row.textContent
34
+ .toLowerCase()
35
+ .includes(searchValue.toLowerCase())
36
+ ) {
37
+ row.style.display = '';
38
+ } else {
39
+ row.style.display = 'none';
40
+ }
41
+ }
42
+ }
43
+
44
+ // loads the search box
45
+ function addSearchBox() {
46
+ var template = document.getElementById('filterTemplate');
47
+ var templateClone = template.content.cloneNode(true);
48
+ templateClone.getElementById('fileSearch').oninput = onFilterInput;
49
+ template.parentElement.appendChild(templateClone);
50
+ }
51
+
52
+ // loads all columns
53
+ function loadColumns() {
54
+ var colNodes = getTableHeader().querySelectorAll('th'),
55
+ colNode,
56
+ cols = [],
57
+ col,
58
+ i;
59
+
60
+ for (i = 0; i < colNodes.length; i += 1) {
61
+ colNode = colNodes[i];
62
+ col = {
63
+ key: colNode.getAttribute('data-col'),
64
+ sortable: !colNode.getAttribute('data-nosort'),
65
+ type: colNode.getAttribute('data-type') || 'string'
66
+ };
67
+ cols.push(col);
68
+ if (col.sortable) {
69
+ col.defaultDescSort = col.type === 'number';
70
+ colNode.innerHTML =
71
+ colNode.innerHTML + '<span class="sorter"></span>';
72
+ }
73
+ }
74
+ return cols;
75
+ }
76
+ // attaches a data attribute to every tr element with an object
77
+ // of data values keyed by column name
78
+ function loadRowData(tableRow) {
79
+ var tableCols = tableRow.querySelectorAll('td'),
80
+ colNode,
81
+ col,
82
+ data = {},
83
+ i,
84
+ val;
85
+ for (i = 0; i < tableCols.length; i += 1) {
86
+ colNode = tableCols[i];
87
+ col = cols[i];
88
+ val = colNode.getAttribute('data-value');
89
+ if (col.type === 'number') {
90
+ val = Number(val);
91
+ }
92
+ data[col.key] = val;
93
+ }
94
+ return data;
95
+ }
96
+ // loads all row data
97
+ function loadData() {
98
+ var rows = getTableBody().querySelectorAll('tr'),
99
+ i;
100
+
101
+ for (i = 0; i < rows.length; i += 1) {
102
+ rows[i].data = loadRowData(rows[i]);
103
+ }
104
+ }
105
+ // sorts the table using the data for the ith column
106
+ function sortByIndex(index, desc) {
107
+ var key = cols[index].key,
108
+ sorter = function(a, b) {
109
+ a = a.data[key];
110
+ b = b.data[key];
111
+ return a < b ? -1 : a > b ? 1 : 0;
112
+ },
113
+ finalSorter = sorter,
114
+ tableBody = document.querySelector('.coverage-summary tbody'),
115
+ rowNodes = tableBody.querySelectorAll('tr'),
116
+ rows = [],
117
+ i;
118
+
119
+ if (desc) {
120
+ finalSorter = function(a, b) {
121
+ return -1 * sorter(a, b);
122
+ };
123
+ }
124
+
125
+ for (i = 0; i < rowNodes.length; i += 1) {
126
+ rows.push(rowNodes[i]);
127
+ tableBody.removeChild(rowNodes[i]);
128
+ }
129
+
130
+ rows.sort(finalSorter);
131
+
132
+ for (i = 0; i < rows.length; i += 1) {
133
+ tableBody.appendChild(rows[i]);
134
+ }
135
+ }
136
+ // removes sort indicators for current column being sorted
137
+ function removeSortIndicators() {
138
+ var col = getNthColumn(currentSort.index),
139
+ cls = col.className;
140
+
141
+ cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, '');
142
+ col.className = cls;
143
+ }
144
+ // adds sort indicators for current column being sorted
145
+ function addSortIndicators() {
146
+ getNthColumn(currentSort.index).className += currentSort.desc
147
+ ? ' sorted-desc'
148
+ : ' sorted';
149
+ }
150
+ // adds event listeners for all sorter widgets
151
+ function enableUI() {
152
+ var i,
153
+ el,
154
+ ithSorter = function ithSorter(i) {
155
+ var col = cols[i];
156
+
157
+ return function() {
158
+ var desc = col.defaultDescSort;
159
+
160
+ if (currentSort.index === i) {
161
+ desc = !currentSort.desc;
162
+ }
163
+ sortByIndex(i, desc);
164
+ removeSortIndicators();
165
+ currentSort.index = i;
166
+ currentSort.desc = desc;
167
+ addSortIndicators();
168
+ };
169
+ };
170
+ for (i = 0; i < cols.length; i += 1) {
171
+ if (cols[i].sortable) {
172
+ // add the click event handler on the th so users
173
+ // dont have to click on those tiny arrows
174
+ el = getNthColumn(i).querySelector('.sorter').parentElement;
175
+ if (el.addEventListener) {
176
+ el.addEventListener('click', ithSorter(i));
177
+ } else {
178
+ el.attachEvent('onclick', ithSorter(i));
179
+ }
180
+ }
181
+ }
182
+ }
183
+ // adds sorting functionality to the UI
184
+ return function() {
185
+ if (!getTable()) {
186
+ return;
187
+ }
188
+ cols = loadColumns();
189
+ loadData();
190
+ addSearchBox();
191
+ addSortIndicators();
192
+ enableUI();
193
+ };
194
+ })();
195
+
196
+ window.addEventListener('load', addSorting);
File without changes
package/dist/index.d.mts CHANGED
@@ -5,6 +5,11 @@ import * as chess_js from 'chess.js';
5
5
  import { Color, Chess } from 'chess.js';
6
6
 
7
7
  type Sound = "check" | "move" | "capture" | "gameOver";
8
+ type Sounds = Record<Sound, HTMLAudioElement>;
9
+
10
+ type SoundsProps = {
11
+ sounds?: Partial<Record<Sound, string>>;
12
+ };
8
13
 
9
14
  interface ChessGameProps extends React__default.ComponentProps<typeof Chessboard> {
10
15
  }
@@ -104,10 +109,35 @@ declare const KeyboardControls: React.FC<KeyboardControlsProps>;
104
109
  declare const ChessGame: {
105
110
  Root: React$1.FC<React$1.PropsWithChildren<RootProps>>;
106
111
  Board: React$1.FC<ChessGameProps>;
107
- Sounds: React$1.FC<Partial<Record<Sound, string>>>;
112
+ Sounds: React$1.FC<SoundsProps>;
108
113
  KeyboardControls: React$1.FC<{
109
114
  controls?: KeyboardControls | undefined;
110
115
  }>;
111
116
  };
112
117
 
113
- export { ChessGame, useChessGame, useChessGameContext };
118
+ /**
119
+ * Returns an object with information about the current state of the game. This can be determined
120
+ * using chess.js instance, but this function is provided for convenience.
121
+ * @param game - The Chess.js instance representing the game.
122
+ * @returns An object with information about the current state of the game.
123
+ */
124
+ declare const getGameInfo: (game: Chess, orientation: Color) => {
125
+ turn: Color;
126
+ isPlayerTurn: boolean;
127
+ isOpponentTurn: boolean;
128
+ moveNumber: number;
129
+ lastMove: chess_js.Move | undefined;
130
+ isCheck: boolean;
131
+ isCheckmate: boolean;
132
+ isDraw: boolean;
133
+ isStalemate: boolean;
134
+ isThreefoldRepetition: boolean;
135
+ isInsufficientMaterial: boolean;
136
+ isGameOver: boolean;
137
+ isDrawn: boolean;
138
+ hasPlayerWon: boolean;
139
+ hasPlayerLost: boolean;
140
+ };
141
+ type GameInfo = ReturnType<typeof getGameInfo>;
142
+
143
+ export { ChessGame, type ChessGameContextType, type ChessGameProps, type GameInfo, KeyboardControls, type RootProps, type Sound, type Sounds, type SoundsProps, useChessGame, useChessGameContext, type useChessGameProps };
package/dist/index.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  import React3 from "react";
3
3
 
4
4
  // src/hooks/useChessGame.ts
5
- import React from "react";
5
+ import React, { useEffect } from "react";
6
6
  import { Chess as Chess2 } from "chess.js";
7
7
 
8
8
  // src/utils/chess.ts
@@ -26,8 +26,8 @@ var getGameInfo = (game, orientation) => {
26
26
  const isThreefoldRepetition = game.isThreefoldRepetition();
27
27
  const isInsufficientMaterial = game.isInsufficientMaterial();
28
28
  const isGameOver = game.isGameOver();
29
- const hasPlayerWon = isPlayerTurn && isGameOver && !isDraw;
30
- const hasPlayerLost = isOpponentTurn && isGameOver && !isDraw;
29
+ const hasPlayerWon = isOpponentTurn && isGameOver && !isDraw;
30
+ const hasPlayerLost = isPlayerTurn && isGameOver && !isDraw;
31
31
  const isDrawn = game.isDraw();
32
32
  return {
33
33
  turn,
@@ -57,12 +57,16 @@ var isLegalMove = (game, move) => {
57
57
  }
58
58
  };
59
59
  var requiresPromotion = (game, move) => {
60
- const copy = cloneGame(game);
61
- const result = copy.move(move);
62
- if (result === null) {
63
- return false;
60
+ try {
61
+ const copy = cloneGame(game);
62
+ const result = copy.move(move);
63
+ return result.flags.indexOf("p") !== -1;
64
+ } catch (e) {
65
+ if (e instanceof Error && e.message.includes("Invalid move")) {
66
+ return false;
67
+ }
68
+ throw e;
64
69
  }
65
- return result.flags.indexOf("p") !== -1;
66
70
  };
67
71
  var getDestinationSquares = (game, square) => {
68
72
  const moves = game.moves({ square, verbose: true });
@@ -90,53 +94,79 @@ var useChessGame = ({
90
94
  orientation: initialOrientation
91
95
  } = {}) => {
92
96
  const [game, setGame] = React.useState(new Chess2(fen));
97
+ useEffect(() => {
98
+ setGame(new Chess2(fen));
99
+ }, [fen]);
93
100
  const [orientation, setOrientation] = React.useState(
94
101
  initialOrientation ?? "w"
95
102
  );
96
103
  const [currentMoveIndex, setCurrentMoveIndex] = React.useState(-1);
97
104
  const history = React.useMemo(() => game.history(), [game]);
98
- const isLatestMove = currentMoveIndex === history.length - 1 || currentMoveIndex === -1;
99
- const setPosition = (fen2, orientation2) => {
105
+ const isLatestMove = React.useMemo(
106
+ () => currentMoveIndex === history.length - 1 || currentMoveIndex === -1,
107
+ [currentMoveIndex, history.length]
108
+ );
109
+ const info = React.useMemo(
110
+ () => getGameInfo(game, orientation),
111
+ [game, orientation]
112
+ );
113
+ const currentFen = React.useMemo(
114
+ () => getCurrentFen(fen, game, currentMoveIndex),
115
+ [game, currentMoveIndex]
116
+ );
117
+ const currentPosition = React.useMemo(
118
+ () => game.history()[currentMoveIndex],
119
+ [game, currentMoveIndex]
120
+ );
121
+ const setPosition = React.useCallback((fen2, orientation2) => {
100
122
  const newGame = new Chess2();
101
123
  newGame.load(fen2);
102
124
  setOrientation(orientation2);
103
125
  setGame(newGame);
104
126
  setCurrentMoveIndex(-1);
105
- };
106
- const makeMove = (move) => {
107
- if (!isLatestMove) {
108
- return false;
109
- }
110
- try {
111
- const copy = cloneGame(game);
112
- copy.move(move);
113
- setGame(copy);
114
- setCurrentMoveIndex(copy.history().length - 1);
115
- return true;
116
- } catch (e) {
117
- return false;
118
- }
119
- };
120
- const flipBoard = () => {
127
+ }, []);
128
+ const makeMove = React.useCallback(
129
+ (move) => {
130
+ if (!isLatestMove) {
131
+ return false;
132
+ }
133
+ try {
134
+ const copy = cloneGame(game);
135
+ copy.move(move);
136
+ setGame(copy);
137
+ setCurrentMoveIndex(copy.history().length - 1);
138
+ return true;
139
+ } catch (e) {
140
+ return false;
141
+ }
142
+ },
143
+ [isLatestMove, game]
144
+ );
145
+ const flipBoard = React.useCallback(() => {
121
146
  setOrientation((orientation2) => orientation2 === "w" ? "b" : "w");
122
- };
123
- const goToMove = (moveIndex) => {
124
- if (moveIndex < -1 || moveIndex >= history.length) return;
125
- setCurrentMoveIndex(moveIndex);
126
- };
127
- const goToStart = () => goToMove(-1);
128
- const goToEnd = () => goToMove(history.length - 1);
129
- const goToPreviousMove = () => goToMove(currentMoveIndex - 1);
130
- const goToNextMove = () => goToMove(currentMoveIndex + 1);
131
- return {
132
- game,
133
- currentFen: getCurrentFen(fen, game, currentMoveIndex),
134
- currentPosition: game.history()[currentMoveIndex],
135
- orientation,
136
- currentMoveIndex,
137
- isLatestMove,
138
- info: getGameInfo(game, orientation),
139
- methods: {
147
+ }, []);
148
+ const goToMove = React.useCallback(
149
+ (moveIndex) => {
150
+ if (moveIndex < -1 || moveIndex >= history.length) return;
151
+ setCurrentMoveIndex(moveIndex);
152
+ },
153
+ [history.length]
154
+ );
155
+ const goToStart = React.useCallback(() => goToMove(-1), []);
156
+ const goToEnd = React.useCallback(
157
+ () => goToMove(history.length - 1),
158
+ [history.length]
159
+ );
160
+ const goToPreviousMove = React.useCallback(
161
+ () => goToMove(currentMoveIndex - 1),
162
+ [currentMoveIndex]
163
+ );
164
+ const goToNextMove = React.useCallback(
165
+ () => goToMove(currentMoveIndex + 1),
166
+ [currentMoveIndex]
167
+ );
168
+ const methods = React.useMemo(
169
+ () => ({
140
170
  makeMove,
141
171
  setPosition,
142
172
  flipBoard,
@@ -145,7 +175,27 @@ var useChessGame = ({
145
175
  goToEnd,
146
176
  goToPreviousMove,
147
177
  goToNextMove
148
- }
178
+ }),
179
+ [
180
+ makeMove,
181
+ setPosition,
182
+ flipBoard,
183
+ goToMove,
184
+ goToStart,
185
+ goToEnd,
186
+ goToPreviousMove,
187
+ goToNextMove
188
+ ]
189
+ );
190
+ return {
191
+ game,
192
+ currentFen,
193
+ currentPosition,
194
+ orientation,
195
+ currentMoveIndex,
196
+ isLatestMove,
197
+ info,
198
+ methods
149
199
  };
150
200
  };
151
201
 
@@ -156,7 +206,7 @@ var useChessGameContext = () => {
156
206
  const context = React2.useContext(ChessGameContext);
157
207
  if (!context) {
158
208
  throw new Error(
159
- "useChessGameContext must be used within a ChessGameProvider"
209
+ `useChessGameContext must be used within a ChessGame component. Make sure your component is wrapped with <ChessGame.Root> or ensure the ChessGame component is properly rendered in the component tree.`
160
210
  );
161
211
  }
162
212
  return context;
@@ -198,8 +248,9 @@ var getCustomSquareStyles = (game, info, activeSquare) => {
198
248
  if (activeSquare) {
199
249
  const destinationSquares = getDestinationSquares(game, activeSquare);
200
250
  destinationSquares.forEach((square) => {
251
+ var _a;
201
252
  customSquareStyles[square] = {
202
- background: game.get(square) && game.get(square).color !== turn ? "radial-gradient(circle, rgba(0,0,0,.1) 85%, transparent 85%)" : "radial-gradient(circle, rgba(0,0,0,.1) 25%, transparent 25%)"
253
+ background: game.get(square) && ((_a = game.get(square)) == null ? void 0 : _a.color) !== turn ? "radial-gradient(circle, rgba(1, 0, 0, 0.1) 85%, transparent 85%)" : "radial-gradient(circle, rgba(0,0,0,.1) 25%, transparent 25%)"
203
254
  };
204
255
  });
205
256
  }
@@ -325,30 +376,37 @@ var defaultSounds = {
325
376
  };
326
377
 
327
378
  // src/hooks/useBoardSounds.ts
328
- import { useEffect } from "react";
379
+ import { useEffect as useEffect2 } from "react";
329
380
  var useBoardSounds = (sounds) => {
330
381
  const {
331
382
  info: { lastMove, isCheckmate }
332
383
  } = useChessGameContext();
333
- useEffect(() => {
384
+ useEffect2(() => {
385
+ var _a, _b, _c;
386
+ if (Object.keys(sounds).length === 0) {
387
+ return;
388
+ }
334
389
  if (isCheckmate) {
335
- sounds.gameOver.play();
390
+ (_a = sounds.gameOver) == null ? void 0 : _a.play();
336
391
  return;
337
392
  }
338
393
  if (lastMove == null ? void 0 : lastMove.captured) {
339
- sounds.capture.play();
394
+ (_b = sounds.capture) == null ? void 0 : _b.play();
340
395
  return;
341
396
  }
342
397
  if (lastMove) {
343
- sounds.move.play();
398
+ (_c = sounds.move) == null ? void 0 : _c.play();
344
399
  return;
345
400
  }
346
401
  }, [lastMove]);
347
402
  };
348
403
 
349
404
  // src/components/ChessGame/parts/Sounds.tsx
350
- var Sounds = (sounds) => {
405
+ var Sounds = ({ sounds }) => {
351
406
  const customSoundsAudios = useMemo(() => {
407
+ if (typeof window === "undefined" || typeof Audio === "undefined") {
408
+ return {};
409
+ }
352
410
  return Object.entries({ ...defaultSounds, sounds }).reduce(
353
411
  (acc, [name, base64]) => {
354
412
  acc[name] = new Audio(`data:audio/wav;base64,${base64}`);
@@ -362,14 +420,14 @@ var Sounds = (sounds) => {
362
420
  };
363
421
 
364
422
  // src/hooks/useKeyboardControls.ts
365
- import { useEffect as useEffect2 } from "react";
423
+ import { useEffect as useEffect3 } from "react";
366
424
  var useKeyboardControls = (controls) => {
367
425
  const gameContext = useChessGameContext();
368
426
  if (!gameContext) {
369
427
  throw new Error("ChessGameContext not found");
370
428
  }
371
429
  const keyboardControls = { ...defaultKeyboardControls, ...controls };
372
- useEffect2(() => {
430
+ useEffect3(() => {
373
431
  const handleKeyDown = (event) => {
374
432
  const handler = keyboardControls[event.key];
375
433
  if (handler) {