GithubHelp home page GithubHelp logo

willb335 / chessboardjsx Goto Github PK

View Code? Open in Web Editor NEW
261.0 10.0 75.0 4.77 MB

:black_square_button: Chessboard built for React

Home Page: https://chessboardjsx.com

License: MIT License

JavaScript 98.62% HTML 1.38%
chessboard react chess

chessboardjsx's Introduction

UNMAINTAINED

lucena position Carlsen 2016 Championship sicilian defense

A chessboard for React inspired by chessboard.js

Build Status Code Coverage PRs Welcome version MIT License Commitizen friendly semantic-release

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's dependencies:

npm install --save chessboardjsx

The package also depends on React. Make sure you have that installed as well.

Usage

Contributing

Please take a look at CONTRIBUTING.md to find out how to contribute.

What is Chessboard.jsx?

Chessboard.jsx is a React component with a flexible "just a board" API modeled from chessboard.js. It's compatible with touch as well as standard HTML5 drag and drop.

What can Chessboard.jsx not do?

The scope of Chessboard.jsx is limited to "just a board." This is intentional and makes Chessboard.jsx flexible for handling a multitude of chess-related problems.

Specifically, Chessboard.jsx does not understand anything about how the game of chess is played: how a knight moves, who's turn is it, is White in check?, etc.

Fortunately, the powerful chess.js library deals with exactly this sort of problem domain and plays nicely with Chessboard.jsx's flexible API.

Here is a list of things that Chessboard.jsx is not:

  • A chess engine
  • A legal move validator
  • A PGN parser

Chessboard.jsx is designed to work well with any of those software components, but the idea behind the library is that the logic that controls the board should be independent of those other domains.

Contributors

Thanks goes to these wonderful people (emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome!


Will

💻 📖 💡 ⚠️

Andrew Bashelor

📖

yougotgotyo

🤔

Roger Knapp

🤔

Tiago Serafim

💻 📖

Kef Schecter

🐛

Nils-Helge Garli Hegvik

💻

Levi Durfee

💻 📖

Chris

💻

Harrison Kerr

💻

LICENSE

MIT

chessboardjsx's People

Contributors

a-bash avatar dependabot[bot] avatar hwkerr avatar levidurfee avatar myarete avatar nilsga avatar slig avatar willb335 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  avatar  avatar  avatar  avatar

chessboardjsx's Issues

changing only piece type does not update completely

Hi, I'm having fun integrating chessboardjsx, but came upon an issue.

When a position includes only changes to the piece type, then the board is not completely updated.

position={{ a1: 'wQ' }}
...then...
position={{ a1: 'bQ' }}

For live example, try playing: https://attogram.github.io/EightQueens/ and view the developer console. A click places a wQ. If any piece is under attack, then it is changed to (customized) bQ. The new 'correct' position is being sent into <Chessboard>, but changes to existing pieces do not take effect.

code at: https://github.com/attogram/EightQueens

Any ideas? Thanks!

firefox

firefox drag layer disappears on drop

Need to introduce an event before drag start, i.e. "onClick"

Use case 1:
Developing an analysis/play board, I need to be able to record the piece that was clicked (aka select the piece for move). I would then need to use hover for styling the desired target, and again handle the event to move the piece.

Use case 2:
While developing a play board, I want to prevent the user from dragging a piece that is not allowed to be moved. This might be the wrong color, or may be a piece of the correct color with no valid moves.

Suggested signature:

    /** 
     * Signature: function(event: { piece: string, square: string, allowDrag: boolean }) => void
     */
    onClick: PropTypes.func,

Note:
allowDrag would default to true and if the function changes the value to false the drag operation would be cancelled. The event would also need to be fired when no piece was clicked to allow click-to-move behavior defined in use case 1 above.

Update with more props is needed

Hello ,
I am integrating Chessboard.jsx which happens to be very smooth and efficient . But I did find some differences between Chessboard.js and Chessboard.jsx functionalities. And how can I implement "OnDragStart" in Chessboard.jsx ? Will the upcoming versions of Chessboard.jsx have the missing props ? It will be of great help if I get to know when will the updates be available and what are the new features to be added in the next version , so that I can put my code accordingly and think for future scope .

I want piece animation

Specifically animations for castling would be just a joy! For example: castleAnimations={ true }

calcWidth , the zoom feature and the yellow highlight

  1. Requesting addition of an example using calcWidth function prop.
  2. My piece drag is pretty 'laggy'. How can one make it faster ?
  3. How to remove the zoom when moving the pieces.
  4. Any chance it can be rebuilt to use the newer react versions

Thank you. This lib came in handy.

Legacy context API warnings in React 16.3+

chessboardjsx is pinned to an old version (2.6.0) of react-dnd that uses React's legacy context API. This generates warnings in React 16.3+:

index.js:1 Warning: Legacy context API has been detected within a strict-mode tree.

The old API will be supported in all 16.x releases, but applications using it should migrate to the new version.

Please update the following components: DragDropContext(t), DragLayer(t)

Learn more about this warning here: https://fb.me/react-legacy-context
    in DragDropContext(t) (at src/index.js:7)
    in StrictMode (at src/index.js:6)
console.<computed> @ index.js:1
printWarning @ react-dom.development.js:88
error @ react-dom.development.js:60
(anonymous) @ react-dom.development.js:11432
push../node_modules/react-dom/cjs/react-dom.development.js.ReactStrictModeWarnings.flushLegacyContextWarning @ react-dom.development.js:11418
flushRenderPhaseStrictModeWarningsInDEV @ react-dom.development.js:23109
commitRootImpl @ react-dom.development.js:22396
unstable_runWithPriority @ scheduler.development.js:653
runWithPriority$1 @ react-dom.development.js:11039
commitRoot @ react-dom.development.js:22381
finishSyncRender @ react-dom.development.js:21807
performSyncWorkOnRoot @ react-dom.development.js:21793
scheduleUpdateOnFiber @ react-dom.development.js:21188
updateContainer @ react-dom.development.js:24373
(anonymous) @ react-dom.development.js:24758
unbatchedUpdates @ react-dom.development.js:21903
legacyRenderSubtreeIntoContainer @ react-dom.development.js:24757
render @ react-dom.development.js:24840
./src/index.js @ index.js:5
__webpack_require__ @ bootstrap:784
fn @ bootstrap:150
1 @ index.js:7
__webpack_require__ @ bootstrap:784
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.chunk.js:1
index.js:1 Warning: Legacy context API has been detected within a strict-mode tree.

The old API will be supported in all 16.x releases, but applications using it should migrate to the new version.

Please update the following components: DropTarget(t)

Learn more about this warning here: https://fb.me/react-legacy-context
    in DropTarget(t) (created by t)
    in div (created by t)
    in div (created by t)
    in t (created by Context.Consumer)
    in t (created by t)
    in div (created by t)
    in t (created by t)
    in t (created by DragDropContext(t))
    in DragDropContext(t) (at src/index.js:7)
    in StrictMode (at src/index.js:6)

Code that triggered the warnings:

import React from 'react';
import ReactDOM from 'react-dom';
import Chessboard from 'chessboardjsx';

ReactDOM.render(
  <React.StrictMode>
    <Chessboard />
  </React.StrictMode>,
  document.getElementById('root')
);

chessboardjsx version 2.4.2

Next js support?

I tried to use with next recently, and got the error "window not defined". Any idea how to solve?

wasSquareClicked is not a function

"wasSquareClicked" is undefined if sparePieces are enabled and the onDrop handler is defined. Example:

<Chessboard onDrop={(data) => {console.log(data)}} sparePieces={true}/>

Just drag a spare piece on the chessboard

context API warnings in React

Please update the following components: DragDropContext(t), DragLayer(t)

Warning: Legacy context API has been detected within a strict-mode tree.

The old API will be supported in all 16.x releases, but applications using it should migrate to the new version.

Please update the following components: DragDropContext(t), DragLayer(t)

Learn more about this warning here: https://reactjs.org/link/legacy-context
at DragDropContext(t) (http://localhost:3000/static/js/0.chunk.js:2540:14)
at Route (http://localhost:3000/static/js/0.chunk.js:44273:29)
at Switch (http://localhost:3000/static/js/0.chunk.js:44475:29)
at div
at Content
at Router (http://localhost:3000/static/js/0.chunk.js:43908:30)
at BrowserRouter (http://localhost:3000/static/js/0.chunk.js:43528:35)
at div
at App

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Updating the position of only one piece outside `onDrop` doesn't update the UI

Hi,

I've forked one demo here with this possible bug reproduced https://codesandbox.io/s/kxqxo8lwo3

One second after manually making a move (WithMoveValidation.js lines 80-89), it calls this.chess.undo() and updates the state. But somehow, as far as I could tell, getDerivedStateFromProps returns null to that change and now the internal state and the displayed board are different. (Try moving a white piece, waiting a second, and then moving another white piece)

Thank you very much and please let me know if you need any more details or a better bug report.

Accessibility

The chessboard needs accessibility upgrades.

  • Text alternatives and captions for non-text media (pieces)
  • Allow users to traverse the board and pick up pieces with only the keyboard

WebpackError: ReferenceError: window is not defined when using ChessboardJSX with Gatsby

I have a React component, and I want to include a Chessboard component within it.

So, I only added this line to my file.
import Chessboard from 'chessboardjsx';
I never actually used the Chessboard in my code, but it still returned this error:

  WebpackError: ReferenceError: window is not defined
  
  - chessboard.min.js:1 
    node_modules/chessboardjsx/dist/chessboard.min.js:1:253

When I remove that line, my code works as expected.

I'm using React v17.0 and Gatsby 2.27.5

Need a property to provide custom styles on specific board squares.

Use case:
In order to display possible valid/legal moves, moves resulting in threats, best moves, and other analytical display, I'd like to be able to use a prop to customize specific board squares. Thus the following would render the g5 square as solid red:

      <Chessboard
        id="board"
        position={this.state.fen}
        width={320}
        squareStyles={{
          g5: { backgroundColor: "red" }
        }}
        ... />

This could, in time, deprecate the use of selectedSquareStyle and selectedSquares since it would allow customization of board display in a number of ways. I would recommend retooling these two properties to simply overwrite (or merge) the value of squareStyles for each entry in selectedSquares with the value of selectedSquareStyle. This should reduce the maintenance of the two similar features.

TypeScript Typings

Hi Will,

First of all, thank you very much for this project. The docs and examples are awesome!

I've prepared a first version of a typings file and I'd like to know if this is welcome in this project. If it's, I'll open a PR.

Here's what I have so far:

type Square =
    "a8" | "b8" | "c8" | "d8" | "e8" | "f8" | "g8" | "h8" |
    "a7" | "b7" | "c7" | "d7" | "e7" | "f7" | "g7" | "h7" |
    "a6" | "b6" | "c6" | "d6" | "e6" | "f6" | "g6" | "h6" |
    "a5" | "b5" | "c5" | "d5" | "e5" | "f5" | "g5" | "h5" |
    "a4" | "b4" | "c4" | "d4" | "e4" | "f4" | "g4" | "h4" |
    "a3" | "b3" | "c3" | "d3" | "e3" | "f3" | "g3" | "h3" |
    "a2" | "b2" | "c2" | "d2" | "e2" | "f2" | "g2" | "h2" |
    "a1" | "b1" | "c1" | "d1" | "e1" | "f1" | "g1" | "h1"
;

type Piece =
    "wP" | "wN" | "wB" | "wR" | "wQ" | "wK" |
    "bP" | "bN" | "bB" | "bR" | "bQ" | "bK"
;

type Position = {
    [pos in Square]?: Piece
}

type CustomPieces = {
    [piece in Piece]?: (obj: {isDragging: boolean, squareWidth: number, droppedPiece: string, targetSquare: string, sourceSquare: string}) => JSX.Element
}

interface Props {
    allowDrag?: (obj: {piece: string, sourceSquare: string}) => boolean,
    boardStyle?: React.CSSProperties,
    calcWidth?: (obj: {screenWidth: number, screenHeight: number}) => number,
    darkSquareStyle?: React.CSSProperties,
    draggable?: boolean,
    dropOffBoard?: "snapback" | "trash",
    dropSquareStyle?: React.CSSProperties,
    getPosition?: (currentPosition: Position) => void,
    id?: string | number,
    lightSquareStyle?: React.CSSProperties,
    onDragOverSquare?: (square: string) => void,
    onDrop?: (obj: {sourceSquare: string, targetSquare: string, piece: string}) => void,
    onMouseOutSquare?: (square: string) => void,
    onMouseOverSquare?: (square: string) => void,
    onPieceClick?: (piece: string) => void,
    onSquareClick?: (square: string) => void,
    onSquareRightClick?: (square: string) => void,
    orientation?: "white" | "black",
    pieces?: CustomPieces,
    position?: string | Position,
    roughSquare?: (obj: {squareElement: SVGElement, squareWidth: number}) => void,
    showNotation?: boolean,
    sparePieces?: boolean,
    squareStyles?: {[square in Square]?: React.CSSProperties},
    transitionDuration?: number,
    width?: number,
}

export default class Chessboard extends React.Component<Props> {

}

Any suggestion on how to improve it is very welcome. Thanks!

using calcwidth

i am using react and it says use calcWidth for responsive board. but how exactly?

what should i replace width={400} with? width={calcWidth} does not work

Bug: board won't update if game's first move is a CPU move

Let's say you have a CPU vs. CPU match, like in the Random vs. Random demo in Demo.js. If you watch that demo carefully, you'll notice that white's first move does not register until black makes a move; they appear to move at about the same time. This is much more obvious if you increase the time between moves to 5 seconds. All moves after white's first move do update the board correctly.

For a CPU vs. CPU game, this is only a visual quirk, but CPU vs. human games (where the CPU is white) are unplayable, because it looks like white hasn't moved.

Need to add an ability to prevent dropping a piece that is being dragged.

Use case:
The user clicks and drags a Knight but moves it in a straight line and/or to an illegal square. Ideally the drag-n-drop would query a new event to determine if dropping the piece is allowed in a given location, and if not, display user visual feedback through {cursor: not-allowed;} and snap-back.

    /** 
     * Signature: function(event: { piece: string, sourceSquare: string, targetSquare: string, allowDrop: boolean }) => void
     */
    canDrop: PropTypes.func,

Note: The allowDrop property should default to true, and if set to false by the function, indicate to the user that the piece can not be dropped.

onDrop with sparePieces

When using sparePieces={true} and try to put a spare piece on the board
i get this error
Uncaught TypeError: s is not a function at Object.endDrag (chessboard.min.js:2478) at t.value (chessboard.min.js:6563) at e.t.endDrag (chessboard.min.js:314) at Object.r.<computed> [as endDrag] (chessboard.min.js:8169) at e.handleTopDragEndCapture (chessboard.min.js:5998)

when is not a spare piece works fine

How to achieve square styles in the landing page demo?

Hi Will, thanks for creating this awesome plug-n-play chessboard!
I'm working on a hobby project and the documentation was great.

But I'm wondering how to achieve the styles such as on chessboardjsx.com?

The default styles didn't look the same.
Please refer to this demo image as an example.

image

rough.js bug

Neighboring pieces are re-rendering during animationOnDrop when squares are built by rough.js.

The re-rendering does not occur when the animationOnDrop prop is not set.

Pieces move off the board when chessboardjsx is minified

Using chessboardjsx with Create React App I noticed that there is funny behaviour when the app is built for production.

Using chess.js to generate random moves, my component looks like this:

function App() {
  const game = useRef(new Chess());
  const [fen, setFen] = useState(game.current.fen());
  const [play, setPlay] = useState(false);
  const [colorToPlay, setColorToPlay] = useState(game.current.turn());

  useEffect(() => {
    if (play) {
      const possibleMoves = game.current.moves({verbose: true});
      const randomIndex = _.random(0, possibleMoves.length - 1);
      game.current.move(possibleMoves[randomIndex]);
      setFen(game.current.fen())
       setTimeout(() => {
        setColorToPlay(game.current.turn());
      }, 1000);
    }

  }, [colorToPlay, play]);

  return (
    <div className="App">
      <header className="App-header">
        <Chessboard
          id="arena"
          position={fen}
          transitionDuration={500}
          lightSquareStyle={{backgroundColor: '#edf2f7'}}
          darkSquareStyle={{backgroundColor: '#a0aec0'}}
          width={400}
        />
        <button onClick={() => setPlay(!play)}>Play/Pause</button>
      </header>
    </div>
  );
}

Everything works fine when I run my CRA app using yarn start however, when built for production all the pieces move when the position prop is updated.

I've uploaded a short screencast to DropBox, and below is a screenshot:

Screenshot 2019-06-14 at 00 20 59

I've reproduced the issue in this repo: https://github.com/ninjaPixel/chessboardjsx-issue

You can run it by executing:

yarn
yarn serve

I've also ejected the CRA app on this branch: https://github.com/ninjaPixel/chessboardjsx-issue/tree/eject
If you modify the webpack config file, line 179 to turn the minification off, then the weird behaviour stops.

I'm not sure if this is an issue with terser-webpack-plugin or chessboardjsx but it's worth mentioning since terser-webpack-plugin is currently the de-facto minifier for webpack so it's likely that others may experience this issue.

with animation, the transition duration creates a pause of exactly that time before each move

To reproduce, set animation to true, and set transitionDuration to something large e.g. 5000. This will create a 5 second pause before the move, which will then also last for 5 seconds.

This looks like a result of some weird behaviour with waitForTransition. I have tried a couple of ways of fixing this but to no avail.

  • waitForTransition cannot just be set to false as it is also used as a truth value for getting transition coordinates - (search for waitfortransition && - This shouldn't be the case, they have different meanings/usages).

We also cannot just remove the setTimeout functions under the comment // Give piece time to transition. - this fixes the first transition, but prevents transitions on anything afterwards.

I think the transition coords/behaviour should be supplied piece by piece, not to the whole board. Because it is supplied to whole board, it appears the setTimeout code is needed to stop piece transitions being removed on rerender (via waitForTransition being set to false).

Is there a simple way you can think of to get rid of the delay before each piece moves?

pieces prop

Get rid of png and svg components, do piece type check in piece component

readme

look into new boards for readme

Usage with React Native

I'd like to use this library with React Native, but when I try to, I get:

Invariant Violation: View config not found for name div. Make sure to start component names with a capital letter.

I'm assuming this is because this is made for ReactJS? Would it be possible to add support for RN, or is there a way of solving this that I'm not aware of?

How to get FEN?

getPosition () gives us only position object, how to get to position FEN. For example, can you add the second argument getPosition function (objPostion: object, fenPosition: string) => void?

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.