@react-chess-tools/react-chess-game 0.3.1 → 0.4.1

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.
Files changed (34) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.MD +42 -35
  3. package/coverage/clover.xml +6 -0
  4. package/coverage/coverage-final.json +1 -0
  5. package/coverage/lcov-report/base.css +224 -0
  6. package/coverage/lcov-report/block-navigation.js +87 -0
  7. package/coverage/lcov-report/favicon.png +0 -0
  8. package/coverage/lcov-report/index.html +101 -0
  9. package/coverage/lcov-report/prettify.css +1 -0
  10. package/coverage/lcov-report/prettify.js +2 -0
  11. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  12. package/coverage/lcov-report/sorter.js +196 -0
  13. package/coverage/lcov.info +0 -0
  14. package/dist/index.d.mts +85 -27
  15. package/dist/index.mjs +180 -37
  16. package/dist/index.mjs.map +1 -1
  17. package/package.json +2 -1
  18. package/src/components/ChessGame/ChessGame.stories.tsx +18 -0
  19. package/src/components/ChessGame/index.ts +2 -0
  20. package/src/components/ChessGame/parts/Board.tsx +2 -1
  21. package/src/components/ChessGame/parts/KeyboardControls.tsx +33 -0
  22. package/src/components/ChessGame/parts/Sounds.tsx +8 -2
  23. package/src/hooks/__tests__/useChessGame.test.tsx +230 -0
  24. package/src/hooks/useBoardSounds.test.ts +196 -0
  25. package/src/hooks/useBoardSounds.ts +8 -3
  26. package/src/hooks/useChessGame.ts +103 -22
  27. package/src/hooks/useChessGameContext.ts +2 -0
  28. package/src/hooks/useKeyboardControls.test.tsx +171 -0
  29. package/src/hooks/useKeyboardControls.ts +28 -0
  30. package/src/index.ts +19 -0
  31. package/src/utils/__tests__/board.test.ts +143 -0
  32. package/src/utils/__tests__/chess.test.ts +198 -0
  33. package/src/utils/board.ts +2 -2
  34. package/src/utils/chess.ts +32 -8
@@ -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
@@ -1,10 +1,15 @@
1
- import * as React from 'react';
1
+ import * as React$1 from 'react';
2
2
  import React__default from 'react';
3
3
  import { Chessboard } from 'react-chessboard';
4
4
  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
  }
@@ -14,17 +19,19 @@ interface RootProps {
14
19
  orientation?: Color;
15
20
  }
16
21
 
17
- declare const ChessGame: {
18
- Root: React.FC<React.PropsWithChildren<RootProps>>;
19
- Board: React.FC<ChessGameProps>;
20
- Sounds: React.FC<Partial<Record<Sound, string>>>;
22
+ type useChessGameProps = {
23
+ fen?: string;
24
+ orientation?: Color;
21
25
  };
22
-
23
- declare const useChessGameContext: () => {
24
- game: chess_js.Chess;
25
- orientation: chess_js.Color;
26
+ declare const useChessGame: ({ fen, orientation: initialOrientation, }?: useChessGameProps) => {
27
+ game: Chess;
28
+ currentFen: string;
29
+ currentPosition: string;
30
+ orientation: Color;
31
+ currentMoveIndex: number;
32
+ isLatestMove: boolean;
26
33
  info: {
27
- turn: chess_js.Color;
34
+ turn: Color;
28
35
  isPlayerTurn: boolean;
29
36
  isOpponentTurn: boolean;
30
37
  moveNumber: number;
@@ -41,25 +48,26 @@ declare const useChessGameContext: () => {
41
48
  hasPlayerLost: boolean;
42
49
  };
43
50
  methods: {
44
- makeMove: (move: string | {
45
- from: string;
46
- to: string;
47
- promotion?: string | undefined;
48
- }) => boolean;
49
- setPosition: (fen: string, orientation: chess_js.Color) => void;
51
+ makeMove: (move: Parameters<Chess["move"]>[0]) => boolean;
52
+ setPosition: (fen: string, orientation: Color) => void;
50
53
  flipBoard: () => void;
54
+ goToMove: (moveIndex: number) => void;
55
+ goToStart: () => void;
56
+ goToEnd: () => void;
57
+ goToPreviousMove: () => void;
58
+ goToNextMove: () => void;
51
59
  };
52
60
  };
53
61
 
54
- type useChessGameProps = {
55
- fen?: string;
56
- orientation?: Color;
57
- };
58
- declare const useChessGame: ({ fen, orientation: initialOrientation, }?: useChessGameProps) => {
59
- game: Chess;
60
- orientation: Color;
62
+ declare const useChessGameContext: () => {
63
+ game: chess_js.Chess;
64
+ currentFen: string;
65
+ currentPosition: string;
66
+ orientation: chess_js.Color;
67
+ currentMoveIndex: number;
68
+ isLatestMove: boolean;
61
69
  info: {
62
- turn: Color;
70
+ turn: chess_js.Color;
63
71
  isPlayerTurn: boolean;
64
72
  isOpponentTurn: boolean;
65
73
  moveNumber: number;
@@ -76,10 +84,60 @@ declare const useChessGame: ({ fen, orientation: initialOrientation, }?: useChes
76
84
  hasPlayerLost: boolean;
77
85
  };
78
86
  methods: {
79
- makeMove: (move: Parameters<Chess["move"]>[0]) => boolean;
80
- setPosition: (fen: string, orientation: Color) => void;
87
+ makeMove: (move: string | {
88
+ from: string;
89
+ to: string;
90
+ promotion?: string | undefined;
91
+ }) => boolean;
92
+ setPosition: (fen: string, orientation: chess_js.Color) => void;
81
93
  flipBoard: () => void;
94
+ goToMove: (moveIndex: number) => void;
95
+ goToStart: () => void;
96
+ goToEnd: () => void;
97
+ goToPreviousMove: () => void;
98
+ goToNextMove: () => void;
82
99
  };
83
100
  };
101
+ type ChessGameContextType = ReturnType<typeof useChessGame>;
102
+
103
+ type KeyboardControlsProps = {
104
+ controls?: KeyboardControls;
105
+ };
106
+ type KeyboardControls = Record<string, (context: ChessGameContextType) => void>;
107
+ declare const KeyboardControls: React.FC<KeyboardControlsProps>;
108
+
109
+ declare const ChessGame: {
110
+ Root: React$1.FC<React$1.PropsWithChildren<RootProps>>;
111
+ Board: React$1.FC<ChessGameProps>;
112
+ Sounds: React$1.FC<SoundsProps>;
113
+ KeyboardControls: React$1.FC<{
114
+ controls?: KeyboardControls | undefined;
115
+ }>;
116
+ };
117
+
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>;
84
142
 
85
- export { ChessGame, useChessGame, useChessGameContext };
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,17 +57,36 @@ 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 });
69
73
  return moves.map((move) => move.to);
70
74
  };
75
+ var getCurrentFen = (fen, game, currentMoveIndex) => {
76
+ const tempGame = new Chess();
77
+ if (currentMoveIndex === -1) {
78
+ if (fen) {
79
+ tempGame.load(fen);
80
+ }
81
+ } else {
82
+ const moves = game.history().slice(0, currentMoveIndex + 1);
83
+ if (fen) {
84
+ tempGame.load(fen);
85
+ }
86
+ moves.forEach((move) => tempGame.move(move));
87
+ }
88
+ return tempGame.fen();
89
+ };
71
90
 
72
91
  // src/hooks/useChessGame.ts
73
92
  var useChessGame = ({
@@ -75,37 +94,108 @@ var useChessGame = ({
75
94
  orientation: initialOrientation
76
95
  } = {}) => {
77
96
  const [game, setGame] = React.useState(new Chess2(fen));
97
+ useEffect(() => {
98
+ setGame(new Chess2(fen));
99
+ }, [fen]);
78
100
  const [orientation, setOrientation] = React.useState(
79
101
  initialOrientation ?? "w"
80
102
  );
81
- const setPosition = (fen2, orientation2) => {
103
+ const [currentMoveIndex, setCurrentMoveIndex] = React.useState(-1);
104
+ const history = React.useMemo(() => game.history(), [game]);
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) => {
82
122
  const newGame = new Chess2();
83
123
  newGame.load(fen2);
84
124
  setOrientation(orientation2);
85
125
  setGame(newGame);
86
- };
87
- const makeMove = (move) => {
88
- try {
89
- const copy = cloneGame(game);
90
- copy.move(move);
91
- setGame(copy);
92
- return true;
93
- } catch (e) {
94
- return false;
95
- }
96
- };
97
- const flipBoard = () => {
126
+ setCurrentMoveIndex(-1);
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(() => {
98
146
  setOrientation((orientation2) => orientation2 === "w" ? "b" : "w");
99
- };
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
+ () => ({
170
+ makeMove,
171
+ setPosition,
172
+ flipBoard,
173
+ goToMove,
174
+ goToStart,
175
+ goToEnd,
176
+ goToPreviousMove,
177
+ goToNextMove
178
+ }),
179
+ [
180
+ makeMove,
181
+ setPosition,
182
+ flipBoard,
183
+ goToMove,
184
+ goToStart,
185
+ goToEnd,
186
+ goToPreviousMove,
187
+ goToNextMove
188
+ ]
189
+ );
100
190
  return {
101
191
  game,
192
+ currentFen,
193
+ currentPosition,
102
194
  orientation,
103
- info: getGameInfo(game, orientation),
104
- methods: {
105
- makeMove,
106
- setPosition,
107
- flipBoard
108
- }
195
+ currentMoveIndex,
196
+ isLatestMove,
197
+ info,
198
+ methods
109
199
  };
110
200
  };
111
201
 
@@ -158,8 +248,9 @@ var getCustomSquareStyles = (game, info, activeSquare) => {
158
248
  if (activeSquare) {
159
249
  const destinationSquares = getDestinationSquares(game, activeSquare);
160
250
  destinationSquares.forEach((square) => {
251
+ var _a;
161
252
  customSquareStyles[square] = {
162
- 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%)"
163
254
  };
164
255
  });
165
256
  }
@@ -188,6 +279,7 @@ var Board = ({
188
279
  }
189
280
  const {
190
281
  game,
282
+ currentFen,
191
283
  orientation,
192
284
  info,
193
285
  methods: { makeMove }
@@ -249,7 +341,7 @@ var Board = ({
249
341
  ...customSquareStyles
250
342
  },
251
343
  boardOrientation: orientation === "b" ? "black" : "white",
252
- position: game.fen(),
344
+ position: currentFen,
253
345
  showPromotionDialog: !!promotionMove,
254
346
  onPromotionPieceSelect: promotionMove ? onPromotionPieceSelect : void 0,
255
347
  onPieceDragBegin: (_2, square) => {
@@ -284,30 +376,37 @@ var defaultSounds = {
284
376
  };
285
377
 
286
378
  // src/hooks/useBoardSounds.ts
287
- import { useEffect } from "react";
379
+ import { useEffect as useEffect2 } from "react";
288
380
  var useBoardSounds = (sounds) => {
289
381
  const {
290
382
  info: { lastMove, isCheckmate }
291
383
  } = useChessGameContext();
292
- useEffect(() => {
384
+ useEffect2(() => {
385
+ var _a, _b, _c;
386
+ if (Object.keys(sounds).length === 0) {
387
+ return;
388
+ }
293
389
  if (isCheckmate) {
294
- sounds.gameOver.play();
390
+ (_a = sounds.gameOver) == null ? void 0 : _a.play();
295
391
  return;
296
392
  }
297
393
  if (lastMove == null ? void 0 : lastMove.captured) {
298
- sounds.capture.play();
394
+ (_b = sounds.capture) == null ? void 0 : _b.play();
299
395
  return;
300
396
  }
301
397
  if (lastMove) {
302
- sounds.move.play();
398
+ (_c = sounds.move) == null ? void 0 : _c.play();
303
399
  return;
304
400
  }
305
401
  }, [lastMove]);
306
402
  };
307
403
 
308
404
  // src/components/ChessGame/parts/Sounds.tsx
309
- var Sounds = (sounds) => {
405
+ var Sounds = ({ sounds }) => {
310
406
  const customSoundsAudios = useMemo(() => {
407
+ if (typeof window === "undefined" || typeof Audio === "undefined") {
408
+ return {};
409
+ }
311
410
  return Object.entries({ ...defaultSounds, sounds }).reduce(
312
411
  (acc, [name, base64]) => {
313
412
  acc[name] = new Audio(`data:audio/wav;base64,${base64}`);
@@ -320,11 +419,55 @@ var Sounds = (sounds) => {
320
419
  return null;
321
420
  };
322
421
 
422
+ // src/hooks/useKeyboardControls.ts
423
+ import { useEffect as useEffect3 } from "react";
424
+ var useKeyboardControls = (controls) => {
425
+ const gameContext = useChessGameContext();
426
+ if (!gameContext) {
427
+ throw new Error("ChessGameContext not found");
428
+ }
429
+ const keyboardControls = { ...defaultKeyboardControls, ...controls };
430
+ useEffect3(() => {
431
+ const handleKeyDown = (event) => {
432
+ const handler = keyboardControls[event.key];
433
+ if (handler) {
434
+ event.preventDefault();
435
+ handler(gameContext);
436
+ }
437
+ };
438
+ window.addEventListener("keydown", handleKeyDown);
439
+ return () => {
440
+ window.removeEventListener("keydown", handleKeyDown);
441
+ };
442
+ }, [gameContext]);
443
+ return null;
444
+ };
445
+
446
+ // src/components/ChessGame/parts/KeyboardControls.tsx
447
+ var defaultKeyboardControls = {
448
+ ArrowLeft: (context) => context.methods.goToPreviousMove(),
449
+ ArrowRight: (context) => context.methods.goToNextMove(),
450
+ ArrowUp: (context) => context.methods.goToStart(),
451
+ ArrowDown: (context) => context.methods.goToEnd()
452
+ };
453
+ var KeyboardControls2 = ({
454
+ controls
455
+ }) => {
456
+ const gameContext = useChessGameContext();
457
+ if (!gameContext) {
458
+ throw new Error("ChessGameContext not found");
459
+ }
460
+ const keyboardControls = { ...defaultKeyboardControls, ...controls };
461
+ useKeyboardControls(keyboardControls);
462
+ return null;
463
+ };
464
+
323
465
  // src/components/ChessGame/index.ts
324
466
  var ChessGame = {
325
467
  Root,
326
468
  Board,
327
- Sounds
469
+ Sounds,
470
+ KeyboardControls: KeyboardControls2
328
471
  };
329
472
  export {
330
473
  ChessGame,