1
1
/* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { Chess } from 'chess.ts'
2
3
import { defaults } from 'chessground/state'
3
4
import type { Key } from 'chessground/types'
4
5
import Chessground from '@react-chess/chessground'
6
+ import type { DrawBrushes , DrawShape } from 'chessground/draw'
7
+ import { ClientBaseGame , Check , GameNode , Color } from 'src/types'
5
8
import {
9
+ useMemo ,
6
10
Dispatch ,
7
- SetStateAction ,
8
11
useCallback ,
9
- useContext ,
10
- useMemo ,
12
+ SetStateAction ,
13
+ useEffect ,
11
14
} from 'react'
12
- import type { DrawBrushes , DrawShape } from 'chessground/draw'
13
-
14
- import { BaseGame , Check } from 'src/types'
15
- import { ClientGameControllerContext } from 'src/contexts'
16
15
17
16
interface Props {
18
- game : BaseGame
17
+ game : ClientBaseGame
19
18
moves ?: Map < string , string [ ] >
19
+ currentNode : GameNode
20
+ orientation : Color
21
+ goToNode : ( node : GameNode ) => void
20
22
setCurrentMove ?: ( move : [ string , string ] | null ) => void
21
23
setCurrentSquare ?: Dispatch < SetStateAction < Key | null > >
22
24
move ?: {
@@ -32,19 +34,48 @@ export const ClientGameBoard: React.FC<Props> = ({
32
34
game,
33
35
moves,
34
36
move,
37
+ currentNode,
38
+ orientation,
39
+ goToNode,
35
40
setCurrentMove,
36
41
setCurrentSquare,
37
42
shapes,
38
43
brushes,
39
44
} : Props ) => {
40
- const { currentNode, orientation } = useContext ( ClientGameControllerContext )
45
+ useEffect ( ( ) => {
46
+ console . log ( currentNode )
47
+ } , [ currentNode ] )
41
48
42
49
const after = useCallback (
43
50
( from : string , to : string ) => {
51
+ if ( ! game . tree || ! currentNode ) return
52
+
44
53
if ( setCurrentMove ) setCurrentMove ( [ from , to ] )
45
54
if ( setCurrentSquare ) setCurrentSquare ( null )
55
+
56
+ const chess = new Chess ( currentNode . fen ) // Use currentNode.fen
57
+
58
+ const moveAttempt = chess . move ( { from : from , to : to } )
59
+
60
+ if ( moveAttempt ) {
61
+ const newFen = chess . fen ( )
62
+ const moveString = from + to
63
+ const san = moveAttempt . san
64
+
65
+ if ( currentNode . mainChild ?. move === moveString ) {
66
+ goToNode ( currentNode . mainChild )
67
+ } else {
68
+ const newVariation = game . tree . addVariation (
69
+ currentNode ,
70
+ newFen ,
71
+ moveString ,
72
+ san ,
73
+ )
74
+ goToNode ( newVariation )
75
+ }
76
+ }
46
77
} ,
47
- [ setCurrentMove , setCurrentSquare ] ,
78
+ [ setCurrentMove , setCurrentSquare , currentNode , game . tree , goToNode ] ,
48
79
)
49
80
50
81
const currentMove = useMemo ( ( ) => {
0 commit comments