Code Monkey home page Code Monkey logo

cm-chessboard's Introduction

cm-chessboard

A JavaScript chessboard which is lightweight, ES6 module based, responsive, SVG rendered and without dependencies.

cm-chessboard is the main chessboard of chessmail.eu and chessmail.de. It is also used in chess-console and in cm-fen-editor. They are all nice written ES6 Modules to handle different aspects of chess games.

Features

Extensions

The core of cm-chessboard is small, fast and reduced to the essentials. You can easily extend its functionality with extensions.

Demo and repository

Example chessboards

Installation and first steps

Step 1: Install the package

Step 2: Create your cm-chessboard page

Step 2a: Include the CSS file

<link rel="stylesheet" href="./node_modules/cm-chessboard/assets/styles/cm-chessboard.css">

Step 2b: Create a container for the chessboard

<div id="board"></div>

Step 2c: Create the chessboard in your JavaScript code.

<script type="module">
  import {Chessboard, FEN} from "./path/to/Chessboard.js"

  const board = new Chessboard(document.getElementById("board"), {
    position: FEN.start,
    assetsUrl: "./path/to/assets/" // wherever you copied the assets folder to, could also be in the node_modules folder
  })
</script>

You need to configure the assetsUrl in your chessboard props (the second parameter). The assetsUrl must be the path to the assets folder of this project, where the pieces SVGs and other resources are located.

You can also copy the assets folder from cm-chessboard/assets to your project and modify the content.

See also

Step 3: (Optional) Enable user input

To enable the user to move the pieces, you have to enable the move input.

const board = new Chessboard(document.getElementById("board"), {
        position: FEN.start,
        assetsUrl: "../assets/",
        extensions: [{class: Markers}] // Looks better with markers. (Don't forget to also include the CSS for the markers)
    })

    board.enableMoveInput(inputHandler) // This enables the move input

    function inputHandler(event) {
        console.log(event)
        if(event.type === INPUT_EVENT_TYPE.moveInputStarted || 
                event.type === INPUT_EVENT_TYPE.validateMoveInput) {
            return true // false cancels move
        }
    }

See also

Take a look at the /examples folder for more examples.

Configuration

Below is the default configuration

this.props = {
    position: FEN.empty, // set position as fen, use FEN.start or FEN.empty as shortcuts
    orientation: COLOR.white, // white on bottom
    responsive: true, // resize the board automatically to the size of the context element
    assetsUrl: "./assets/", // put all css and sprites in this folder, will be ignored for absolute urls of assets files
    assetsCache: true, // cache the sprites, deactivate if you want to use multiple pieces sets in one page
    style: {
        cssClass: "default", // set the css theme of the board, try "green", "blue" or "chess-club"
        showCoordinates: true, // show ranks and files
        borderType: BORDER_TYPE.none, // "thin" thin border, "frame" wide border with coordinates in it, "none" no border
        aspectRatio: 1, // height/width of the board
        pieces: {
            type: PIECES_FILE_TYPE.svgSprite, // pieces are in an SVG sprite, no other type supported for now
            file: "pieces/standard.svg", // the filename of the sprite in `assets/pieces/` or an absolute url like `https://…` or `/…`
            tileSize: 40 // the tile size in the sprite
        },
        animationDuration: 300 // pieces animation duration in milliseconds. Disable all animations with `0`
    },
    extensions: [ /* {class: ExtensionClass, props: { ... }} */] // add extensions here
}

API

constructor

new Chessboard(context, props = {})

  • context: the HTML DOM element being the container of the widget
  • props: The board configuration (properties)

setPiece(square, piece, animated = false)

Sets a piece on a square. Example: board.setPiece("e4", PIECE.blackKnight, true) or board.setPiece("e4", "bn"). Remove a Piece with board.setPiece("e4", null). Returns a Promise, which is resolved, after the animation finished.

getPiece(square)

Returns the piece on a square or null if the square is empty.

movePiece(squareFrom, squareTo, animated = false)

Move a piece from squareFrom to squareTo. Returns a Promise, which is resolved, after the animation finished.

Example for movePiece

setPosition(fen, animated = false)

Sets the position as fen or only the position part of a fen. Returns a Promise, which is resolved, after the animation finished.

Example for setPosition

getPosition()

Returns the board position in form of the position part of a fen.

setOrientation(color)

Sets the board orientation (color at bottom). Allowed values are COLOR.white or COLOR.black.

Example for setOrientation

getOrientation()

Returns the board orientation.

destroy()

Removes the board from the DOM.

Example for destroy

enableMoveInput(eventHandler, color = undefined)

Enables moves via user input (mouse or touch). Set optional color, if you want to enable the move input for a specific side, COLOR.white or COLOR.black.

eventHandler is called on specific events of the user interaction. Receives the parameter event.

board.enableMoveInput((event) => {
    // handle user input here
}, COLOR.white)

Example for enableMoveInput

The event has the following event.type:

  • INPUT_EVENT_TYPE.moveInputStarted: User started the move input, event.squareFrom contains the coordinates. Return true or false to validate the start square. false cancels the move.
  • INPUT_EVENT_TYPE.validateMoveInput: To validate the users move input. event.squareFrom and event.squareTo contain the coordinates. Return true or false to validate the move. false cancels the move.
  • INPUT_EVENT_TYPE.moveInputCanceled: The user canceled the move with clicking again on the start square, clicking outside the board or right click.
  • INPUT_EVENT_TYPE.moveInputFinished: Fired after the move was made, also when canceled.
  • INPUT_EVENT_TYPE.movingOverSquare: Fired, when the user moves the piece over a square. event.squareTo contains the coordinates.
chessboard.enableMoveInput((event) => {
    console.log("move input", event)
  switch (event.type) {
      case INPUT_EVENT_TYPE.moveInputStarted:
          console.log(`moveInputStarted: ${event.squareFrom}`)
          return true // false cancels move
      case INPUT_EVENT_TYPE.validateMoveInput:
          console.log(`validateMoveInput: ${event.squareFrom}-${event.squareTo}`)
          return true // false cancels move
      case INPUT_EVENT_TYPE.moveInputCanceled:
          console.log(`moveInputCanceled`)
          break
      case INPUT_EVENT_TYPE.moveInputFinished:
          console.log(`moveInputFinished`)
          break
      case INPUT_EVENT_TYPE.movingOverSquare:
          console.log(`movingOverSquare: ${event.squareTo}`)
          break
  }
}, COLOR.white)

disableMoveInput()

Disables moves via user input.

Piece sets

cm-chessboard supports alternative piece sets. A piece set is defined in an SVG sprite. cm-chessboard is shipped with two sets, the default staunty ( chessboard-sprite-staunty.svg) and a sprite of the Wikimedia standard pieces (chessboard-sprite.svg).

Sprites must be 40x40px in size where the piece elements must have ids like "bp" (black pawn) or "wq" (white queen). Just open the sprite in a text editor, SVG is readable like HTML.

Extensions

cm-chessboard provides the ability to extend its functionality with extensions. Extensions extend the class Extension and have access to the chessboard and can register extension points.

registerExtensionPoint(name, callback)

class MyCoolChessboardExtension extends Extension {
    constructor(chessboard, props) {
        super(chessboard, props)
        this.registerExtensionPoint(EXTENSION_POINT.moveInput, (data) => {
            // do something on move [start | cancel | done]
            console.log(data)
        })
    }
}

Currently possible extension points are defined in Extension.js.

export const EXTENSION_POINT = {
    positionChanged: "positionChanged", // the positions of the pieces was changed
    boardChanged: "boardChanged", // the board (orientation) was changed
    boardResized: "boardResized", // the board was resized
    moveInputToggled: "moveInputToggled", // move input was enabled or disabled
    moveInput: "moveInput", // move started, moving over a square, validating or canceled
    beforeRedrawBoard: "beforeRedrawBoard", // called before redrawing the board
    afterRedrawBoard: "afterRedrawBoard", // called after redrawing the board
    animation: "animation", // called on animation start, end and on every animation frame
    destroy: "destroy" // called, before the board is destroyed
}

Enable extensions via the chessboard props.

const chessboard = new Chessboard(document.getElementById("board"), {
    position: FEN.start,
    extensions: // list of used extensions
        [{
            class: MyCoolChessboardExtension, // the class of the extension
            props: {
                // configure the extension here
            }
        }]
})

Add methods to the chessboard

Add methods to the chessboard in the constructor of your extension like shown below.

  chessboard.addMarker = this.addMarker.bind(this)

The main extensions contained in cm-chessboard

Markers extension

Creates markers on the board. Example: Markers extension

See the README of the Markers. extension.

Arrows extension

Draw arrows on the board. Example: Arrows extension

Methods

addArrow(type, fromSquare, toSquare)

Add an arrow.

removeArrows(type, from, to)

To remove all arrows, call chessboard.removeArrows() without parameters. To remove all arrows of a specific type (type "danger"), call chessboard.removeArrows(ARROW_TYPE.danger). To remove all arrows starting at " e2" you can call chessboard.removeArrows(undefined, "e2") and so on...

getArrows(type, from, to)

To get all arrows, call chessboard.getArrows() without parameters, as with removeArrows(type, from, to).

Accessibility Extension

This extension ensures that visual impaired people can better use the chessboard. It displays the braille notation of the current position in the alt tag of the board image and enables a form to move the pieces via text input. It can also display the board as HTML table and the pieces as list.

See the example Accessibility extension

Usage

const chessboard = new Chessboard(document.getElementById("board"), {
    position: FEN.start,
    sprite: {url: "../assets/images/chessboard-sprite.svg"},
    // animationDuration: 0, // optional, set to 0 to disable animations
    style: {
        cssClass: "default-contrast" // make the coordinates better visible with the "default-contrast" theme
    },
    extensions:
        [{
            class: Accessibility,
            props: {
                brailleNotationInAlt: true, // show the braille notation of the position in the alt attribute of the SVG image
                boardAsTable: true, // display the board additionally as HTML table
                movePieceForm: true, // display a form to move a piece (from, to, move)
                piecesAsList: true, // display the pieces additionally as List
                visuallyHidden: false // hide all those extra outputs visually but keep them accessible for screen readers and braille displays
            }

        }]
})

Usage with JS Frameworks

  • Works with Vue out of the box
  • Works with Svelte out of the box
  • I don't use React, but there exists a ticket from someone who is using cm-chessboard with react: #20
  • It should work also with all other JS frameworks, because cm-chessboard is written in standard ES6 and has no dependencies.

Licenses

  • License for the code: MIT
  • License for the Staunty SVG-pieces ( chessboard-sprite-staunty.svg): CC BY-NC-SA 4.0
  • License for the Wikimedia SVG-pieces ( chessboard-sprite.svg): CC BY-SA 3.0

cm-chess

You may also be interested in cm-chess, it is like chess.js, but in ES6 and can handle games and PGNs with variants, NAGs and comments.

cm-chessboard's People

Contributors

barakmich avatar biowaffeln avatar disservin avatar doomdesign avatar furriousfox avatar huydhoang avatar jjonnnyy avatar landonschropp avatar mrenroke avatar nandakumar-m avatar noerls avatar pnb avatar shaack 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  avatar

cm-chessboard's Issues

Small UX Issue

In doing a little UX testing with my app, I noticed a couple of people getting stuck when one piece is selected, and another is clicked. Currently, cm-chessboard deselect the current square, and a second click then selects the new square. This caused a slight user perception that the board wasn't always responsive to mouse input.

Screen.Recording.2021-05-11.at.3.41.54.PM.mov

This differs from the behavior of Chess.com, where the new piece is selected on click.

Screen.Recording.2021-05-11.at.3.44.51.PM.mov

I'd expect the following behavior when a piece is currently selected and the board is clicked:

  • If a new piece that can be moved is clicked, the new piece is selected.
  • Otherwise, the current piece is deselected.

Thanks!

can't yarn add package

I tried installing the package with yarn add cm-chessboard and got the following error message:

error C:\Users\Mark\Documents\Coding Projekte\chess-notation\node_modules\cm-chessboard: Command failed.
Exit code: 1
Command: node postinstall.js
Arguments:
Directory: C:\Users\Mark\Documents\Coding Projekte\chess-notation\node_modules\cm-chessboard
Output:
internal/modules/cjs/loader.js:550
    throw err;
    ^

Error: Cannot find module 'web-module-linker'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:548:15)
    at Function.Module._load (internal/modules/cjs/loader.js:475:25)
    at Module.require (internal/modules/cjs/loader.js:598:17)
    at require (internal/modules/cjs/helpers.js:11:18)
    at Object.<anonymous> (C:\Users\Mark\Documents\Coding Projekte\chess-notation\node_modules\cm-chessboard\postinstall.js:6:25)
    at Module._compile (internal/modules/cjs/loader.js:654:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)

Any idea what the problem could be?

Promise returned by setPosition resolves immediately

I'm trying to use the promise returned from setPosition to add before and after markers for my moves. However, the promise I'm using seems to resolve immediately rather than when the animation finishes.

Thanks!

Console errors on pointer move after destroying board with selected piece

Hi @shaack,

With version 2.12.4, when I have a piece selected and I call destroy(), I get errors on pointer move.

import {Chessboard} from "cm-chessboard";
const chessboard = new Chessboard(document.getElementById('myBoard'), {}, (board) => {
  // simulate selecting a piece
  board.view.moveInput.setStatus(0)
  board.view.moveInput.setStatus(1, {index: 0, piece: 'wr', point: {x:0,y:0}, type: 'mousedown'})
});
setTimeout(() => chessboard.destroy(), 1000);

Now move the mouse pointer around the page, and this errors appears many times in the console:

Uncaught TypeError: Cannot read property 'markers' of null
    at ChessboardView.drawMarkers (ChessboardView.js?8d80:307)
    at drawMarkersDebounce.setTimeout (ChessboardView.js?8d80:299)

Click anywhere and this error appears:

Uncaught TypeError: Cannot read property 'squares' of null
    at ChessboardView.drawPiecesDebounced (ChessboardView.js?8d80:241)
    at ChessboardMoveInput.onPointerUp (ChessboardMoveInput.js?a535:313)

If you drag the piece instead of just selecting it, you get the same errors, and the dragablePiece stays visible and follows the pointer.

I think the problem is that the event listeners and dragablePiece in ChessboardMoveInput aren't being removed when destroy is called.

Error occurs when chessboard is constructed and destroyed immediately afterwards

I am using cm-chessboard on my Vue app. Noticed an interesting issue when my Vue chessboard component (which internally makes use of cm-chessboard) is mounted and unmounted immediately afterwards.

Uncaught (in promise) TypeError: Cannot read property 'inputWhiteEnabled' of undefined
at eval (ChessboardView.js?8d80:434)

eval @ ChessboardView.js?8d80:434
Promise.then (async)
setCursor @ ChessboardView.js?8d80:433
eval @ ChessboardView.js?8d80:150
setTimeout (async)
eval @ ChessboardView.js?8d80:146
redraw @ ChessboardView.js?8d80:144
eval @ Chessboard.js?8ff1:93
setTimeout (async)
eval @ Chessboard.js?8ff1:92
ChessboardView @ ChessboardView.js?8d80:48
eval @ Chessboard.js?8ff1:84
Chessboard @ Chessboard.js?8ff1:83
mounted @ ProblemViewer.vue?ca1b:63

From what I could see, for responsive chessboards, the ChessboardView constructor makes a call to handleResize function which in turn ends up calling setCursor.

if (chessboard.props.responsive) {
            setTimeout(() => {
                this.handleResize()
            })
        }

Because of the setTimeout, this ends up getting called after the chessboard has been destroyed.. I tried removing the setTimeout and called the handleResize function synchronously from the ChessboardView constructor.. This seems to solve the issue for me.

I am wondering if the setTimeout is there for any specific reason.

The constructor in ChessBoard.js also has a similar setTimeout block.

Regards,
Nanda

Usage with React Native / Gatsby.js (React)

Hi, is there any instructions/guidance to use cm-chessboard with React Native?
I read the issue usage with React but still not sure because RN doesn't utilize html dom.
Great chessboard module anyway!

animated pieces

Hey @shaack,

This isn't really an issue, but more of a question.

I'd like to have chess pieces that use svg clip-path and svg animation. Like in this exmaple: http://files.vonnau.com/fiddle/svg-sprite-animated/animated_sprite.svg

I haven't been able to get this working with the current sprite sheet setup. How would you recommend going about this? Do you think extending svjs-svg to support clip-path is practical or more trouble than it's worth? This is a niche use case, so I don't think it's worth your time, but I thought you might have a better sense of where to start than me.

Thanks,
Chad

svg code
<svg id="animated_sprite" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="546.5701" height="54.5808" viewBox="0 0 546.5701 54.5808">
  <defs>
    <clipPath id="clip-path" transform="translate(0 -5.8631)">
      <circle id="circle_mask" cx="33.6533" cy="33.6533" r="23.6533" fill="none"/>
    </clipPath>
  </defs>
  <title>animated_sprite</title>
  <g id="piece">
    <g clip-path="url(#clip-path)">
      <g id="waves">
        <path d="M546.57,27.8631c-34.1589,0-34.1589-14-68.3179-14s-34.16,14-68.3207,14-34.16-14-68.32-14-34.1587,14-68.3173,14c-34.16,0-34.16-14-68.32-14s-34.1612,14-68.3225,14c-34.1628,0-34.1628-14-68.3257-14s-34.1628,14-68.3256,14" transform="translate(0 -5.8631)" fill="none" stroke="#fcf" stroke-miterlimit="10" stroke-width="16"/>
        <path d="M546.57,52.4439c-34.1589,0-34.1589-14-68.3179-14s-34.16,14-68.3207,14-34.16-14-68.32-14-34.1587,14-68.3173,14c-34.16,0-34.16-14-68.32-14s-34.1612,14-68.3225,14c-34.1628,0-34.1628-14-68.3257-14s-34.1628,14-68.3256,14" transform="translate(0 -5.8631)" fill="none" stroke="#fcf" stroke-miterlimit="10" stroke-width="16"/>
      </g>
    </g>
    <circle id="ring" cx="33.6533" cy="27.7902" r="23.6533" fill="none" stroke="#99f" stroke-miterlimit="10"/>
  </g>
  <animateTransform xlink:href="#waves" attributeName="transform" type="translate" from="-137 0" to="0 0" begin="0s" dur="2s" repeatCount="indefinite" />
</svg>

Remove props.moveInputMode

It should be sufficient to define enableMoveInput(eventHandler, color = null). MOVE_INPUT_MOVE.moveMarker is no longer needed.

Custom text over chessboard square

I've managed to work out how to do a highlight of squares. But what about putting custom text over a square? I know that css is used for the highlight, but can I use css for text? I am guessing not, but just trying to work out how to do my text over a square thing.

Any ideas?

Support for piece images

Can someone help me understand what's going on with the .svg file and how they are being pulled as separate images from the one file? Is it going to be possible to use separate image files for each piece? My endgame is to have 2 different themes at the same time where for example the black piece theme is pulled from chessboard-sprite-staunty.svg and the white piece theme is pulled from chessboard-sprite.svg. Thanks in advance for any help and sorry if this is not an appropriate post for issues.

Chess board is not responsive when parent element dimension changes

Hi,

I have a three column layout for my page and use cm-chessboard in one of the columns. On resizing the columns, the board does not get resized.

When the entire window is resized the board's size is adjusted as expected.

Would be good if the responsiveness is based on the dimensions of the parent element specified when creating the board instead of window size.

I guess this can be accomplished using the Resize_Observer_API. This seems to be supported by all major browsers now in 2021.

Many thanks for making cm-chessboard. It is wonderful.

Regards,
Nanda

Export as SVG image

Hi,

Since the board, markings, pieces are all in svg, is it possible to export the board (along with pieces, markings etc) as an svg image?

Regards,
Nanda

Navigating through histroy

I have created a button to go to the first/previous/next/last move, but having looked at the underlying code, I cannot work out how to navigate through the history. I also had a look at chess-console but couldn't work it out!

Do you have any simple pointers to how I can attach some code to my button that will let me move back and forth?

How to add AI like this example?

Since there are no other document examples, I don't know if there is such a method

example


var cfg = {
    draggable: true,
    position: 'start',
    onDragStart: onDragStart,
    onDrop: onDrop,
    onMouseoutSquare: onMouseoutSquare,
    onMouseoverSquare: onMouseoverSquare,
    onSnapEnd: onSnapEnd
};
board = ChessBoard('board', cfg);

Default Markers Don't Work

Hey, just a heads up, it looks like the default markers in MARKER_TYPE don't work with the Wikimedia standard pieces sprite included in the library. Looking at the SVG, it seems to be missing the IDs specified in MARKER_TYPE.

No animation after destroying a board

With 2.12.5, after destroying a board, animation doesn't work on new boards. This breaks the 2-click move style.

This is a regression caused by changes in #9. It looks like stopAnimation never gets reset.

Can I animate a single piece using board positions?

I want to use the Knight piece to show how it can travel over the board using a set of input co ordininates. Can I start the board with a single piece and then leverage the animate functionality to show how the Knight moves on the board.
I tried using the board.setPosition method but it a bit complex and was wondering if there is a simple way to achieve my use case.

Thank you!

Sprite images with linear gradients

I'm trying to use cm-chessboard with SVG images that use a linearGradient. This works fine using Firefox, but on all other browsers that I tried the gradients are not displayed. To illustrate the problem I have attached a modified version of chessboard-sprite-staunty.svg in which the white pawn has been replaced by a draughts piece with a gradient. And here is a link to how I'm using it in practice: https://10x10.org/analysis/2021/nk5-8a.html.

This probably isn't a bug in cm-chessboard, but I thought it might be worth mentioning it. I've googled for sprites and linear gradients, and found some hits that suggest browsers sometimes have trouble finding the definitions of linear gradients. If someone knows a solution for this problem that would be highly appreciated! Otherwise I will try to work around it by replacing the gradients with something else.

sprite.zip

No square when dragging piece out of board

When dragging a piece out of the board, I'm not seeing a square property populated on the event.

{ 
  chessboard: {}, 
  type: "moveCanceled", 
  reason: "movedOutOfBoard", 
  square: undefined 
}

Suggestion: Add highlight system

I suggest having highlight system for highlighting previous moves. If I use marker class for highlighting previous moves, it would be ugly because markerclass is for marking squares by the move input.

Additional Animation

Hello again!

I'd love to see a new animation added to the Chessboard. If a move is canceled, it'd be great for the piece to animate back to its previous position instead of snapping back to it. I'm using this in a "wrong move" effect, and I think it'd be a bit less jarring if the piece would animate.

Screen.Recording.2021-05-04.at.6.00.56.PM.mov

This suggestion could maybe be generalized to all pieces animating into a position rather than snapping when moved by the user, such as when you move a piece to the corner of a square.

Screen.Recording.2021-05-04.at.6.05.02.PM.mov

Edit

Previously, this question contained an additional request for a casting animation, but that animation already existed and wasn't working due to a bug in my code:

When the player castles, it would be nice if the rook animated to its new spot instead of appearing there. Here's an example of what it currently does:

Screen.Recording.2021-05-04.at.5.58.58.PM.mov

Console errors on window resize after destroying responsive board

Hi @shaack,

I'm really enjoying cm-chessboard. I'm using it in an SPA, where I'm creating and destroying boards frequently.

With version 2.11.26, when I use responsive:true and I call destroy(), I get errors on window resize.

import {Chessboard} from "cm-chessboard";
const chessboard = new Chessboard(document.getElementById('myBoard'), {responsive: true});
setTimeout(() => chessboard.destroy(), 1000);

Now resize the window, and these errors appear in the console:

Uncaught TypeError: Cannot read property 'squares' of null
    at ChessboardView.drawPieces (ChessboardView.js?8d80:226)
Uncaught TypeError: Cannot read property 'orientation' of null
    at drawBoardDebounce.setTimeout (ChessboardView.js?8d80:149)
Uncaught TypeError: Cannot read property 'markers' of null
    at drawMarkersDebounce.setTimeout (ChessboardView.js?8d80:287)

I think the problem is that the resize listener isn't being removed when destroy is called.

Pawn promotion support?

Is there some support-GUI for pawn promotion available (a select-option for promotion to knight, bishop, rook or queen?)

How to add arrows?

I am creating an app so people can use it as a coaching aid, or just for analysing their games with others. The ability to add arrows to the board is an important one for me. I know other competing boards have this feature, and I think it would be a significant additional improvement for cm-chessboard.

Is it likely to come to cm-chessboard anytime soon? Are there any pointers for how to create such an improvement?

TypeError: 'application/octet-stream' is not a valid JavaScript MIME type.

If you get an invalid MIME type error from your server, the server does not recognise ".mjs" as an extension for module scripts. In that case, you have to add this to your .htaccess

<IfModule mod_mime.c>
  AddType text/javascript mjs
</IfModule>
  • Safari: TypeError: 'application/octet-stream' is not a valid JavaScript MIME type.
  • Chrome: Failed to load module script: The server responded with a non-JavaScript MIME type of "application/octet-stream"
  • Firefox: Loading module from “https://shaack.com/projekte/cm-chessboard/src/cm-chessboard/Chessboard.mjs” was blocked because of a disallowed MIME type (“application/octet-stream”).

Editing default dashed move highlighter

The dashed box around the piece appears on the square where I click the piece and the square I move it to.

How can I:

a) Change the dashed style for the first square clicked?

b) Change the dashed style for the marker that points to the destination square (if that makes sense!)?

Allow no border

I'm trying to disable the border, but the style.showBorder setting doesn't seem to work. For example, here's what I get with my current config:

{
  "responsive": true,
  "moveInputMode": 1,
  "sprite": {
    "url": "/static/chessboard-sprite-7ae4df542523aef7007536d2a99557d0.svg"
  },
  "style": {
    "showCoordinates": false,
    "showBorder": false
  },
  "position": "8/8/8/8/8/8/8/8 w KQkq - 0 1"
}

Screen Shot 2021-03-15 at 6 37 01 PM

I would just hide the border with CSS, but the squares are still offset from 0,0, so my board would't align to other elements in my UI.

Displaying board in dialog box

I have a problem displaying the board in a modal dialog box, where I am using it for a context sensitive help popup.

My code below is supposed to show the board in the dialog box, but instead I get an error:

Error: container element is null

Any idea where I am going wrong?

import React from 'react';
import { Typography } from '@material-ui/core';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogContent from '@material-ui/core/DialogContent';
import Paper from '@material-ui/core/Paper';
import {
  Chessboard,
  INPUT_EVENT_TYPE,
  MOVE_INPUT_MODE,
  COLOR,
} from 'cm-chessboard';

// import './styles/cm-chessboard.css';

export const MyFunction = props => {

  new Chessboard(document.getElementById('board3'), {
    position:
      'rn2k1r1/ppp1pp1p/3p2p1/5bn1/P7/2N2B2/1PPPPP2/2BNK1RR w Gkq - 4 11',
    orientation: COLOR.black,
  });

  return (
    <>
      <DialogContent dividers>
        <Paper id="board3"></Paper>
      </DialogContent>
    </>
  );
};

on jQuery tabs doesn't work

Gen a chessboard inside a tab which is not visible at start, seems to not work (see code)
When I deactivate the jQuery Tab script, or move the board div to top, it works.

For me it seems that the ChessBoardView gets height & width of 0 in error case's.
Can y take a look? Actually I need it for "framework7" (also not working on tabs)
but I made this small example - its basically the jQuery Tab example, with your chessboard in Tab2.

`

<title>cm-chessboard</title>
<link rel="stylesheet" href="jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="jquery-1.12.4.js"></script>
<script src="jquery-ui.js"></script>
<script>
   $( function() {
      $( "#tabs" ).tabs();
   } );
</script>

<meta name="viewport" content="width=device-width, user-scalable=yes, initial scale=1.0"/>

cm-chessboard

Proin elit arcu, rutrum commodo Curabitur nec arcu.

Morbi tincidunt, dui sit amet facilisis feugiat

Insert here

Mauris eleifend est et turpis. Duis id erat.

<script type="module"> import {Chessboard} from "./src/cm-chessboard/Chessboard.js" const board = new Chessboard(document.getElementById("board"), { position: "start" }); </script> `

Problems with XHR and Apache Cordova

Hi,
im referring to #23

for me at IOS it doesn't work. When I turn the cache on, I get this error:

2021-03-07 08:16:15.607257+0100 MyApp[9980:418063] Task .<1> finished with error [-1002] Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSLocalizedDescription=unsupported URL, NSErrorFailingURLStringKey=app://localhost/static/chessboard-sprite.svg, NSErrorFailingURLKey=app://localhost/static/chessboard-sprite.svg, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask .<1>"
), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask .<1>, NSUnderlyingError=0x600001d782a0 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}}

with cache = false, or the old version 3.4.5 it works.
But without cache, it seems to be no big difference to 3.4.5 looking at code.
Btw, you removed a lot of ";" why?

When I say "doesn't work" , it means, there are no pieces displayed (just the empty board) plus an error message.
I guess, cause its not an url instead a filepath and this XHR seems to have a problem with that.
Strangely on android it works even with cache.

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.