react-chess / chessground

Chessground React Wrapper
https://www.npmjs.com/package/@react-chess/chessground
GNU General Public License v3.0
29 stars 5 forks source link

Add API callback prop #14

Closed isofarro closed 12 months ago

isofarro commented 1 year ago

The current React component doesn't expose the Chessground API in it's interface, which makes it difficult to interact directly with the board from other components.

I've surfaced the API in a callback props called onApiReady. This makes the Chessground API available to calling code, and allows interactions like making a move on the board, resetting the board to a new position, and adding arrows. API interface documentation here: https://github.com/lichess-org/chessground/blob/master/src/api.ts

Sample code demonstrating its use:

import Chessground from "@react-chess/chessground"
import { Config } from 'chessground/config'
import { Api } from 'chessground/api'
import { Key } from 'chessground/types'

const CONFIG: Config = {
  fen: "rnbq1rk1/1p3pbp/p2p1np1/2pP4/P3P3/2NB4/1P2NPPP/R1BQ1RK1 b - a3 0 10",
  lastMove: ["a2", "a4"],
  turnColor: "black",
  movable: {
    free: false
  }
}

const MOVES = "d8c7 e2g3 b8d7 h2h3 c5c4 d3c2 a8b8 c1e3 d7c5 a4a5 c8d7 d1d2 b7b5".split(" ")

export const BasicMovesView = () => {

  const onApiReadyHandler = (api: Api) => {
    const interval = setInterval(() => {
      const move: string = MOVES.shift() as string
      if (move) {
        api.move(move.substring(0, 2) as Key, move.substring(2,4) as Key)
      } else {
        clearInterval(interval)
      }
    }, 2000)
  }

  return (
    <Chessground width={640} height={640} config={CONFIG} onApiReady={onApiReadyHandler} />
  )
}
H-Richard commented 1 year ago

Hey, thanks so much for opening this PR :)

This is quite a nice approach, but I'm wondering if it's cleaner to expose the api through forwardRef and useimperativehandle?

that way we can more easily expose other control methods to the parent, maybe we can even build a few helpers on top of the exposed api to make controlling the chess board easier

isofarro commented 12 months ago

Closing in preference for #16 which uses forwardRef and useImperativeHandler.