GithubHelp home page GithubHelp logo

clariity / react-chessboard Goto Github PK

View Code? Open in Web Editor NEW
290.0 290.0 86.0 5.24 MB

The React Chessboard Library used at ChessOpenings.co.uk. Inspired and adapted from the unmaintained Chessboard.jsx.

Home Page: https://react-chessboard.vercel.app

License: MIT License

JavaScript 0.96% TypeScript 94.91% MDX 4.13%
chess chessboard chessjs drag-and-drop javascript npm npm-package react react-chessboard reactjs

react-chessboard's People

Contributors

achim-k avatar benjaminknox avatar clariity avatar devarches avatar keeghanm avatar leedavidcs avatar manukyanq avatar matthewherrmanndev avatar navgeet avatar orivoir avatar orta avatar poorneshhn avatar richardjzhang avatar robbertkl avatar samanpwbb avatar saravmajestic avatar snelsi avatar terasurfer avatar tronikelis avatar zekicaneksi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

react-chessboard's Issues

onPieceDrop doesn't work correctly

Hello, I need help with a strange problem

If I initialize the arguments of the onPieceDrop function, then the chessboard does not care if I return true or false, the move is not made (example 1).

const onPieceDrop = (sourceSquare: Square, targetSquare: Square, piece: Piece) => { return true }

If I don't initialize the arguments of the onPieceDrop function, then the chessboard doesn't care if I return true or false, the move is made (example 2).

const onPieceDrop = () => { return true }

Am I the only one with this problem? Please help resolve this issue.

When the container div of the board has a transform: translate it does this

My mouse is actually at where the the blue marking is.
And when i remove the transform: translate(-50%,-50%) property of the container div, the problem resolves.

Any ideas? Or i could prove more info if needed.

edit: under the blue marking, there is nothing. i first wanted to mark with black pen but i thought it would be hard to notice. then i marked with the blue pen at the same spot. sorry for confusion.

image

I couldn't build the example in my local

Test your changes using the example folder npm run build cd example npm start

Since there are package.json files in only the example and package folders. And there is the cd example command in the explanation, i assume that we run npm run build in the package folder. And npm start in the example folder.

Before running commands, i of course did npm install.

After i do npm start all i see is this;

image

Sooo, i tried to change to render to createRoot but other errors just stayed as they are.

So i just wanted to ask what i was doing wrong.

Thanks

Use return value of onPieceDrop to actually move the piece, or change the docs

Currently, the implementation functions so that devs have to keep track of the state of the game manually when using the onPieceDrop. The docs say that you should return whether the move was valid or not, leading me to believe that this is a function that I can use to control whether the move was valid, and the board will then move it based on whether that was true or false, instead of me having to keep track of that state. I had to go look through the source code and find a comment in the 10k line script that says that this state has to manually be stored and applied to the board.

I think that just having it to be able to control whether the move is valid or not would be the best solution, as that means that it is possible to use this function without having to keep the state manually. At the very least, the docs should clearly state this, and perhaps even comment about it in the example.

Custom square rendering based on game state

Hello,

This is such a wonderful library, and I know what I am trying to do is possible (since you do it on chess openings!) so I thought I'd just ask: How do you achieve the custom rendering of the squares to show possible moves when a piece is clicked? I'd figure there'd be some method to render the board squares based on its position, but I couldn't see it in the docs. Am I missing something obvious?

Responsive boardWidth not working

Hello,

I am new to react and chessboard js.
i am using your basic 'click to move' code , my issue is with board width, its not responsive. can you pls help me with this.

onPieceDrop not triggered when promoting

When I am trying to promote my pawn while capturing a piece, the onPieceDrop event is not triggered.

FEN = "1nb1kbnr/2P2ppp/r7/2p5/3p4/8/PP3PPP/RNBQKBNR w KQk - 0 9"

Styled Squares (using drop and drag) + Click to Move feature

Hello !

I like very much the "Styled Squares" example (with drag and drop pieces).
But i have problem for adding the "Click to Move" to this.

It is possible, you do a new example : "Styled Squares with drag and drop and click to move" ?
I really appreciate this. I was close to something but it is strange :

;-)

Dependency warnings (yarn)

yarn keeps throwing these warnings at me after installing the package on a create-react-app typescript project (node v14.16.1).
The component still works wonderfully, anything I could do to get rid of the dependency warnings?

warning "react-chessboard > [email protected]" has incorrect peer dependency "react@^16.13".
warning "react-chessboard > [email protected]" has incorrect peer dependency "react-dnd-html5-backend@^11.1.3".
warning "react-chessboard > [email protected]" has incorrect peer dependency "react-dnd-touch-backend@^11.1.3".
warning "react-chessboard > [email protected]" has incorrect peer dependency "react-dom@^16.13".
warning "react-chessboard > react-dnd-multi-backend > [email protected]" has incorrect peer dependency "react@^16.13.1".
warning "react-chessboard > react-dnd-multi-backend > [email protected]" has incorrect peer dependency "react-dnd@^11.1.3".

Drag-Drop issues

Hello,

I installed a bare bones project following the README.
Unfortunately, there seems to be an issue with the drag-and-drop : while dragging a piece, it disappears completely, and reappears only when releasing it on a square.

It sometimes kinda works, as the piece is semi-transparent, but the behaviour seems random (moving the same pieces makes it disapeear while dragging again).

Is there any configuration I'm missing ?

EDIT : I've cloned this repo and ran the examples, no issue. So it's probably something related to my project. I've ran a simple create-react-app, but with a typescript template. Could it be linked to typescript ?

EDIT2 : Tried with a vanilla JS create-react-app, same issue. Probably not related to typescript.

square style flickering when dragged piece passes over from one square to other

Untitled 3

(converting a 60fps vid to gif made a nice slowmo there, actually it's much faster and more annoying, flickering a few times in a row)

In the provided Storybook examples, it occurs in all of them that have draggable pieces except for the first one ("Configurable Board") where it also occurs but rarely and less consistently. Shows up in all combinations of Chrome/Firefox + Win11/Linux Mint for me. I don't understand React well enough to debug this myself so far ngl

move function doesn't work second time

i have a for loop from where i am trying to get fen() with the help of move()

for (var i = 0; i < tempLiveGameMoves.length; i++) {
let game_movement = game.move(tempLiveGameMoves[i].move, {sloppy:true});
let gameHistory = game.history({ verbose: true });
tempGameFen.push(game.fen());
}

the move() works fine on 1st render but when i update my state it doesn't work, it shows 'null' value.
can you pls help me understand what am I doing wrong ?

Stockfish integration

It would be great to have stockfish integrated with the chessboard. I have created some custom in a private repo, but I am more than happy to add the implementation which shall be relevant for a larger audience.

Promotion bugs

Hello!

According to the rules, the dialog is not supposed to pop up when a promotion is illegal, but when it is legal, I want to choose which piece to promote to on my own.
The problem is that this library does show the dialog when a pawn is moved to the other end of the board illegally (over 3 squares, let's say), but when it is moved there legally, it always selects the queen on its own. This is not the desired behaviour, I suspect. Do you have any ideas?

gameCopy.move is not a function

Following the examples in the readme I came across this error:

useState updates game, however, the chess board is not re-rendered using position={game.fen()}

Additionally, I get the error "Uncaught TypeError: gameCopy.move is not a function"

Would appreciate any feedback.

export const Board = () => {

  const [game, setGame] = useState(new Chess());

  const makeAMove = (move) => {
    const gameCopy = { ...game };
    const result = gameCopy.move(move);
    setGame(gameCopy);
    return result; // null if the move was illegal, the move object if the move was legal
  }

  const onDrop = (sourceSquare, targetSquare) => {
    const move = makeAMove({
      from: sourceSquare,
      to: targetSquare,
      promotion: "q", // always promote to a queen for example simplicity
    });
    console.log(game.fen())

    // illegal move
    if (move === null) return false;

    return true;
  }

  return (<Chessboard onPieceDrop={onDrop} position={game.fen()} />);
}

Migration from chessboardjsx to react-chessboard

This library is really helpful, but I used to use chessboardjsx and many of the properties changed, which made migration difficult.

I think that the property names should to match chessboardjsx

Using Chessboard causes issue with apps already using react-dnd

I have a DndProvider component at the root of my app. When rendering a Chessboard component, this interferes with the rest of the app, disabling drag / drop in the whole app. Is there an option to render a Chessboard without the DndProvider? Or is there some other way this can integrate with apps already using react-dnd?

Some drawbacks

Hi,

According to the playground https://react-chessboard.com/

  1. the exchange King-rook (O-O) dont work and i suppose (O-O-O) dont work [king's side and queen's side]
  2. no dots of mouvement possibilities
  3. no red color or something when ennemy king have danger

as a chess player the basics are not here (1)

Doesn't the Usage / Basic example in the README has an async issue?

I was trying to implement this board to my site. But sometimes, even tho my move was valid even though the board registered my move (didn't put my piece back into its original position), the "move" variable's value still null. I changed the value to "123", and made many invalid moves on purpose. And logged the "move"s value. And what do i see? It's sometimes 123 and sometimes null. I'm a newbie developer and this issue put me two days behind because no errors, no nothing and sometimes gives errors, and sometimes doesn't...

  const [game, setGame] = useState(new Chess());

  function safeGameMutate(modify) {
    setGame((g) => {                  <---- ASYNC FUNCTION, so this kinda makes the safeGameMutate function an async function
      const update = { ...g };
      modify(update);
      return update;
    });
  }
  
  function onDrop(sourceSquare, targetSquare) {
    let move = null;
    safeGameMutate((game) => {                    <-------- Calling an async function to set the move variable. and instantly after, checking it's value.
      move = game.move({
        from: sourceSquare,
        to: targetSquare,
        promotion: "q", // always promote to a queen for example simplicity
      });
    });
    if (move === null) return false; // illegal move
    setTimeout(makeRandomMove, 200);
    return true;
  }

My solution for my instance was to just use game.move() before hands, if it didn't return null, i just updated the board with the safeGameMutate function.

Multiple boards issue

Hi guys, I am trying to implement this board in a project using react 18 and latest version of material ui framework for styles. I've implemented 3 different boards (all using different id attribute), one for big screen, other for medium and one for small screens and depending on resolution i use display -> none to hide it or not.

Problem is that after implementing three boards at the same time I am getting this error when trying to make a move:

Uncaught Error: Cannot have two HTML5 backends at the same time.
at HTML5BackendImpl.setup (index.esm.js:3650:1)
at DragDropManagerImpl.handleRefCountChange (index.esm.js:890:1)
at Object.dispatch (index.esm.js:308:1)
at HandlerRegistryImpl.addSource (index.esm.js:1595:1)
at registerSource (index.esm.js:2448:1)
at registerDragSource (index.esm.js:2985:1)
at commitHookEffectListMount (react-dom.development.js:23150:1)
at commitLayoutEffectOnFiber (react-dom.development.js:23268:1)
at commitLayoutMountEffects_complete (react-dom.development.js:24688:1)
at commitLayoutEffects_begin (react-dom.development.js:24674:1)

Having multiple boards is a limitation of this project or am I doing something wrong? Could you please clarify a little bit? Thanks in advance!

cant install peer dependency [react] [react-dom]

Currently with React 18 can't install react-chessboard with npm error below:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"^18.1.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.14.0 || ^17.0.2" from [email protected]
npm ERR! node_modules/react-chessboard
npm ERR!   react-chessboard@"*" from the root project

I think peer dependencies specified in package.json is out date

"react": "^16.14.0 || ^17.0.2",

"react-dom": "^16.14.0 || ^17.0.2"

I propose upgrade peer dependency at latest version

Putting flex on the board wrapper breaks the chessboard

      <div className="max-w-[70vh] bg-white rounded-xl p-2 flex">
        <ReactChessBoard position={game.fen()} />
        <div className="flex space-x-2">
          <button className="flex p-2 bg-primaryButtonColor text-buttonTextColor rounded-xl">
            <ChevronLeftIcon />
          </button>
          <button className="flex p-2 bg-primaryButtonColor text-buttonTextColor rounded-xl">
            <ChevronRightIcon />
          </button>
        </div>
      </div>

The board breaks here sometimes it renders sometimes it just shows 0?

Type of prop `customSquare` is missing

When installing react-chessboard@latest, the prop customSquare is missing on the exported Chessboard component.

When looking at react-chessboard within node_modules:

export declare const Chessboard: import("react").ForwardRefExoticComponent<Pick<ChessboardProps, "animationDuration" | "areArrowsAllowed" | "arePiecesDraggable" | "arePremovesAllowed" | "boardOrientation" | "boardWidth" | "clearPremovesOnRightClick" | "customArrows" | "customArrowColor" | "customBoardStyle" | "customDarkSquareStyle" | "customDndBackend" | "customDndBackendOptions" | "customDropSquareStyle" | "customLightSquareStyle" | "customPieces" | "customPremoveDarkSquareStyle" | "customPremoveLightSquareStyle" | "customSquareStyles" | "dropOffBoardAction" | "id" | "isDraggablePiece" | "getPositionObject" | "onArrowsChange" | "onDragOverSquare" | "onMouseOutSquare" | "onMouseOverSquare" | "onPieceClick" | "onPieceDragBegin" | "onPieceDragEnd" | "onPieceDrop" | "onSquareClick" | "onSquareRightClick" | "position" | "showBoardNotation" | "snapToCursor"> & import("react").RefAttributes<ClearPremoves>>;

However, when I rebuild my fork of react-chessboard this prop does exist. Could react-chessboard be rebuilt and republished?

Transform breaks animations

I need to transform: scale() a parent container of the chessboard. Everything works fine, but animations are broken,
is that something you plan to fix, or is that out of scope.

Bildschirmaufnahme.2023-04-12.um.19.12.43.mov

Not seeing new promotion options in the node build version

Sorry I know it has only been out for an hour. Just checking if this is a bug or not.

"react-chessboard": "^3.0.0",

Deleted old package
Reinstalled with new package
Cannot add autoPromoteToQueen prop

/// <reference types="react" />
import { ChessboardProps } from "./types";
export type ClearPremoves = {
    clearPremoves: (clearLastPieceColour?: boolean) => void;
};
export declare const Chessboard: import("react").ForwardRefExoticComponent<Pick<ChessboardProps, "animationDuration" | "areArrowsAllowed" | "arePiecesDraggable" | "arePremovesAllowed" | "boardOrientation" | "boardWidth" | "clearPremovesOnRightClick" | "customArrows" | "customArrowColor" | "customBoardStyle" | "customDarkSquareStyle" | "customDndBackend" | "customDndBackendOptions" | "customDropSquareStyle" | "customLightSquareStyle" | "customPieces" | "customPremoveDarkSquareStyle" | "customPremoveLightSquareStyle" | "customSquare" | "customSquareStyles" | "dropOffBoardAction" | "id" | "isDraggablePiece" | "getPositionObject" | "onArrowsChange" | "onDragOverSquare" | "onMouseOutSquare" | "onMouseOverSquare" | "onPieceClick" | "onPieceDragBegin" | "onPieceDragEnd" | "onPieceDrop" | "onSquareClick" | "onSquareRightClick" | "position" | "showBoardNotation" | "snapToCursor"> & import("react").RefAttributes<ClearPremoves>>;


Board not rendering

When I open my site on a desktop, it works perfectly fine but when I open it on my phone I get this image of a sideways king. Could you please tell me when this King comes up. Could you please help in identifying why this happens

tempFileForShare_20230314-110505

Please let me know if you need any additional information. P.S I am new to react and JS. Thanks!

EDIT: There was an error initializing one of the variables and that caused the error boundary to trigger the image being displayed

Chess board not responsive & has a fixed width/height

Hey, thanks for all the work you've done here, I'm having fun implementing https://dailychess.club and want it to work on mobile.

Seems like the board has a fixed width and height of 560px and setting it to anything else doesn't seem to allow it to take 100% of the width of the viewport. I'm not finding any option to allow it to be responsive.

What's your opinion on the matter? Are you able to make it responsive for mobile phones on your end?

Thanks !

Styled Board + snapToCursor breaks

Just checked https://react-chessboard.com and only on the Styled Board, while dragging, I see this:

Screen Shot 2022-02-20 at 03 25 27

(on Safari 15.3 @ macOS Monterey)

Seems to be related to the new snapToCursor, although weirdly enough in my own setup (where I also use custom pieces with images) I don't have this issue. There I'm using background-image on DIVs, so my guess is this is related to dragging IMGs. They have a default drag preview which was probably always there for IMGs, but wasn't really noticeable before snapToCursor because they lined up perfectly.

If this is indeed the case, I'm not sure it can be fixed in the lib, but there are a few workarounds for people to use (and can be applied to the Styled Board example):

  • switching to DIVs with a background-image
  • turning off snapToCursor
  • switching to a different react-dnd backend (see also #19), because this probably only happens on HTML5Backend

Install package failed

Please check this issue, reproduce steps:

  1. npx create-react-app@latest my-chess
  2. cd my-chess
  3. npm i react-chessboard

Error details:
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR! peer react@"" from @testing-library/[email protected]
npm ERR! node_modules/@testing-library/react
npm ERR! @testing-library/react@"^12.1.2" from the root project
npm ERR! peer react@"17.0.2" from [email protected]
npm ERR! node_modules/react-dom
npm ERR! peer react-dom@"
" from @testing-library/[email protected]
npm ERR! node_modules/@testing-library/react
npm ERR! @testing-library/react@"^12.1.2" from the root project
npm ERR! react-dom@"^17.0.2" from the root project
npm ERR! 1 more (react-chessboard)
npm ERR! 4 more (react-scripts, the root project, react-chessboard, react-dnd)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.13.1" from [email protected]
npm ERR! node_modules/react-dnd-multi-backend/node_modules/react-dnd-preview
npm ERR! react-dnd-preview@"^6.0.2" from [email protected]
npm ERR! node_modules/react-dnd-multi-backend
npm ERR! react-dnd-multi-backend@"^6.0.2" from [email protected]
npm ERR! node_modules/react-chessboard
npm ERR! react-chessboard@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

Basic example minor fix

In the basic example, I see the following line:

const gameCopy = { ...game };

I don't think this will work, because the copy will only inherit the enumerable properties, instead of the prototype's methods.

Therefore the following line will fail:

const result = gameCopy.move(move);

Easily fixed with using:

const gameCopy = Object.create(game);

Errors When Using Basic Example

Error 1: Import Error

This is the error I received when using the basic example:

Failed to compile.

Attempted import error: 'chess.js' does not contain a default export (imported as 'Chess').
ERROR in ./src/App.js 11:39-44
export 'default' (imported as 'Chess') was not found in 'chess.js' (possible exports: BISHOP, BLACK, Chess, DEFAULT_POSITION, KING, KNIGHT, PAWN, QUEEN, ROOK, SQUARES, WHITE, __esModule, validateFen)

webpack compiled with 1 error

Attempted Solution

I changed line 2 from
import Chess from "chess.js"; to
import { Chess } from "chess.js";
which now displays the chess board.

Error 2: Uncaught TypeError

However, upon making a move by dragging and dropping a piece, I get the following error message:

Uncaught TypeError: gameCopy.move is not a function
    at makeAMove (App.js:10:1)
    at onDrop (App.js:24:1)
    at handleSetPosition (index.esm.js:4905:1)
    at Object.drop (index.esm.js:5180:1)
    at DropTargetImpl.drop (index.esm.js:2775:1)
    at determineDropResult (index.esm.js:687:1)
    at index.esm.js:670:1
    at Array.forEach (<anonymous>)
    at DragDropManagerImpl.drop (index.esm.js:669:1)
    at Object.drop (index.esm.js:823:1)

My suspicion is that the spread operator is not working as intended for some reason. Could this be confirmed and is there any solution for this issue? Thank you!

Customise board size

I am using this library for a school project and I need to be able to customise the board size as in make 6×6, 9×9... how do I go about this ?

Automated testing with Jest

Had a hell of a time trying to figure this one out. Thought I would share the solution I found here to help anyone else trying to set up automated Jest tests with ReactChessboard.

Solution for writing automated tests with Jest

  1. npx create-react-app react-chessboard-jest-testing, cd react-chessboard-jest-testing
  2. npm i react-chessboard
  3. npm i --save-dev react-dnd-test-utils react-dnd-test-backend

Getting Jest to play nicely with ESM modules

package.json

{
  ...
  "jest": {
    "transformIgnorePatterns": [
      "/node_modules/(?!(@?react-dnd[^/]*|dnd-core)/)"
    ]
  }
}

Writing the test

src/App.test.js

import React from 'react';
import { act } from 'react-dom/test-utils';
import { cleanup, render } from '@testing-library/react';
import { fireDragDrop, tick } from 'react-dnd-test-utils';
import { Chessboard as ReactChessboard } from 'react-chessboard';

/* act and await tick to ensure setup animation completes  
 * (and sets waitingForAnimation to false) before running assertions
 */
beforeEach(async () => {
  await act(async () => {
    const props = {
      position: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", // starting position
      onPieceDrop: () => true,
      animationDuration: 0, // **important** to not slow down your tests
    }
    render (<ReactChessboard {...props} />);
    await tick();
  })
})

afterEach(() => {
  cleanup()
})

test('e2 to e4', async () => {
  let e2pawn = document.querySelector('[data-square=e2] [draggable]');
  let e4square = document.querySelector('[data-square=e4]')

  expect(e2pawn).toBeInTheDocument();
  expect(e4square.querySelector('[draggable]')).not.toBeInTheDocument();
  await fireDragDrop(e2pawn, e4square);
  expect(e2pawn).not.toBeInTheDocument();
  expect(e4square.querySelector('[draggable]')).toBeInTheDocument();
})

Tested on:

Brainstorming possible improvements

Using querySelector is not necessarily a best practice. By adding aria roles and labels, those calls could be replaced with the more standard testing-library queries.

test('can find white pawn', () => {
  render(
    <>
      <div role="gridcell" aria-label="e2 square">
          <div role="widget" aria-label="white e2 pawn" />
      </div>
    </>
  )

  let e2pawn = screen.getByRole('widget', { name: /white e2 pawn/i });
  expect(e2pawn).toBeInTheDocument();
})

I'm by no means an expert on accessibility. I went to both chess.com and lichess.org to see how they approach this, and it seems that they don't yet have any support for screen readers. Would be nice to get input from someone more knowledgeable about accessibility before making these changes and to think more broadly about the experience for visually impaired players.

Sping-based animations

Right now react-chessboard uses duration-based animations (

transition: `transform ${animationDuration}ms`,
) - these are good because they're simple and predictable. However, there is a big downside: further pieces move really fast, and closer pieces move really slow. Spring-based animations would offer natural-feeling movement regardless of the distance a piece has to travel.

I'd like to propose adopting https://react-spring.io/ for piece movement. A few questions/considerations to keep in mind:

  • React-spring would add about 38kb (raw) to bundle size. Is that acceptable?
  • We could give consumers the choice between spring-based and durational animations. Is this important?
  • Because react-spring is not durational, for consumers to synchronize their games with react-chessboard's animations, we would need to expose a new callback (onAnimationEnd).

@Clariity let me know what you think of this. I'm going to implement it for a project I'm working on and would be happy to contribute back if you're in support.

Notation Font

It is quite weird to see that the NotationStyle has a predefined font in it. Might it be possible to give custom font or let it use inherit?

Thanks for the project btw, it's really helpful.

Fails to compile

Firstly, thanks for the library. Unfortunately I got the following error, with the "Bare Minimum" and "Basic Example" examples. Probably there is a bug.

bug

Custom Square component

I would like to apply additional elements within a square, based on which square it is. Would it be possible to support a custom square renderer?

Currently, I see Square renders a div that takes a ref, style and children: https://github.com/Clariity/react-chessboard/blob/main/src/chessboard/components/Square.tsx#L123-L132

Instead of this div, would it be possible to provide our own renderer with this type?

interface CustomSquareProps {
    // pass down the children
    children: ReactNode;
    // pass down the ref
    squareRef: RefObject<HTMLElement>;
    // pass down the style
    style: CSSProperties;

    // extra props
    square: Square;
    squareColor: "white" | "black";
}

type CustomSquareRenderer = FC<CustomSquareProps>;

Add `data-piece` attribute to pieces html tags

This library marks square html tags with data-square and data-square-color.

But it looks like the pieces don't have any distinguishable className or data-attribute attached to them.
It would be very helpfull to attach data-piece attribute to tags, so they can be selected via CSS

Possible bug when undoing last move, and useRef question with Typescript

Following the example here: https://github.com/Clariity/react-chessboard/blob/main/example/src/boards/PlayVsPlay.js

It seems as though we need to call .clearPremoves() after undoing a move.

First, this seems like a bug or anti-pattern. Right now, calling .undo() without calling .clearPremoves() seems to not update the last piece color, resulting in the color that is supposed to be able to move not being able to (this if statement evaluates to true because lastPieceColour === piece[0]). When you attempt to move a piece of the other color, it still won't work, but some branching side effect of that check (I think here because my onPieceDrop handler correctly returns false because the underlying call to game.move() fails) corrects the color that is allowed to move, seemingly by calling clearPremoves(). If this is intended, the function should probably be renamed, or the last color logic refactored into another function, because the intention is unclear from that name. Or better yet, encapsulate this so we don't need to call any function after calling .undo().

Second, to call .clearPremoves() you need to use a ref (I think). However, Typescript is complaining that there is no ref property on Chessboard:

Type '{ id: number; position: string; onPieceDrop: (sourceSquare: Square, targetSquare: Square) => boolean; onSquareClick: (square: Square) => void; customBoardStyle: { ...; }; customSquareStyles: {}; boardWidth: number; ref: RefObject<...>; }' is not assignable to type 'IntrinsicAttributes & ChessBoardProps'.
  Property 'ref' does not exist on type 'IntrinsicAttributes & ChessBoardProps'.  TS2322

    176 |               }}
    177 |               boardWidth={boardWidth}
  > 178 |               ref={chessboardRef}
        |               ^
    179 |             />

My useRef:
const chessboardRef = useRef();

My Chessboard, where the error is originating from:

<Chessboard
  ...
  ref={chessboardRef}
/>

This might be just be a lack of understanding on my part with Typescript/React/useRef. If so, any help would be appreciated. Regardless of this ref issue, I think the first issue I pointed out is still a bug.

Thanks

Citation

I used this repository extensively in a university project and I would like to ba able to cite the repo in my report. Could you add your citation functionality to the repo please ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.