1- import { memo } from 'react' ;
1+ import { memo , useEffect , useRef } from 'react' ;
22
33import { useChessboardContext } from './ChessboardProvider' ;
44import {
@@ -34,6 +34,7 @@ export const Square = memo(function Square({
3434 chessboardColumns,
3535 chessboardRows,
3636 currentPosition,
37+ draggingPiece,
3738 squareStyle,
3839 squareStyles,
3940 darkSquareStyle,
@@ -58,6 +59,26 @@ export const Square = memo(function Square({
5859 clearArrows,
5960 } = useChessboardContext ( ) ;
6061
62+ // track previous isOver to only fire onMouseOutSquare on transition
63+ const prevIsOverRef = useRef ( isOver ) ;
64+
65+ // handle firing onMouseOverSquare and onMouseOutSquare during drag operations
66+ // as onMouseOver and onMouseLeave do not fire during dragging
67+ useEffect ( ( ) => {
68+ if ( isOver && draggingPiece ) {
69+ onMouseOverSquare ?.( {
70+ piece : currentPosition [ squareId ] ?? null ,
71+ square : squareId ,
72+ } ) ;
73+ } else if ( ! isOver && draggingPiece && prevIsOverRef . current ) {
74+ onMouseOutSquare ?.( {
75+ piece : currentPosition [ squareId ] ?? null ,
76+ square : squareId ,
77+ } ) ;
78+ }
79+ prevIsOverRef . current = isOver ;
80+ } , [ currentPosition , draggingPiece , isOver , squareId ] ) ;
81+
6182 const column = squareId . match ( / ^ [ a - z ] + / ) ?. [ 0 ] ;
6283 const row = squareId . match ( / \d + $ / ) ?. [ 0 ] ;
6384
@@ -138,17 +159,24 @@ export const Square = memo(function Square({
138159 ctrlKey : e . ctrlKey ,
139160 } ) ;
140161 }
141- onMouseOverSquare ?.( {
142- piece : currentPosition [ squareId ] ?? null ,
143- square : squareId ,
144- } ) ;
162+
163+ // don't fire when dragging as that is handled by the useEffect
164+ if ( ! draggingPiece ) {
165+ onMouseOverSquare ?.( {
166+ piece : currentPosition [ squareId ] ?? null ,
167+ square : squareId ,
168+ } ) ;
169+ }
170+ } }
171+ onMouseLeave = { ( ) => {
172+ // don't fire when dragging as that is handled by the useEffect
173+ if ( ! draggingPiece ) {
174+ onMouseOutSquare ?.( {
175+ piece : currentPosition [ squareId ] ?? null ,
176+ square : squareId ,
177+ } ) ;
178+ }
145179 } }
146- onMouseLeave = { ( ) =>
147- onMouseOutSquare ?.( {
148- piece : currentPosition [ squareId ] ?? null ,
149- square : squareId ,
150- } )
151- }
152180 >
153181 { showNotation ? (
154182 < span
0 commit comments