### Full Example with Imports and Logging Source: https://github.com/shaack/cm-chessboard/blob/master/examples/enable-input.html A complete example demonstrating the initialization of the chessboard with extensions, enabling move input, and setting up a logging function. This snippet includes all necessary imports and helper functions for a runnable example. ```javascript import {INPUT_EVENT_TYPE, Chessboard} from "../src/Chessboard.js" import {FEN} from "../src/model/Position.js" import {Markers} from "../src/extensions/markers/Markers.js" window.board = new Chessboard(document.getElementById("board"), { position: FEN.start, assetsUrl: "../assets/", style: {pieces: {file: "pieces/staunty.svg"}}, extensions: [{class: Markers}] }) window.board.enableMoveInput(inputHandler) function inputHandler(event) { console.log(event) switch (event.type) { case INPUT_EVENT_TYPE.moveInputStarted: log(`moveInputStarted: ${event.squareFrom}`) return true // false cancels move case INPUT_EVENT_TYPE.validateMoveInput: log(`validateMoveInput: ${event.squareFrom}-${event.squareTo}`) return true // false cancels move case INPUT_EVENT_TYPE.moveInputCanceled: log(`moveInputCanceled`) break case INPUT_EVENT_TYPE.moveInputFinished: log(`moveInputFinished`) break case INPUT_EVENT_TYPE.movingOverSquare: log(`movingOverSquare: ${event.squareTo}`) break } } const output = document.getElementById("output") function log(text) { const log = document.createElement("div") log.innerText = text output.appendChild(log) } ``` -------------------------------- ### Initialize Chessboard with Animation Source: https://github.com/shaack/cm-chessboard/blob/master/examples/pieces-animation.html Initializes the chessboard with a starting position and configures animation duration. This setup is required before using animation features. ```javascript import {Chessboard, PIECE} from "../src/Chessboard.js" import {FEN} from "../src/model/Position.js" const board = new Chessboard(document.getElementById("board"), { position: FEN.start, assetsUrl: "../assets/", style: { pieces: {file: "pieces/staunty.svg"}, animationDuration: 500 } }) ``` -------------------------------- ### Create a simple chessboard Source: https://github.com/shaack/cm-chessboard/blob/master/examples/simple-boards.html Initializes a basic chessboard with the starting position. Ensure the target element exists in the HTML. ```javascript new Chessboard(document.getElementById("board1"), { assetsUrl: "../assets/", position: FEN.start }) ``` -------------------------------- ### Create and configure chessboards with imports Source: https://github.com/shaack/cm-chessboard/blob/master/examples/simple-boards.html Demonstrates creating two chessboards with different configurations, including a starting position and a custom FEN, along with custom styles and caching disabled for the second board. Requires importing necessary constants and classes. ```javascript import {COLOR, Chessboard, BORDER_TYPE} from "../src/Chessboard.js" import {FEN} from "../src/model/Position.js" new Chessboard(document.getElementById("board1"), { assetsUrl: "../assets/", position: FEN.start }) new Chessboard(document.getElementById("board2"), { assetsUrl: "../assets/", assetsCache: false, position: "rn2k1r1/ppp1pp1p/3p2p1/5bn1/P7/2N2B2/1PPPPP2/2BNK1RR w Gkq - 4 11", style: {pieces: {file: "pieces/staunty.svg"},cssClass: "green", borderType: BORDER_TYPE.frame}, orientation: COLOR.black }) ``` -------------------------------- ### Initialize Chessboard with HtmlLayer Extension Source: https://github.com/shaack/cm-chessboard/blob/master/examples/extensions/html-layer-extension.html Initializes the chessboard with the HtmlLayer extension enabled. This setup is required before you can add or remove HTML layers. ```javascript import {Chessboard, FEN} from "../../src/Chessboard.js" import {HtmlLayer} from "../../src/extensions/html-layer/HtmlLayer.js" import {Markers} from "../../src/extensions/markers/Markers.js" const board = new Chessboard(document.getElementById("board"), { position: FEN.start, assetsUrl: "../../assets/", extensions: [{class: HtmlLayer}, {class: Markers}] }) board.enableMoveInput(() => true) ``` -------------------------------- ### Initialize Chessboards with Arrows Extension Source: https://github.com/shaack/cm-chessboard/blob/master/examples/sandbox/arrows-extension-multiple.html Initializes two chessboard instances, each configured with the Arrows extension. This setup allows for independent arrow drawing on separate boards. ```javascript import {Chessboard} from '../../src/Chessboard.js' import {Arrows, ARROW_TYPE} from "../../src/extensions/arrows/Arrows.js" window.Chessboard = Chessboard; window.Arrows = Arrows; window.ARROW_TYPE = ARROW_TYPE; let brd1; let brd2; function init() { brd1 = new Chessboard(document.getElementById('board1'), { assetsUrl: "../../assets/", extensions: [ {class: Arrows}, ] }); brd1.addArrow(ARROW_TYPE.pointy, 'a1', 'b3') brd1.setPiece('a1', 'wn') brd2 = new Chessboard(document.getElementById('board2'), { assetsUrl: "../../assets/", extensions: [ {class: Arrows}, ] }); brd2.setOrientation('b'); brd2.addArrow(ARROW_TYPE.pointy, 'a1', 'b3') brd2.setPiece('a1', 'wn') } ``` -------------------------------- ### Create 100 Boards on One Page Source: https://github.com/shaack/cm-chessboard/blob/master/examples/many-boards.html This example shows how to dynamically create and initialize 100 chessboard instances on a single HTML page. It utilizes a loop to generate divs for each board and then instantiates `Chessboard` for each, setting initial positions and custom piece assets. A helper function `makeRandomMove` is included to simulate game progression. ```javascript import {Chessboard} from "../src/Chessboard.js" import {Chess} from "https://cdn.jsdelivr.net/npm/chess.mjs@1/src/chess.mjs/Chess.js" const boardsDiv = document.getElementById("boards") const game = new Chess() for (let i = 0; i < 100; i++) { const boardDiv = document.createElement("div") boardDiv.setAttribute("class", "board") boardsDiv.appendChild(boardDiv) new Chessboard(boardDiv, { responsive: false, position: game.fen(), assetsUrl: "../assets/", style: {pieces: {file: "pieces/staunty.svg"}}, }) } function makeRandomMove() { const possibleMoves = game.moves(); if (possibleMoves.length === 0) return; const randomIndex = Math.floor(Math.random() * possibleMoves.length); game.move(possibleMoves[randomIndex]); } ``` -------------------------------- ### Handle All Move Input Events Source: https://github.com/shaack/cm-chessboard/blob/master/README.md Provides a detailed example of handling all possible move input events, including validation and cancellation. Use this to manage the entire move input lifecycle. ```javascript 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) ``` -------------------------------- ### Add, Get, and Remove Markers Source: https://github.com/shaack/cm-chessboard/blob/master/src/extensions/markers/README.md Demonstrates the basic usage of addMarker, getMarkers, and removeMarkers functions. Ensure you use the same marker type reference for adding and removing. ```javascript const myType = {class: "marker-frame", slice: "markerFrame"} board.addMarker(myType, "e4") board.removeMarkers(myType) // removed // ❌ silently does nothing — different reference, even though the // object looks identical board.addMarker({class: "marker-frame", slice: "markerFrame"}, "e4") board.removeMarkers({class: "marker-frame", slice: "markerFrame"}) ``` -------------------------------- ### Initialize Chessboard with Random Moves Source: https://github.com/shaack/cm-chessboard/blob/master/index.html Initializes a chessboard with the starting position and then continuously makes random moves using chess.mjs, updating the board's display with animation. Clears the interval if the game ends. ```javascript import {Chessboard} from "./src/Chessboard.js" import {FEN} from "./src/model/Position.js" import {Chess} from "https://cdn.jsdelivr.net/npm/chess.mjs@1/src/chess.mjs/Chess.js" const chess = new Chess() const board = new Chessboard(document.getElementById("board"), { position: FEN.start }) const interval = setInterval(() => { makeRandomMove() board.setPosition(chess.fen(), true) }, 500) function makeRandomMove() { if(chess.game_over()) { chess.reset() } const possibleMoves = chess.moves() if (possibleMoves.length === 0) { clearInterval(interval) return } const randomIndex = Math.floor(Math.random() * possibleMoves.length) chess.move(possibleMoves[randomIndex]) } ``` -------------------------------- ### Responsive Chessboard with Aspect Ratio Source: https://github.com/shaack/cm-chessboard/blob/master/examples/responsive-board.html Configure a responsive chessboard with a specific aspect ratio and custom pieces. This example also utilizes the AutoBorderNone extension to disable the frame border on smaller boards. ```javascript new Chessboard(document.getElementById("board"), { position: FEN.start, assetsUrl: "../assets/", style: { aspectRatio: 0.9, pieces: {file: "pieces/staunty.svg"}, borderType: BORDER_TYPE.frame }, extensions: [{"class": AutoBorderNone} ]) ``` -------------------------------- ### Initialize Chessboard with Accessibility Extension Source: https://github.com/shaack/cm-chessboard/blob/master/examples/extensions/accessibility-extension.html Initializes the chessboard with the Accessibility extension enabled. Configure features like Braille notation, HTML table display, move forms, piece lists, and keyboard navigation. Set 'visuallyHidden' to false to display these features. This setup is useful for enhancing board accessibility. ```javascript import {Chessboard} from "../../src/Chessboard.js" import {Accessibility} from "../../src/extensions/accessibility/Accessibility.js" import {Markers} from "../../src/extensions/markers/Markers.js" const chessboard = new Chessboard(document.getElementById("board"), { position: "rn2k1r1/ppp1pp1p/3p2p1/5bn1/P7/2N2B2/1PPPPP2/2BNK1RR w Gkq - 4 11", assetsUrl: "../../assets/", // 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 game in the alt attribute of the SVG board 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 keyboardMoveInput: true, // enable keyboard navigation on the board with arrow keys visuallyHidden: false // hide all those extra outputs visually but keep them accessible for screen readers and braille displays } }, {class: Markers} ] }) window.switchOrientation = function () { chessboard.setOrientation(chessboard.getOrientation() === 'w' ? 'b' : 'w') } chessboard.enableMoveInput(() => true) ``` -------------------------------- ### Custom Marker Usage Source: https://github.com/shaack/cm-chessboard/blob/master/src/extensions/markers/README.md Shows how to define and use a custom marker type with specific CSS classes and SVG slices. Includes examples for adding and removing markers. ```javascript const myMarkerType = {class: "marker-circle-red", slice: "markerCircle"} // add chessboard.addMarker(myMarkerType, "e4") // remove a specific marker chessboard.removeMarkers(myMarkerType, "e4") // remove all "myMarkerType" chessboard.removeMarkers(myMarkerType) // remove all markers chessboard.removeMarkers() ``` -------------------------------- ### Get All Arrows on Chessboard Source: https://github.com/shaack/cm-chessboard/blob/master/examples/extensions/arrows-extension.html Retrieves all arrows currently displayed on the chessboard. The output is an array of arrow objects. ```javascript console.log(chessboard.getArrows()) ``` -------------------------------- ### Knight's Dance Animation Source: https://github.com/shaack/cm-chessboard/blob/master/examples/pieces-animation.html Executes a sequence of moves simulating a knight's dance. This example demonstrates chained piece movements with animation. ```javascript window.knightMove = async () => { board.setPiece("e5", PIECE.wn) board.movePiece("e5", "c4", true) board.movePiece("c4", "d6", true) board.movePiece("d6", "f5", true) board.movePiece("f5", "h4", true) board.movePiece("h4", "g6", true) board.movePiece("g6", "e5", true) } ``` -------------------------------- ### Set Board Position Source: https://github.com/shaack/cm-chessboard/blob/master/examples/pieces-animation.html Sets the chessboard to a specified position, which can be a FEN string, 'start', or 'empty'. Animation is controlled by the 'animated' parameter. ```javascript let i = 0 window.setPosition = (position, animated) => { if(position === "start") { position = FEN.start } if(position === "empty") { position = FEN.empty } i++ return board.setPosition(position, animated) } ``` -------------------------------- ### Move Piece on Board Source: https://github.com/shaack/cm-chessboard/blob/master/examples/pieces-animation.html Moves a piece from a starting square to a target square. This function reads the 'from' and 'to' squares from input fields and optionally animates the move. ```javascript window.movePiece = () => { const squareFrom = document.getElementById("moveFrom").value const squareTo = document.getElementById("moveTo").value console.log("movePiece", squareFrom, squareTo) board.movePiece(squareFrom, squareTo, true) } ``` -------------------------------- ### getArrows Source: https://github.com/shaack/cm-chessboard/blob/master/examples/extensions/arrows-extension.html Retrieves all arrows currently on the chessboard, optionally filtered by type, start, or end square. ```APIDOC ## getArrows(type, from, to) ### Description Retrieves all arrows from the chessboard. ### Parameters - **type** (string) - Optional - The type of arrows to retrieve. - **from** (string) - Optional - The starting square of arrows to retrieve. - **to** (string) - Optional - The ending square of arrows to retrieve. ### Usage Examples - `chessboard.getArrows()`: Retrieves all arrows. - `chessboard.getArrows(ARROW_TYPE.danger)`: Retrieves all arrows of type 'danger'. ``` -------------------------------- ### Initialize Chessboard with Promotion Dialog Source: https://github.com/shaack/cm-chessboard/blob/master/examples/extensions/promotion-dialog-extension.html Initializes the chessboard with the PromotionDialog extension and enables move input. The promotion dialog is shown when a pawn reaches the last rank. ```javascript import {Chessboard, COLOR, INPUT_EVENT_TYPE} from "../../src/Chessboard.js?v=1" import {PromotionDialog} from "../../src/extensions/promotion-dialog/PromotionDialog.js?v=1" import {Markers} from "../../src/extensions/markers/Markers.js?v=1" import {Accessibility} from "../../src/extensions/accessibility/Accessibility.js?v=1" const position = "4k3/1P6/8/8/6r1/8/61p/2R1K3 w - - 0 1" const chessboard = new Chessboard(document.getElementById("chessboard"), { position: position, assetsUrl: "../../assets/", extensions: [ {class: PromotionDialog}, {class: Markers}, {class: Accessibility, props: { brailleNotationInAlt: true, // show the braille notation of the game in the alt attribute of the SVG 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 }} ] }) chessboard.enableMoveInput((event) => { if (event.type === INPUT_EVENT_TYPE.validateMoveInput) { if ((event.squareTo.charAt(1) === "8" || event.squareTo.charAt(1) === "1") && event.piece.charAt(1) === "p") { const pieceColor = event.piece.charAt(0) chessboard.showPromotionDialog(event.squareTo, pieceColor, (result) => { console.log("Promotion result", result) if (result && result.piece) { chessboard.setPiece(result.square, result.piece, true) } else { chessboard.setPosition(position) } }) } } return true }) window.switchOrientation = function () { chessboard.setOrientation(chessboard.getOrientation() === 'w' ? 'b' : 'w') } ``` -------------------------------- ### Enabling Custom Extensions in Chessboard Initialization Source: https://github.com/shaack/cm-chessboard/blob/master/README.md Shows how to initialize the Chessboard component and enable custom extensions by providing their class and optional properties in the configuration. ```javascript 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 } }] }) ``` -------------------------------- ### addArrow Source: https://github.com/shaack/cm-chessboard/blob/master/examples/extensions/arrows-extension.html Adds an arrow to the chessboard. You can specify the arrow type, starting square, and ending square. ```APIDOC ## addArrow(type, from, to) ### Description Adds an arrow to the chessboard. ### Parameters - **type** (string) - Optional - The type of the arrow (e.g., ARROW_TYPE.default, ARROW_TYPE.danger). - **from** (string) - Required - The starting square of the arrow (e.g., "e2"). - **to** (string) - Required - The ending square of the arrow (e.g., "e4"). ``` -------------------------------- ### constructor Source: https://github.com/shaack/cm-chessboard/blob/master/README.md Initializes a new Chessboard instance. Requires a DOM element context and an optional properties object for configuration. ```APIDOC ## constructor ### Description Initializes a new Chessboard instance. ### Method `new Chessboard(context, props = {})` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **`context`** (HTMLElement) - The HTML DOM element that will serve as the container for the chessboard widget. - **`props`** (Object) - An optional object containing properties to configure the board. ### Request Example ```javascript const board = new Chessboard(document.getElementById("board"), { position: FEN.start, assetsUrl: "../assets/" }) ``` ### Response None #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Initialize cm-chessboard in JavaScript Source: https://github.com/shaack/cm-chessboard/blob/master/README.md Import the Chessboard and FEN classes and initialize a new chessboard instance. Configure the initial position and the path to the assets folder. ```javascript 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 }) ``` -------------------------------- ### Initialize Chessboard with Custom Styles and Pieces Source: https://github.com/shaack/cm-chessboard/blob/master/examples/different-styles.html Initializes a chessboard with a custom CSS class, frame border, and a specific piece set. Ensure the assets URL is correctly configured. ```javascript import {Chessboard, BORDER_TYPE} from "../src/Chessboard.js" import {FEN} from "../src/model/Position.js" new Chessboard(document.getElementById("board1"), { position: FEN.start, assetsUrl: "../assets/", assetsCache: false, style: { cssClass: "green", borderType: BORDER_TYPE.frame, pieces: { file: "pieces/staunty.svg" } } }) ``` ```javascript new Chessboard(document.getElementById("board2"), { position: FEN.start, assetsUrl: "../assets/", assetsCache: false, style: { cssClass: "chessboard-js", borderType: BORDER_TYPE.thin } }) ``` ```javascript new Chessboard(document.getElementById("board3"), { position: FEN.start, assetsUrl: "../assets/", assetsCache: false, style: { cssClass: "chess-club", borderType: BORDER_TYPE.frame, pieces: {file: "pieces/staunty.svg"} } }) ``` ```javascript new Chessboard(document.getElementById("board4"), { position: FEN.start, assetsUrl: "../assets/", assetsCache: false, style: { cssClass: "blue", borderType: BORDER_TYPE.thin, showCoordinates: false, } }) ``` ```javascript new Chessboard(document.getElementById("board5"), { position: FEN.start, assetsUrl: "../assets/", assetsCache: false, style: { borderType: BORDER_TYPE.none, pieces: {file: "pieces/staunty.svg"} }, }) ``` ```javascript new Chessboard(document.getElementById("board6"), { position: FEN.start, assetsUrl: "../assets/", assetsCache: false, style: { pieces: {file: "pieces/staunty.svg"}, cssClass: "blue", borderType: BORDER_TYPE.frame }, }) ``` ```javascript new Chessboard(document.getElementById("board7"), { position: FEN.start, assetsUrl: "../assets/", assetsCache: false, style: { cssClass: "green" } }) ``` ```javascript new Chessboard(document.getElementById("board8"), { position: FEN.start, assetsUrl: "../assets/", assetsCache: false, style: { cssClass: "black-and-white" } }) ``` ```javascript new Chessboard(document.getElementById("board9"), { position: FEN.start, assetsUrl: "../assets/", assetsCache: false, style: { cssClass: "chessboard-js", borderType: BORDER_TYPE.frame } }) ``` -------------------------------- ### Initialize Chessboard with Arrows Extension Source: https://github.com/shaack/cm-chessboard/blob/master/examples/extensions/arrows-extension.html Initializes the chessboard and enables the Arrows extension. Ensure the Arrows class is imported. ```javascript const chessboard = new Chessboard(document.getElementById("board"), { position: "rn2k1r1/ppp1pp1p/3p2p1/5bn1/P7/2N2B2/1PPPPP2/2BNK1RR w Gkq - 4 11", assetsUrl: "../../assets/", extensions: [{"class": Arrows}] }) ``` -------------------------------- ### Adding Methods to the Chessboard Instance Source: https://github.com/shaack/cm-chessboard/blob/master/README.md Illustrates how to add custom methods to the chessboard instance from within an extension's constructor using `bind` to maintain the correct context. ```javascript chessboard.addMarker = this.addMarker.bind(this) ``` -------------------------------- ### Initialize Chessboard with Persistence Extension Source: https://github.com/shaack/cm-chessboard/blob/master/examples/extensions/persistence-extension.html Use the Persistence extension to store the initial board position in localStorage. This extension is in alpha and not recommended for production. ```javascript import {Chessboard, FEN} from "../../src/Chessboard.js" import {Persistence} from "../../src/extensions/persistence/Persistence.js" const board = new Chessboard(document.getElementById("board"), { assetsUrl: "../../assets/", // todo initialPosition: FEN.start, extensions: [ { class: Persistence, props: { initialPosition: FEN.start } } ] }) board.enableMoveInput(() => true) ``` -------------------------------- ### Create a chessboard with custom options Source: https://github.com/shaack/cm-chessboard/blob/master/examples/simple-boards.html Configures a chessboard with a specific FEN position, custom piece styles, a CSS class, a frame border, and black orientation. Requires importing COLOR, Chessboard, and BORDER_TYPE. ```javascript new Chessboard(document.getElementById("board2"), { assetsUrl: "../assets/", position: "rn2k1r1/ppp1pp1p/3p2p1/5bn1/P7/2N2B2/1PPPPP2/2BNK1RR w Gkq - 4 11", style: {pieces: {file: "pieces/staunty.svg"},cssClass: "green", borderType: BORDER_TYPE.frame}, orientation: COLOR.black }) ``` -------------------------------- ### Initialize Chessboard with Auto-Markers Source: https://github.com/shaack/cm-chessboard/blob/master/examples/extensions/markers-extension.html Initializes a chessboard with the Markers extension and configures autoMarkers to highlight squares during piece movement. It also defines a custom marker and adds event listeners for manual placement of custom markers. ```javascript const board2 = new Chessboard(document.getElementById("board2"), { position: "rn2k1r1/ppp1pp1p/3p2p1/5bn1/P7/2N2B2/1PPPPP2/2BNK1RR", assetsUrl: "../../assets/", style: {pieces: {file: "pieces/staunty.svg"}}, extensions: [{class: Markers, props: {autoMarkers: MARKER_TYPE.frame}}] }) board2.enableMoveInput(() => { return true }) // define your own marker const myOwnMarker = {class: "marker-circle-danger-filled", slice: "markerCircleFilled"} board2.context.addEventListener("contextmenu", (event) => { event.preventDefault() }) board2.context.addEventListener("mousedown", (event) => { if (event.button === 2) { const square = event.target.getAttribute("data-square") const markersOnSquare = board2.getMarkers(myOwnMarker, square) if (markersOnSquare.length > 0) { board2.removeMarkers(myOwnMarker, square) } else { board2.addMarker(myOwnMarker, square) } } }) ``` -------------------------------- ### Initialize Chessboard with Markers Extension Source: https://github.com/shaack/cm-chessboard/blob/master/examples/extensions/markers-extension.html Initializes a chessboard with the Markers extension enabled. This allows for adding custom markers to squares. Left-click adds a dot, right-click adds a primary circle. ```javascript import {Chessboard} from "../../src/Chessboard.js" import {FEN} from "../../src/model/Position.js" import {MARKER_TYPE, Markers} from "../../src/extensions/markers/Markers.js" const board1 = new Chessboard(document.getElementById("board1"), { position: FEN.start, assetsCache: false, assetsUrl: "../../assets/", extensions: [{class: Markers}] }) board1.context.addEventListener("contextmenu", (event) => { event.preventDefault() }) board1.context.addEventListener("mousedown", (event) => { console.log("mousedown board1", event) let markerType if (event.button === 0) { markerType = MARKER_TYPE.dot } else { markerType = MARKER_TYPE.circlePrimary } const square = event.target.getAttribute("data-square") const markersOnSquare = board1.getMarkers(markerType, square) if (markersOnSquare.length > 0) { board1.removeMarkers(markerType, square) } else { board1.addMarker(markerType, square) } }) ``` -------------------------------- ### Run cm-chessboard Tests with Teevi Source: https://github.com/shaack/cm-chessboard/blob/master/test/index.html Imports necessary test modules and runs the test suite using the Teevi framework. Ensure Teevi and the test modules are correctly imported. ```javascript import {teevi} from "../node_modules/teevi/src/teevi.js" import "./TestChessboard.js" import "./TestPiecesAnimation.js" import "./TestMarkers.js" import "./TestPosition.js" teevi.run() ``` -------------------------------- ### Enable User Move Input with Markers Extension Source: https://github.com/shaack/cm-chessboard/blob/master/README.md Enables user interaction for moving pieces on the chessboard. Requires importing and enabling the Markers extension. The input handler function determines which move input events are allowed. ```javascript import {Chessboard, FEN, INPUT_EVENT_TYPE} from "./path/to/Chessboard.js" import {Markers} from "./path/to/extensions/markers/Markers.js" 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 } } ``` -------------------------------- ### Enable Chessboard with Move Validation and Promotion Source: https://github.com/shaack/cm-chessboard/blob/master/examples/validate-moves-chess960.html Initializes the Chessboard with chess.js for validation, enables move input for white, and configures extensions for markers, annotation, promotion dialog, and accessibility. The `inputHandler` manages move logic, including validation, promotion, and triggering engine moves. ```javascript import {INPUT_EVENT_TYPE, COLOR, Chessboard, BORDER_TYPE} from "../src/Chessboard.js" import {MARKER_TYPE, Markers} from "../src/extensions/markers/Markers.js" import {PROMOTION_DIALOG_RESULT_TYPE, PromotionDialog} from "../src/extensions/promotion-dialog/PromotionDialog.js" import {Accessibility} from "../src/extensions/accessibility/Accessibility.js" import {Chess} from "https://cdn.jsdelivr.net/npm/chess.mjs@2/src/Chess.js" import {RightClickAnnotator} from "../src/extensions/right-click-annotator/RightClickAnnotator.js" const chess = new Chess("bnrqnkrb/pppppppp/8/8/8/8/PPPPPPPP/BNRQNKRB w KQkq - 0 1", {chess960: true}) let seed = 71 function random() { const x = Math.sin(seed++) * 10000 return x - Math.floor(x) } function makeEngineMove(chessboard) { const possibleMoves = chess.moves({verbose: true}) if (possibleMoves.length > 0) { const randomIndex = Math.floor(random() * possibleMoves.length) const randomMove = possibleMoves[randomIndex] setTimeout(() => { // smoother with 500ms delay chess.move({from: randomMove.from, to: randomMove.to}) chessboard.setPosition(chess.fen(), true) chessboard.enableMoveInput(inputHandler, COLOR.white) }, 500) } } function inputHandler(event) { console.log("inputHandler", event) if (event.type === INPUT_EVENT_TYPE.movingOverSquare) { return // ignore this event } if (event.type !== INPUT_EVENT_TYPE.moveInputFinished) { event.chessboard.removeLegalMovesMarkers() } if (event.type === INPUT_EVENT_TYPE.moveInputStarted) { // mark legal moves const moves = chess.moves({square: event.squareFrom, verbose: true}) event.chessboard.addLegalMovesMarkers(moves) return moves.length > 0 } else if (event.type === INPUT_EVENT_TYPE.validateMoveInput) { const move = {from: event.squareFrom, to: event.squareTo, promotion: event.promotion} const result = chess.move(move) if (result) { event.chessboard.state.moveInputProcess.then(() => { // wait for the move input process has finished event.chessboard.setPosition(chess.fen(), true).then(() => { // update position, maybe castled and wait for animation has finished makeEngineMove(event.chessboard) }) }) } else { // promotion? let possibleMoves = chess.moves({square: event.squareFrom, verbose: true}) for (const possibleMove of possibleMoves) { if (possibleMove.promotion && possibleMove.to === event.squareTo) { event.chessboard.showPromotionDialog(event.squareTo, COLOR.white, (result) => { console.log("promotion result", result) if (result.type === PROMOTION_DIALOG_RESULT_TYPE.pieceSelected) { chess.move({ from: event.squareFrom, to: event.squareTo, promotion: result.piece.charAt(1) }) event.chessboard.setPosition(chess.fen(), true) makeEngineMove(event.chessboard) } else { // promotion canceled event.chessboard.enableMoveInput(inputHandler, COLOR.white) event.chessboard.setPosition(chess.fen(), true) } }) return true } } } return result } else if (event.type === INPUT_EVENT_TYPE.moveInputFinished) { if (event.legalMove) { event.chessboard.disableMoveInput() } } } const board = new Chessboard(document.getElementById("board"), { position: chess.fen(), assetsUrl: "../assets/", style: {borderType: BORDER_TYPE.none, pieces: {file: "pieces/staunty.svg"}, animationDuration: 300}, orientation: COLOR.white, extensions: [ {class: Markers, props: {autoMarkers: MARKER_TYPE.square}}, {class: RightClickAnnotator}, {class: PromotionDialog}, {class: Accessibility, props: {visuallyHidden: true}} ] }) board.enableMoveInput(inputHandler, COLOR.white) ``` -------------------------------- ### Responsive Chessboard with Debug Mode Source: https://github.com/shaack/cm-chessboard/blob/master/examples/responsive-board.html Initialize a responsive chessboard with a specific aspect ratio, custom pieces, and debug mode enabled. The AutoBorderNone extension is included to automatically remove the frame border on smaller boards. ```javascript import {BORDER_TYPE, Chessboard} from "../src/Chessboard.js" import {FEN} from "../src/model/Position.js" import {AutoBorderNone} from "../src/extensions/auto-border-none/AutoBorderNone.js" new Chessboard(document.getElementById("board"), { position: FEN.start, assetsUrl: "../assets/", debug: true, style: { aspectRatio: 0.9, pieces: {file: "pieces/staunty.svg"}, borderType: BORDER_TYPE.frame }, extensions: [{"class": AutoBorderNone} ]) ``` -------------------------------- ### Advanced Arrow Manipulation with Imports Source: https://github.com/shaack/cm-chessboard/blob/master/examples/extensions/arrows-extension.html Demonstrates adding multiple arrows of different types and then logging them. Requires importing ARROW_TYPE and Arrows. ```javascript import {ARROW_TYPE, Arrows} from "../../src/extensions/arrows/Arrows.js" import {Chessboard} from "../../src/Chessboard.js" const chessboard = new Chessboard(document.getElementById("board"), { position: "rn2k1r1/ppp1pp1p/3p2p1/5bn1/P7/2N2B2/1PPPPP2/2BNK1RR w Gkq - 4 11", assetsUrl: "../../assets/", extensions: [{class: Arrows}] }) chessboard.addArrow(ARROW_TYPE.danger, "f3", "d5") chessboard.addArrow(ARROW_TYPE.info, "b8", "c6") chessboard.addArrow(ARROW_TYPE.success, "d2", "d3") chessboard.addArrow(ARROW_TYPE.warning, "g5", "e6") chessboard.addArrow(ARROW_TYPE.secondary, "a1", "c3") console.log(chessboard.getArrows()) ``` -------------------------------- ### Registering an Extension Point in a Custom Extension Source: https://github.com/shaack/cm-chessboard/blob/master/README.md Demonstrates how to register a callback for a specific extension point within a custom chessboard extension. Ensure the extension point is defined in `Extension.js`. ```javascript 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) }) } } ``` -------------------------------- ### Enable and Log Pointer Events on Chessboard Source: https://github.com/shaack/cm-chessboard/blob/master/examples/pointer-events.html Enables square selection for all defined pointer events and logs the event details to the console when a square is clicked. Requires the Chessboard and FEN/POINTER_EVENTS modules. ```javascript import {Chessboard} from "./../src/Chessboard.js" import {FEN, POINTER_EVENTS} from "../src/Chessboard.js" const board = new Chessboard(document.getElementById("board"), { position: FEN.start, assetsUrl: "../assets/" }) for (const pointerEvent in POINTER_EVENTS) { console.log("pointerEvent", pointerEvent) board.enableSquareSelect(pointerEvent, (event) => { console.log(event) }) } ``` -------------------------------- ### Default Chessboard Configuration Source: https://github.com/shaack/cm-chessboard/blob/master/README.md Defines the default properties for initializing a cm-chessboard instance. This includes settings for position, orientation, responsiveness, assets, styling, and extensions. ```javascript 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: { ... }} */] } ``` -------------------------------- ### Initialize Chessboard with Right-Click Annotator Source: https://github.com/shaack/cm-chessboard/blob/master/examples/extensions/right-click-annotator.html Initializes the cm-chessboard with the RightClickAnnotator extension enabled. This allows for interactive annotation of the board. ```javascript import {Chessboard} from "../../src/Chessboard.js" import {FEN} from "../../src/model/Position.js" import {RightClickAnnotator} from "../../src/extensions/right-click-annotator/RightClickAnnotator.js" const board = new Chessboard(document.getElementById("board"), { position: FEN.start, assetsUrl: "../../assets/", extensions: [{class: RightClickAnnotator}] }) ``` -------------------------------- ### addExtension Source: https://github.com/shaack/cm-chessboard/blob/master/README.md Adds an extension at runtime. Throws if the extension class is already added. ```APIDOC ## addExtension(extensionClass, props) ### Description Adds an extension at runtime. Throws if the extension class is already added. ### Parameters #### Path Parameters - **extensionClass** (class) - Required - The class of the extension to add. - **props** (object) - Optional - Properties to pass to the extension. ``` -------------------------------- ### getExtension Source: https://github.com/shaack/cm-chessboard/blob/master/README.md Returns the instance of an added extension, or null if not found. ```APIDOC ## getExtension(extensionClass) ### Description Returns the instance of an added extension, or `null` if not found. ### Parameters #### Path Parameters - **extensionClass** (class) - Required - The class of the extension to retrieve. ``` -------------------------------- ### Create HTML Container for Chessboard Source: https://github.com/shaack/cm-chessboard/blob/master/README.md Define a div element with a unique ID to serve as the container for the chessboard. ```html
``` -------------------------------- ### Enable Move Input with Validation and Promotion Source: https://github.com/shaack/cm-chessboard/blob/master/examples/validate-moves.html Enables move input for white, using chess.js for validation and a promotion dialog. The engine makes random moves after each valid human move. ```javascript import {INPUT_EVENT_TYPE, COLOR, Chessboard, BORDER_TYPE} from "../src/Chessboard.js" import {MARKER_TYPE, Markers} from "../src/extensions/markers/Markers.js" import {PROMOTION_DIALOG_RESULT_TYPE, PromotionDialog} from "../src/extensions/promotion-dialog/PromotionDialog.js" import {Accessibility} from "../src/extensions/accessibility/Accessibility.js" import {Chess} from "https://cdn.jsdelivr.net/npm/chess.mjs@1/src/chess.mjs/Chess.js" import {RightClickAnnotator} from "../src/extensions/right-click-annotator/RightClickAnnotator.js"; const chess = new Chess() let seed = 71; function random() { const x = Math.sin(seed++) * 10000; return x - Math.floor(x); } function makeEngineMove(chessboard) { const possibleMoves = chess.moves({verbose: true}) if (possibleMoves.length > 0) { const randomIndex = Math.floor(random() * possibleMoves.length) const randomMove = possibleMoves[randomIndex] setTimeout(() => { // smoother with 500ms delay chess.move({from: randomMove.from, to: randomMove.to}) chessboard.setPosition(chess.fen(), true) chessboard.enableMoveInput(inputHandler, COLOR.white) }, 500) } } function inputHandler(event) { console.log("inputHandler", event) if(event.type === INPUT_EVENT_TYPE.movingOverSquare) { return // ignore this event } if(event.type !== INPUT_EVENT_TYPE.moveInputFinished) { event.chessboard.removeLegalMovesMarkers() } if (event.type === INPUT_EVENT_TYPE.moveInputStarted) { // mark legal moves const moves = chess.moves({square: event.squareFrom, verbose: true}) event.chessboard.addLegalMovesMarkers(moves) return moves.length > 0 } else if (event.type === INPUT_EVENT_TYPE.validateMoveInput) { const move = {from: event.squareFrom, to: event.squareTo, promotion: event.promotion} const result = chess.move(move) if (result) { event.chessboard.state.moveInputProcess.then(() => { // wait for the move input process has finished event.chessboard.setPosition(chess.fen(), true).then(() => { // update position, maybe castled and wait for animation has finished makeEngineMove(event.chessboard) }) }) } else { // promotion? let possibleMoves = chess.moves({square: event.squareFrom, verbose: true}) for (const possibleMove of possibleMoves) { if (possibleMove.promotion && possibleMove.to === event.squareTo) { event.chessboard.showPromotionDialog(event.squareTo, COLOR.white, (result) => { console.log("promotion result", result) if (result.type === PROMOTION_DIALOG_RESULT_TYPE.pieceSelected) { chess.move({from: event.squareFrom, to: event.squareTo, promotion: result.piece.charAt(1)}) event.chessboard.setPosition(chess.fen(), true) makeEngineMove(event.chessboard) } else { // promotion canceled event.chessboard.enableMoveInput(inputHandler, COLOR.white) event.chessboard.setPosition(chess.fen(), true) } }) return true } } } return result } else if (event.type === INPUT_EVENT_TYPE.moveInputFinished) { if(event.legalMove) { event.chessboard.disableMoveInput() } } } const board = new Chessboard(document.getElementById("board"), { position: chess.fen(), assetsUrl: "../assets/", style: {borderType: BORDER_TYPE.none, pieces: {file: "pieces/staunty.svg"}, animationDuration: 300}, orientation: COLOR.white, extensions: [ {class: Markers, props: {autoMarkers: MARKER_TYPE.square}}, {class: RightClickAnnotator}, {class: PromotionDialog}, {class: Accessibility, props: {visuallyHidden: true}} ] }) board.enableMoveInput(inputHandler, COLOR.white) ``` -------------------------------- ### Include CSS File for cm-chessboard Source: https://github.com/shaack/cm-chessboard/blob/master/README.md Include this CSS file to style the chessboard. Some extensions may require additional CSS. ```html ``` -------------------------------- ### enableMoveInput Source: https://github.com/shaack/cm-chessboard/blob/master/README.md Enables user input for moving pieces on the chessboard. Requires an input handler function to process move events. ```APIDOC ## enableMoveInput(inputHandler) ### Description Enables the user to move pieces on the chessboard. An `inputHandler` function is required to process move events. ### Method `board.enableMoveInput(inputHandler)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript board.enableMoveInput(inputHandler) function inputHandler(event) { console.log(event) if(event.type === INPUT_EVENT_TYPE.moveInputStarted || event.type === INPUT_EVENT_TYPE.validateMoveInput) { return true // false cancels move } } ``` ### Response None #### Success Response (200) None #### Response Example None ```