diff --git a/docs/stories/performance/RenderCounts.stories.tsx b/docs/stories/performance/RenderCounts.stories.tsx new file mode 100644 index 0000000..7e028d7 --- /dev/null +++ b/docs/stories/performance/RenderCounts.stories.tsx @@ -0,0 +1,273 @@ +import type { Meta, StoryObj } from '@storybook/react'; +import { Chess, SQUARES } from 'chess.js'; +import { + Profiler, + useRef, + useState, + type ProfilerOnRenderCallback, +} from 'react'; +import { flushSync } from 'react-dom'; + +import { Chessboard, type ChessboardOptions } from '../../../src/index.js'; + +const scenarios = { + S1: 'Replay 60 plies', + S2: '100 parent renders with stable options', + S3: '100 parent renders with inline options and callbacks', + S4: '50 square highlight changes', + S5: '10 drags across six squares', +}; + +type Scenario = keyof typeof scenarios; +type Measurement = { commits: number; actualDuration: number }; +type Point = { x: number; y: number }; + +// Kasparov–Topalov, Wijk aan Zee 1999, the first 30 moves. +const replayPgn = ` +1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Be3 Bg7 5. Qd2 c6 6. f3 b5 +7. Nge2 Nbd7 8. Bh6 Bxh6 9. Qxh6 Bb7 10. a3 e5 11. O-O-O Qe7 +12. Kb1 a6 13. Nc1 O-O-O 14. Nb3 exd4 15. Rxd4 c5 16. Rd1 Nb6 +17. g3 Kb8 18. Na5 Ba8 19. Bh3 d5 20. Qf4+ Ka7 21. Rhe1 d4 +22. Nd5 Nbxd5 23. exd5 Qd6 24. Rxd4 cxd4 25. Re7+ Kb6 26. Qxd4+ Kxa5 +27. b4+ Ka4 28. Qc3 Qxd5 29. Ra7 Bb7 30. Rxb7 Qc4 * +`.trim(); +const dragPath = ['e2', 'e3', 'd3', 'c3', 'c4', 'd4', 'e4']; +const dropPosition = + 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1'; + +const baseOptions: ChessboardOptions = { + id: 'render-counts', + showAnimations: false, + allowDrawingArrows: false, + clearArrowsOnClick: false, + canDragPiece: () => true, + onPieceClick: () => {}, +}; + +function afterPaint() { + return new Promise((resolve) => { + requestAnimationFrame(() => { + const channel = new MessageChannel(); + channel.port1.onmessage = () => { + channel.port1.close(); + channel.port2.close(); + resolve(); + }; + channel.port2.postMessage(null); + }); + }); +} + +function dispatchDragEvent( + target: EventTarget, + phase: 'down' | 'move' | 'up', + { x, y }: Point, +) { + const options = { + bubbles: true, + cancelable: true, + clientX: x, + clientY: y, + button: 0, + buttons: phase === 'up' ? 0 : 1, + }; + // Match the browser's event sequence for either dnd-kit mouse activator. + target.dispatchEvent( + new PointerEvent(`pointer${phase}`, { + ...options, + pointerId: 1, + pointerType: 'mouse', + isPrimary: true, + }), + ); + target.dispatchEvent(new MouseEvent(`mouse${phase}`, options)); +} + +async function dragAcrossBoard( + board: HTMLElement, + step: (change: () => void) => Promise, +) { + const [source, ...targets] = dragPath.map((square) => { + const cell = board.querySelector(`[data-square="${square}"]`); + if (!cell) throw new Error(`Square ${square} was not found.`); + return cell; + }); + const piece = source.querySelector('[data-piece]'); + if (!piece) throw new Error('The pawn on e2 was not found.'); + + function center(element: Element): Point { + const { left, top, width, height } = element.getBoundingClientRect(); + return { x: left + width / 2, y: top + height / 2 }; + } + + const start = center(source); + const points = targets.map(center); + const document = board.ownerDocument; + await step(() => { + dispatchDragEvent(piece, 'down', start); + // The first move past the activation distance starts the drag. + dispatchDragEvent(document, 'move', { x: start.x + 2, y: start.y }); + }); + for (const point of points) { + await step(() => dispatchDragEvent(document, 'move', point)); + } + await step(() => + dispatchDragEvent(document, 'up', points[points.length - 1]), + ); +} + +function RenderCountsBenchmark() { + const board = useRef(null); + const measurement = useRef(null); + const [running, setRunning] = useState(null); + const [runNumber, setRunNumber] = useState(0); + const [counter, setCounter] = useState(0); + const [options, setOptions] = useState(baseOptions); + const [results, setResults] = useState< + Partial> + >({}); + const [error, setError] = useState(null); + + const onRender: ProfilerOnRenderCallback = (_, __, actualDuration) => { + if (measurement.current) { + measurement.current.commits++; + measurement.current.actualDuration += actualDuration; + } + }; + + async function step(change: () => void) { + if (!board.current) throw new Error('The story was closed.'); + change(); + await afterPaint(); + } + + async function run(scenario: Scenario) { + const root = board.current; + if (running || !root) return; + + const sample = { commits: 0, actualDuration: 0 }; + let didDrop = false; + const dragOptions: ChessboardOptions = { + ...baseOptions, + onPieceDrop: ({ sourceSquare, targetSquare }) => { + didDrop = sourceSquare === 'e2' && targetSquare === 'e4'; + if (didDrop) setOptions({ ...dragOptions, position: dropPosition }); + return didDrop; + }, + }; + + try { + await step(() => + flushSync(() => { + setRunning(scenario); + setError(null); + setCounter(0); + setRunNumber((previous) => previous + 1); + setOptions(scenario === 'S5' ? dragOptions : baseOptions); + }), + ); + root.scrollIntoView({ block: 'nearest' }); + measurement.current = sample; + + if (scenario === 'S1') { + const chess = new Chess(); + chess.loadPgn(replayPgn, { strict: true }); + for (const { after: position } of chess.history({ verbose: true })) { + await step(() => + flushSync(() => setOptions({ ...baseOptions, position })), + ); + } + } else if (scenario === 'S2' || scenario === 'S3') { + for (let update = 1; update <= 100; update++) { + await step(() => flushSync(() => setCounter(update))); + } + } else if (scenario === 'S4') { + for (const square of SQUARES.slice(0, 50)) { + await step(() => + flushSync(() => + setOptions({ + ...baseOptions, + squareStyles: { + [square]: { boxShadow: 'inset 0 0 0 4px #646cff' }, + }, + }), + ), + ); + } + } else { + for (let repeat = 0; repeat < 10; repeat++) { + didDrop = false; + await dragAcrossBoard(root, step); + if (!didDrop) throw new Error('The pawn did not drop on e4.'); + + // Exclude the position reset between drags from the profile. + measurement.current = null; + await step(() => flushSync(() => setOptions(dragOptions))); + measurement.current = sample; + } + } + setResults((previous) => ({ ...previous, [scenario]: sample })); + } catch (failure) { + if (board.current) { + setError(`${scenario} failed. ${String(failure)}`); + } + } finally { + measurement.current = null; + if (board.current) setRunning(null); + } + } + + const boardOptions = + running === 'S3' + ? { ...baseOptions, canDragPiece: () => true, onPieceClick: () => {} } + : options; + + return ( +
+ + + + + + + + + + {(Object.keys(scenarios) as Scenario[]).map((scenario) => ( + + + + + + ))} + +
ScenarioCommitsTotal actual duration (ms)
+ + {results[scenario]?.commits ?? '—'}{results[scenario]?.actualDuration.toFixed(2) ?? '—'}
+

+ {running ? `Running ${running}…` : `Parent updates: ${counter}`} +

+ {error &&

{error}

} +
+ + + +
+
+ ); +} + +const meta = { + title: 'stories/Performance/RenderCounts', + component: RenderCountsBenchmark, +} satisfies Meta; + +export default meta; + +export const RenderCounts: StoryObj = {}; diff --git a/src/Arrows.tsx b/src/Arrows.tsx index d61ed8a..35b6527 100644 --- a/src/Arrows.tsx +++ b/src/Arrows.tsx @@ -1,6 +1,9 @@ -import { Fragment } from 'react'; +import { Fragment, use } from 'react'; -import { useChessboardContext } from './ChessboardProvider.js'; +import { + ChessboardLiveContext, + ChessboardSettingsContext, +} from './ChessboardProvider.js'; import { getRelativeCoords } from './utils.js'; export function Arrows() { @@ -11,10 +14,10 @@ export function Arrows() { boardOrientation, chessboardColumns, chessboardRows, - internalArrows, - newArrowStartSquare, - newArrowOverSquare, - } = useChessboardContext(); + } = use(ChessboardSettingsContext)!.settings; + const { internalArrows, newArrowStartSquare, newArrowOverSquare } = use( + ChessboardLiveContext, + )!; const viewBoxWidth = 2048; const viewBoxHeight = viewBoxWidth * (chessboardRows / chessboardColumns); diff --git a/src/Board.tsx b/src/Board.tsx index 4f63199..720a2c9 100644 --- a/src/Board.tsx +++ b/src/Board.tsx @@ -1,25 +1,31 @@ import { DragOverlay } from '@dnd-kit/core'; import { snapCenterToCursor } from '@dnd-kit/modifiers'; +import { memo, use } from 'react'; import { Arrows } from './Arrows.js'; -import { Draggable } from './Draggable.js'; import { Droppable } from './Droppable.js'; import { Piece } from './Piece.js'; -import { Square } from './Square.js'; -import { useChessboardContext } from './ChessboardProvider.js'; +import { + ChessboardLiveContext, + ChessboardSettingsContext, + ChessboardSquareStylesContext, +} from './ChessboardProvider.js'; import { defaultBoardStyle } from './defaults.js'; import { preventDragOffBoard } from './modifiers.js'; -export function Board() { +export const Board = memo(function Board() { const { allowDragOffBoard, board, boardStyle, chessboardColumns, - currentPosition, - draggingPiece, id, - } = useChessboardContext(); + squareRenderer, + } = use(ChessboardSettingsContext)!.settings; + const { currentPosition, draggingPiece, positionDifferences } = use( + ChessboardLiveContext, + )!; + const squareStyles = use(ChessboardSquareStylesContext)!; return ( <> @@ -32,21 +38,15 @@ export function Board() { const piece = currentPosition[square.squareId]; return ( - - {({ isOver }) => ( - - {piece ? ( - - - - ) : null} - - )} - + ); }), )} @@ -68,9 +68,10 @@ export function Board() { clone position={draggingPiece.position} pieceType={draggingPiece.pieceType} + moveTo={positionDifferences[draggingPiece.position]} /> ) : null} ); -} +}); diff --git a/src/Chessboard.tsx b/src/Chessboard.tsx index b286c4b..508cea1 100644 --- a/src/Chessboard.tsx +++ b/src/Chessboard.tsx @@ -1,8 +1,10 @@ +import { use } from 'react'; + import { Board } from './Board.js'; import { ChessboardOptions, ChessboardProvider, - useChessboardContext, + ChessboardSettingsContext, } from './ChessboardProvider.js'; type ChessboardProps = { @@ -10,7 +12,7 @@ type ChessboardProps = { }; export function Chessboard({ options }: ChessboardProps) { - const { isWrapped } = useChessboardContext() ?? { isWrapped: false }; + const isWrapped = use(ChessboardSettingsContext)?.settings.isWrapped; if (isWrapped) { return ; diff --git a/src/ChessboardProvider.tsx b/src/ChessboardProvider.tsx index 83be395..364f365 100644 --- a/src/ChessboardProvider.tsx +++ b/src/ChessboardProvider.tsx @@ -15,9 +15,11 @@ import { use, useCallback, useEffect, + useLayoutEffect, useMemo, useRef, useState, + useSyncExternalStore, } from 'react'; import { @@ -139,9 +141,113 @@ type ContextType = { clearArrows: () => void; }; -const ChessboardContext = createContext(null); +type LiveState = Pick< + ContextType, + | 'draggingPiece' + | 'currentPosition' + | 'positionDifferences' + | 'newArrowStartSquare' + | 'newArrowOverSquare' + | 'internalArrows' +>; +type Settings = Omit< + ContextType, + keyof LiveState | 'allowDragging' | 'canDragPiece' | 'squareStyles' +>; + +export const ChessboardSettingsContext = createContext<{ + settings: Settings; + liveRef: React.RefObject; + dragStarts: React.RefObject; +} | null>(null); +export const ChessboardLiveContext = createContext(null); +export const ChessboardSquareStylesContext = createContext< + ContextType['squareStyles'] | null +>(null); +const ChessboardDragContext = createContext<{ + allowDragging: ContextType['allowDragging']; + canDragPieceStore: ReturnType; +} | null>(null); +// Consumers of the public hook can evaluate the predicate during render. +const ChessboardCanDragPieceContext = + createContext(undefined); + +export const useChessboardContext = () => { + const settings = use(ChessboardSettingsContext)?.settings; + const live = use(ChessboardLiveContext); + const allowDragging = use(ChessboardDragContext)?.allowDragging; + const canDragPiece = use(ChessboardCanDragPieceContext); + const squareStyles = use(ChessboardSquareStylesContext); + + return useMemo(() => { + if (!settings || !live || allowDragging === undefined || !squareStyles) { + return null; + } + + return { ...settings, ...live, allowDragging, canDragPiece, squareStyles }; + }, [ + settings, + live, + allowDragging, + canDragPiece, + squareStyles, + ]) as ContextType; +}; + +// Inline handlers used to invalidate every square through the settings context. +function useLatestHandler( + handler: ((...args: Args) => void) | undefined, +) { + const handlerRef = useRef(handler); + useLayoutEffect(() => { + handlerRef.current = handler; + }, [handler]); + + const callHandler = useCallback((...args: Args) => { + const current = handlerRef.current; + current?.(...args); + }, []); + return handler ? callHandler : undefined; +} -export const useChessboardContext = () => use(ChessboardContext) as ContextType; +function createCanDragPieceStore(predicate: ChessboardOptions['canDragPiece']) { + const listeners = new Set<() => void>(); + + return { + canDragPiece: (piece: PieceHandlerArgs) => predicate?.(piece) ?? true, + setPredicate(next: ChessboardOptions['canDragPiece']) { + if (predicate === next) { + return; + } + predicate = next; + listeners.forEach((listener) => listener()); + }, + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + }; +} + +export function useCanDragPiece(piece: PieceHandlerArgs) { + const { allowDragging, canDragPieceStore } = use(ChessboardDragContext)!; + // Compare the result per piece so new predicates can change drag permission + // without re-rendering pieces whose permission stayed the same. + const getSnapshot = () => + allowDragging && canDragPieceStore.canDragPiece(piece); + return useSyncExternalStore( + canDragPieceStore.subscribe, + getSnapshot, + getSnapshot, + ); +} + +// Pointer-based detection for mouse and touch, rectangle intersection for keyboards. +function collisionDetection(args: Parameters[0]) { + return args.pointerCoordinates ? pointerWithin(args) : rectIntersection(args); +} export type ChessboardOptions = { // id @@ -220,6 +326,12 @@ export function ChessboardProvider({ children, options, }: React.PropsWithChildren<{ options?: ChessboardOptions }>) { + const emptySquareStyles = useMemo( + () => ({}), + [], + ); + const emptyArrows = useMemo(() => [], []); + const { // id id = 'chessboard', @@ -234,9 +346,9 @@ export function ChessboardProvider({ chessboardColumns = 8, // board and squares styles - boardStyle = defaultBoardStyle(chessboardColumns), + boardStyle: boardStyleOption, squareStyle = defaultSquareStyle, - squareStyles = {}, + squareStyles = emptySquareStyles, darkSquareStyle = defaultDarkSquareStyle, lightSquareStyle = defaultLightSquareStyle, dropSquareStyle = defaultDropSquareStyle, @@ -262,27 +374,40 @@ export function ChessboardProvider({ // arrows allowDrawingArrows = true, - arrows = [], + arrows = emptyArrows, arrowOptions = defaultArrowOptions, clearArrowsOnClick = true, clearArrowsOnPositionChange = true, // handlers - canDragPiece, - onArrowsChange, - onMouseOutSquare, - onMouseOverSquare, - onPieceClick, - onPieceDrag, - onPieceDragCancel, - onPieceDrop, - onSquareClick, - onSquareMouseDown, - onSquareMouseUp, - onSquareRightClick, + canDragPiece: canDragPieceOption, + + // A new renderer can change the rendered content of every square. squareRenderer, } = options || {}; + const optionsRef = useRef(options); + useLayoutEffect(() => { + optionsRef.current = options; + }, [options]); + + const onMouseOutSquare = useLatestHandler(options?.onMouseOutSquare); + const onMouseOverSquare = useLatestHandler(options?.onMouseOverSquare); + const onPieceClick = useLatestHandler(options?.onPieceClick); + const onSquareClick = useLatestHandler(options?.onSquareClick); + const onSquareMouseDown = useLatestHandler(options?.onSquareMouseDown); + const onSquareMouseUp = useLatestHandler(options?.onSquareMouseUp); + const onSquareRightClick = useLatestHandler(options?.onSquareRightClick); + + const boardStyle = useMemo( + () => + boardStyleOption === undefined + ? defaultBoardStyle(chessboardColumns) + : boardStyleOption, + [boardStyleOption, chessboardColumns], + ); + const dragStarts = useRef(0); + // the piece currently being dragged const [draggingPiece, setDraggingPiece] = useState(null); @@ -317,6 +442,29 @@ export function ChessboardProvider({ } | null>(null); const [internalArrows, setInternalArrows] = useState([]); + const live = useMemo( + () => ({ + draggingPiece, + currentPosition, + positionDifferences, + newArrowStartSquare, + newArrowOverSquare, + internalArrows, + }), + [ + draggingPiece, + currentPosition, + positionDifferences, + newArrowStartSquare, + newArrowOverSquare, + internalArrows, + ], + ); + const liveRef = useRef(live); + useLayoutEffect(() => { + liveRef.current = live; + }, [live]); + // position we are animating to, if a new position comes in before the animation completes, we will use this to set the new position const [waitingForAnimationPosition, setWaitingForAnimationPosition] = useState(null); @@ -466,6 +614,7 @@ export function ChessboardProvider({ // if the arrows change, call the onArrowsChange callback useEffect(() => { + const onArrowsChange = optionsRef.current?.onArrowsChange; onArrowsChange?.({ arrows: internalArrows }); }, [internalArrows]); @@ -489,6 +638,7 @@ export function ChessboardProvider({ return; } + const { internalArrows, newArrowStartSquare } = liveRef.current; const arrowExistsIndex = internalArrows.findIndex( (arrow) => arrow.startSquare === newArrowStartSquare && @@ -545,17 +695,7 @@ export function ChessboardProvider({ setNewArrowOverSquare(null); } }, - [ - allowDrawingArrows, - arrows, - // TODO : remove support for legacy arrow color props in future breaking version - arrowOptions.color, - arrowOptions.secondaryColor, - arrowOptions.tertiaryColor, - internalArrows, - newArrowStartSquare, - newArrowOverSquare, - ], + [allowDrawingArrows, arrows, arrowOptions], ); const clearArrows = useCallback(() => { @@ -607,64 +747,69 @@ export function ChessboardProvider({ const handleDragCancel = useCallback(() => { setDraggingPiece(null); + const onPieceDragCancel = optionsRef.current?.onPieceDragCancel; onPieceDragCancel?.(); - }, [onPieceDragCancel]); + }, []); - const handleDragEnd = useCallback( - function handleDragEnd(event: DragEndEvent) { - if (!draggingPiece) { - return; - } + const handleDragEnd = useCallback(function handleDragEnd( + event: DragEndEvent, + ) { + const { draggingPiece } = liveRef.current; + if (!draggingPiece) { + return; + } - const dropSquare = event.over?.id.toString(); + const dropSquare = event.over?.id.toString(); + const onPieceDrop = optionsRef.current?.onPieceDrop; - // dropped outside of droppable area (e.g. off board) - if (!dropSquare) { - const isDropValid = onPieceDrop?.({ - piece: draggingPiece, + // dropped outside of droppable area (e.g. off board) + if (!dropSquare) { + const isDropValid = onPieceDrop?.({ + piece: draggingPiece, + sourceSquare: draggingPiece.position, + targetSquare: null, + }); + + // set as manually dropped piece so that no animation is shown + if (isDropValid) { + setManuallyDroppedPieceAndSquare({ + piece: draggingPiece.pieceType, sourceSquare: draggingPiece.position, - targetSquare: null, + targetSquare: '', }); - - // set as manually dropped piece so that no animation is shown - if (isDropValid) { - setManuallyDroppedPieceAndSquare({ - piece: draggingPiece.pieceType, - sourceSquare: draggingPiece.position, - targetSquare: '', - }); - } - setDraggingPiece(null); - return; } + setDraggingPiece(null); + return; + } - if (event.over) { - const isDropValid = onPieceDrop?.({ - piece: draggingPiece, + if (event.over) { + const isDropValid = onPieceDrop?.({ + piece: draggingPiece, + sourceSquare: draggingPiece.position, + targetSquare: dropSquare, + }); + + // if the drop is valid, set the manually dropped piece and square + if (isDropValid) { + setManuallyDroppedPieceAndSquare({ + piece: draggingPiece.pieceType, sourceSquare: draggingPiece.position, targetSquare: dropSquare, }); - - // if the drop is valid, set the manually dropped piece and square - if (isDropValid) { - setManuallyDroppedPieceAndSquare({ - piece: draggingPiece.pieceType, - sourceSquare: draggingPiece.position, - targetSquare: dropSquare, - }); - } - setDraggingPiece(null); } - }, - [draggingPiece], - ); + setDraggingPiece(null); + } + }, []); const handleDragStart = useCallback( // active.id is the id of the piece being dragged function handleDragStart({ active }: DragStartEvent) { + dragStarts.current++; + const { currentPosition } = liveRef.current; // the id is either the position of the piece on the board if it's on the board (e.g. "a1", "b2", etc.), or the type of the piece if it's a spare piece (e.g. "wP", "bN", etc.) const isSparePiece = active.data.current?.isSparePiece; + const onPieceDrag = optionsRef.current?.onPieceDrag; onPieceDrag?.({ isSparePiece, piece: isSparePiece @@ -684,40 +829,28 @@ export function ChessboardProvider({ }); return; }, - [currentPosition], + [], ); - const pointerActivationConstraint = - dragActivationDistance > 0 - ? { - distance: dragActivationDistance, - } - : undefined; - const sensors = useSensors( - useSensor(RightClickCancelSensor, { - activationConstraint: pointerActivationConstraint, + const pointerSensorOptions = useMemo( + () => ({ + activationConstraint: + dragActivationDistance > 0 + ? { distance: dragActivationDistance } + : undefined, }), + [dragActivationDistance], + ); + const sensors = useSensors( + useSensor(RightClickCancelSensor, pointerSensorOptions), useSensor(KeyboardSensor), - useSensor(TouchSensor, { - activationConstraint: pointerActivationConstraint, - }), + useSensor(TouchSensor, pointerSensorOptions), useSensor(MouseSensor), ); - // collision detection that first tries pointer-based detection and then falls back to rectangle intersection for keyboards - function collisionDetection(args: Parameters[0]) { - // if a pointer is found, return those - if (args.pointerCoordinates) { - return pointerWithin(args); - } - - // otherwise fall back to rectangle intersection - return rectIntersection(args); - } - - return ( - ({ + settings: { // chessboard options id, @@ -729,7 +862,6 @@ export function ChessboardProvider({ boardStyle, squareStyle, - squareStyles, darkSquareStyle, lightSquareStyle, dropSquareStyle, @@ -745,14 +877,12 @@ export function ChessboardProvider({ animationDurationInMs, showAnimations, - allowDragging, allowDragOffBoard, allowDrawingArrows, arrows, arrowOptions, - canDragPiece, onMouseOutSquare, onMouseOverSquare, onPieceClick, @@ -765,29 +895,83 @@ export function ChessboardProvider({ // internal state board, isWrapped: true, - draggingPiece, - currentPosition, - positionDifferences, - newArrowStartSquare, - newArrowOverSquare, setNewArrowStartSquare, setNewArrowOverSquare: setNewArrowOverSquareWithModifiers, - internalArrows, drawArrow, clearArrows, - }} - > - - {children} - - + }, + liveRef, + dragStarts, + }), + [ + id, + pieces, + boardOrientation, + chessboardRows, + chessboardColumns, + boardStyle, + squareStyle, + darkSquareStyle, + lightSquareStyle, + dropSquareStyle, + draggingPieceStyle, + draggingPieceGhostStyle, + darkSquareNotationStyle, + lightSquareNotationStyle, + alphaNotationStyle, + numericNotationStyle, + showNotation, + animationDurationInMs, + showAnimations, + allowDragOffBoard, + allowDrawingArrows, + arrows, + arrowOptions, + onMouseOutSquare, + onMouseOverSquare, + onPieceClick, + onSquareClick, + onSquareMouseDown, + onSquareMouseUp, + onSquareRightClick, + squareRenderer, + board, + setNewArrowOverSquareWithModifiers, + drawArrow, + clearArrows, + ], + ); + const [canDragPieceStore] = useState(() => + createCanDragPieceStore(canDragPieceOption), + ); + useLayoutEffect(() => { + canDragPieceStore.setPredicate(canDragPieceOption); + }, [canDragPieceStore, canDragPieceOption]); + const dragContext = useMemo( + () => ({ allowDragging, canDragPieceStore }), + [allowDragging, canDragPieceStore], + ); + return ( + + + + + + + {children} + + + + + + ); } diff --git a/src/Draggable.tsx b/src/Draggable.tsx index a8acfec..84521d5 100644 --- a/src/Draggable.tsx +++ b/src/Draggable.tsx @@ -1,6 +1,6 @@ import { useDraggable } from '@dnd-kit/core'; -import { useChessboardContext } from './ChessboardProvider.js'; +import { useCanDragPiece } from './ChessboardProvider.js'; import type { DraggingPieceDataType, PieceDataType } from './types.js'; type DraggableProps = { @@ -16,7 +16,11 @@ export function Draggable({ pieceType, position, }: DraggableProps) { - const { allowDragging, canDragPiece } = useChessboardContext(); + const canDrag = useCanDragPiece({ + piece: { pieceType }, + isSparePiece, + square: position, + }); const { setNodeRef, attributes, listeners } = useDraggable({ id: position, @@ -24,14 +28,7 @@ export function Draggable({ isSparePiece, pieceType, }, - disabled: - !allowDragging || - (canDragPiece && - !canDragPiece({ - piece: { pieceType }, - isSparePiece, - square: position, - })), + disabled: !canDrag, }); return ( diff --git a/src/Droppable.tsx b/src/Droppable.tsx index f692527..fe3641f 100644 --- a/src/Droppable.tsx +++ b/src/Droppable.tsx @@ -1,14 +1,19 @@ import { useDroppable } from '@dnd-kit/core'; +import { memo } from 'react'; -type DroppableProps = { - children: (props: { isOver: boolean }) => React.ReactNode; - squareId: string; -}; +import { Square, type SquareProps } from './Square.js'; -export function Droppable({ children, squareId }: DroppableProps) { +export const Droppable = memo(function Droppable({ + squareId, + ...square +}: Omit) { const { isOver, setNodeRef } = useDroppable({ id: squareId, }); - return
{children({ isOver })}
; -} + return ( +
+ +
+ ); +}); diff --git a/src/Piece.tsx b/src/Piece.tsx index b18e4e4..86c8abf 100644 --- a/src/Piece.tsx +++ b/src/Piece.tsx @@ -1,8 +1,10 @@ -import { memo } from 'react'; +import { memo, use, useEffect, useState } from 'react'; -import { useChessboardContext } from './ChessboardProvider.js'; +import { + ChessboardSettingsContext, + useCanDragPiece, +} from './ChessboardProvider.js'; import type { DraggingPieceDataType, PieceDataType } from './types.js'; -import { useEffect, useState } from 'react'; import { defaultDraggingPieceGhostStyle, defaultDraggingPieceStyle, @@ -13,43 +15,43 @@ type PieceProps = { isSparePiece?: DraggingPieceDataType['isSparePiece']; position: DraggingPieceDataType['position']; pieceType: PieceDataType['pieceType']; + ghost?: boolean; + moveTo?: string; }; +const noAnimation: React.CSSProperties = {}; + export const Piece = memo(function Piece({ clone, isSparePiece = false, position, pieceType, + ghost = false, + moveTo, }: PieceProps) { const { id, - allowDragging, animationDurationInMs, boardOrientation, - canDragPiece, - draggingPiece, draggingPieceStyle, draggingPieceGhostStyle, pieces, - positionDifferences, onPieceClick, - } = useChessboardContext(); + } = use(ChessboardSettingsContext)!.settings; + const canDrag = useCanDragPiece({ + piece: { pieceType }, + isSparePiece, + square: position, + }); - const [animationStyle, setAnimationStyle] = useState({}); + const [animationStyle, setAnimationStyle] = useState(noAnimation); - let cursorStyle = clone ? 'grabbing' : 'grab'; - if ( - !allowDragging || - (canDragPiece && - !canDragPiece({ piece: { pieceType }, isSparePiece, square: position })) - ) { - cursorStyle = 'pointer'; - } + const cursorStyle = canDrag ? (clone ? 'grabbing' : 'grab') : 'pointer'; useEffect(() => { - if (positionDifferences[position]) { + if (moveTo) { const sourceSquare = position; - const targetSquare = positionDifferences[position]; + const targetSquare = moveTo; const squareWidth = document .querySelector(`#${id}-square-${sourceSquare}`) @@ -74,9 +76,9 @@ export const Piece = memo(function Piece({ zIndex: 10, }); } else { - setAnimationStyle({}); + setAnimationStyle(noAnimation); } - }, [positionDifferences]); + }, [moveTo]); const PieceSvg = pieces[pieceType]; @@ -89,7 +91,7 @@ export const Piece = memo(function Piece({ ...(clone ? { ...defaultDraggingPieceStyle, ...draggingPieceStyle } : {}), - ...(!clone && draggingPiece?.position === position + ...(!clone && ghost ? { ...defaultDraggingPieceGhostStyle, ...draggingPieceGhostStyle } : {}), width: '100%', diff --git a/src/SparePiece.tsx b/src/SparePiece.tsx index 582e1b6..0f84a52 100644 --- a/src/SparePiece.tsx +++ b/src/SparePiece.tsx @@ -1,3 +1,6 @@ +import { use } from 'react'; + +import { ChessboardLiveContext } from './ChessboardProvider.js'; import { Draggable } from './Draggable.js'; import { Piece } from './Piece.js'; @@ -6,9 +9,17 @@ type SparePieceProps = { }; export function SparePiece({ pieceType }: SparePieceProps) { + const { draggingPiece, positionDifferences } = use(ChessboardLiveContext)!; + return ( - + ); } diff --git a/src/Square.tsx b/src/Square.tsx index 910064f..11dc6e3 100644 --- a/src/Square.tsx +++ b/src/Square.tsx @@ -1,6 +1,9 @@ -import { memo, useEffect, useRef, useState } from 'react'; +import { memo, use, useEffect, useRef, useState } from 'react'; -import { useChessboardContext } from './ChessboardProvider.js'; +import { + ChessboardLiveContext, + ChessboardSettingsContext, +} from './ChessboardProvider.js'; import { defaultAlphaNotationStyle, defaultDarkSquareNotationStyle, @@ -11,36 +14,42 @@ import { defaultNumericNotationStyle, defaultSquareStyle, } from './defaults.js'; -import { SquareDataType } from './types.js'; +import { Draggable } from './Draggable.js'; +import { Piece } from './Piece.js'; +import type { PieceDataType, SquareDataType } from './types.js'; import { columnIndexToChessColumn, isTouchEndWithinSquare } from './utils.js'; -type SquareProps = { - children?: React.ReactNode; - squareId: SquareDataType['squareId']; - isLightSquare: SquareDataType['isLightSquare']; +export type SquareProps = SquareDataType & { isOver: boolean; + pieceType?: string; + rendererPiece?: PieceDataType; + customSquareStyle?: React.CSSProperties; + ghost: boolean; + moveTo?: string; }; export const Square = memo(function Square({ - children, squareId, isLightSquare, isOver, + pieceType, + rendererPiece, + customSquareStyle, + ghost, + moveTo, }: SquareProps) { // track if we are drawing an arrow so that onSquareRightClick is not fired when we finish drawing an arrow const [isDrawingArrow, setIsDrawingArrow] = useState(false); - const [isClickingOnMobile, setIsClickingOnMobile] = useState(false); + const touchStartDrags = useRef(null); + const { settings, liveRef, dragStarts } = use(ChessboardSettingsContext)!; const { id, allowDrawingArrows, boardOrientation, chessboardColumns, chessboardRows, - currentPosition, - draggingPiece, squareStyle, - squareStyles, darkSquareStyle, lightSquareStyle, dropSquareStyle, @@ -56,12 +65,17 @@ export const Square = memo(function Square({ onSquareMouseUp, onSquareRightClick, squareRenderer, - newArrowStartSquare, setNewArrowStartSquare, setNewArrowOverSquare, drawArrow, clearArrows, - } = useChessboardContext(); + } = settings; + const pieceHere = () => liveRef.current.currentPosition[squareId] ?? null; + + // Only the hovered square needs to report live position changes during a drag. + const hoveredState = isOver ? use(ChessboardLiveContext) : null; + const hoveredPosition = hoveredState?.currentPosition; + const hoveredPiece = hoveredState?.draggingPiece; // track previous isOver to only fire onMouseOutSquare on transition const prevIsOverRef = useRef(isOver); @@ -69,26 +83,35 @@ export const Square = memo(function Square({ // handle firing onMouseOverSquare and onMouseOutSquare during drag operations // as onMouseOver and onMouseLeave do not fire during dragging useEffect(() => { - if (isOver && draggingPiece) { + if (isOver && hoveredPiece) { onMouseOverSquare?.({ - piece: currentPosition[squareId] ?? null, + piece: pieceHere(), square: squareId, }); - } else if (!isOver && draggingPiece && prevIsOverRef.current) { + } else if ( + !isOver && + liveRef.current.draggingPiece && + prevIsOverRef.current + ) { onMouseOutSquare?.({ - piece: currentPosition[squareId] ?? null, + piece: pieceHere(), square: squareId, }); } prevIsOverRef.current = isOver; - }, [currentPosition, draggingPiece, isOver, squareId]); + }, [hoveredPosition, hoveredPiece, isOver, squareId]); - // if we are dragging a piece, we are no longer clicking on mobile as that is a drag operation, so reset the clicking on mobile state - useEffect(() => { - if (draggingPiece && isClickingOnMobile) { - setIsClickingOnMobile(false); - } - }, [draggingPiece, isClickingOnMobile]); + const children = + pieceType !== undefined ? ( + + + + ) : null; const column = squareId.match(/^[a-z]+/)?.[0]; const row = squareId.match(/\d+$/)?.[0]; @@ -110,14 +133,14 @@ export const Square = memo(function Square({ onClick={(e) => { if (e.button === 0) { onSquareClick?.({ - piece: currentPosition[squareId] ?? null, + piece: pieceHere(), square: squareId, }); } }} onTouchStart={() => { - // in order to prevent onTouchEnd from firing if we are dragging within the same square, we need to store if a touch has started so that we can reset it if we drag, and if it isn't reset by the time the touch ends, we know it was a tap and can fire the click event - setIsClickingOnMobile(true); + // A drag starting before touchend disqualifies the gesture as a tap. + touchStartDrags.current = dragStarts.current; }} onTouchEnd={(e) => { // Prevent default to avoid double-firing with onClick on some devices @@ -126,20 +149,20 @@ export const Square = memo(function Square({ // we only want to fire onSquareClick if the touch event ended within the same square as it started const within = isTouchEndWithinSquare(id, squareId, e); - if (within && isClickingOnMobile) { + if (within && touchStartDrags.current === dragStarts.current) { onSquareClick?.({ - piece: currentPosition[squareId] ?? null, + piece: pieceHere(), square: squareId, }); } - setIsClickingOnMobile(false); + touchStartDrags.current = null; }} onContextMenu={(e) => { e.preventDefault(); if (!isDrawingArrow) { onSquareRightClick?.({ - piece: currentPosition[squareId] ?? null, + piece: pieceHere(), square: squareId, }); } @@ -154,13 +177,14 @@ export const Square = memo(function Square({ } onSquareMouseDown?.( { - piece: currentPosition[squareId] ?? null, + piece: pieceHere(), square: squareId, }, e, ); }} onMouseUp={(e) => { + const { newArrowStartSquare } = liveRef.current; if (e.button === 2) { if ( allowDrawingArrows && @@ -182,13 +206,14 @@ export const Square = memo(function Square({ } onSquareMouseUp?.( { - piece: currentPosition[squareId] ?? null, + piece: pieceHere(), square: squareId, }, e, ); }} onMouseOver={(e) => { + const { draggingPiece, newArrowStartSquare } = liveRef.current; // right mouse button is held down and we are drawing an arrow if ( e.buttons === 2 && @@ -210,16 +235,16 @@ export const Square = memo(function Square({ // don't fire when dragging as that is handled by the useEffect if (!draggingPiece) { onMouseOverSquare?.({ - piece: currentPosition[squareId] ?? null, + piece: pieceHere(), square: squareId, }); } }} onMouseLeave={() => { // don't fire when dragging as that is handled by the useEffect - if (!draggingPiece) { + if (!liveRef.current.draggingPiece) { onMouseOutSquare?.({ - piece: currentPosition[squareId] ?? null, + piece: pieceHere(), square: squareId, }); } @@ -270,7 +295,7 @@ export const Square = memo(function Square({ ) : null} {squareRenderer?.({ - piece: currentPosition[squareId] ?? null, + piece: rendererPiece ?? null, square: squareId, children, }) || ( @@ -278,7 +303,7 @@ export const Square = memo(function Square({ style={{ width: '100%', height: '100%', - ...squareStyles[squareId], + ...customSquareStyle, }} > {children} diff --git a/src/index.ts b/src/index.ts index fb1cc9c..656df54 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,9 @@ export * from './Chessboard.js'; -export * from './ChessboardProvider.js'; +export { + ChessboardProvider, + useChessboardContext, +} from './ChessboardProvider.js'; +export type { ChessboardOptions } from './ChessboardProvider.js'; export * from './defaults.js'; export * from './pieces.js'; export * from './SparePiece.js';