2 * chessboard.js v0.3.0+asn
4 * Copyright 2013 Chris Oakman
5 * Portions copyright 2022 Steinar H. Gunderson
6 * Released under the MIT license
7 * http://chessboardjs.com/license
12 // start anonymous scope
16 //------------------------------------------------------------------------------
17 // Chess Util Functions
18 //------------------------------------------------------------------------------
19 var COLUMNS = 'abcdefgh'.split('');
21 function validMove(move) {
22 // move should be a string
23 if (typeof move !== 'string') return false;
25 // move should be in the form of "e2-e4", "f6-d5"
26 var tmp = move.split('-');
27 if (tmp.length !== 2) return false;
29 return (validSquare(tmp[0]) === true && validSquare(tmp[1]) === true);
32 function validSquare(square) {
33 if (typeof square !== 'string') return false;
34 return (square.search(/^[a-h][1-8]$/) !== -1);
37 function validPieceCode(code) {
38 if (typeof code !== 'string') return false;
39 return (code.search(/^[bw][KQRNBP]$/) !== -1);
42 // TODO: this whole function could probably be replaced with a single regex
43 function validFen(fen) {
44 if (typeof fen !== 'string') return false;
46 // cut off any move, castling, etc info from the end
47 // we're only interested in position information
48 fen = fen.replace(/ .+$/, '');
50 // FEN should be 8 sections separated by slashes
51 var chunks = fen.split('/');
52 if (chunks.length !== 8) return false;
54 // check the piece sections
55 for (var i = 0; i < 8; i++) {
56 if (chunks[i] === '' ||
57 chunks[i].length > 8 ||
58 chunks[i].search(/[^kqrbnpKQRNBP1-8]/) !== -1) {
66 function validPositionObject(pos) {
67 if (typeof pos !== 'object') return false;
70 if (pos.hasOwnProperty(i) !== true) continue;
72 if (validSquare(i) !== true || validPieceCode(pos[i]) !== true) {
80 // convert FEN piece code to bP, wK, etc
81 function fenToPieceCode(piece) {
83 if (piece.toLowerCase() === piece) {
84 return 'b' + piece.toUpperCase();
88 return 'w' + piece.toUpperCase();
91 // convert bP, wK, etc code to FEN structure
92 function pieceCodeToFen(piece) {
93 var tmp = piece.split('');
97 return tmp[1].toUpperCase();
101 return tmp[1].toLowerCase();
104 // convert FEN string to position object
105 // returns false if the FEN string is invalid
106 function fenToObj(fen) {
107 if (validFen(fen) !== true) {
111 // cut off any move, castling, etc info from the end
112 // we're only interested in position information
113 fen = fen.replace(/ .+$/, '');
115 var rows = fen.split('/');
119 for (var i = 0; i < 8; i++) {
120 var row = rows[i].split('');
123 // loop through each character in the FEN section
124 for (var j = 0; j < row.length; j++) {
125 // number / empty squares
126 if (row[j].search(/[1-8]/) !== -1) {
127 var emptySquares = parseInt(row[j], 10);
128 colIndex += emptySquares;
132 var square = COLUMNS[colIndex] + currentRow;
133 position[square] = fenToPieceCode(row[j]);
144 // position object to FEN string
145 // returns false if the obj is not a valid position object
146 function objToFen(obj) {
147 if (validPositionObject(obj) !== true) {
154 for (var i = 0; i < 8; i++) {
155 for (var j = 0; j < 8; j++) {
156 var square = COLUMNS[j] + currentRow;
159 if (obj.hasOwnProperty(square) === true) {
160 fen += pieceCodeToFen(obj[square]);
176 // squeeze the numbers together
177 // haha, I love this solution...
178 fen = fen.replace(/11111111/g, '8');
179 fen = fen.replace(/1111111/g, '7');
180 fen = fen.replace(/111111/g, '6');
181 fen = fen.replace(/11111/g, '5');
182 fen = fen.replace(/1111/g, '4');
183 fen = fen.replace(/111/g, '3');
184 fen = fen.replace(/11/g, '2');
193 window.ChessBoard = function(containerElOrId, cfg) {
198 //------------------------------------------------------------------------------
200 //------------------------------------------------------------------------------
202 var MINIMUM_JQUERY_VERSION = '1.7.0',
203 START_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR',
204 START_POSITION = fenToObj(START_FEN);
206 // use unique class names to prevent clashing with anything else on the page
207 // and simplify selectors
209 alpha: 'alpha-d2270',
210 board: 'board-b72b1',
211 chessboard: 'chessboard-63f37',
212 clearfix: 'clearfix-7da63',
213 highlight1: 'highlight1-32417',
214 highlight2: 'highlight2-9c5d2',
215 notation: 'notation-322f9',
216 numeric: 'numeric-fc462',
217 piece: 'piece-417db',
219 sparePieces: 'spare-pieces-7492f',
220 sparePiecesBottom: 'spare-pieces-bottom-ae20f',
221 sparePiecesTop: 'spare-pieces-top-4028b',
222 square: 'square-55d63'
225 CSSColor['white'] = 'white-1e1d7';
226 CSSColor['black'] = 'black-3c85d';
228 //------------------------------------------------------------------------------
229 // Module Scope Variables
230 //------------------------------------------------------------------------------
239 // constructor return object
242 //------------------------------------------------------------------------------
244 //------------------------------------------------------------------------------
246 var BOARD_BORDER_SIZE = 2,
247 CURRENT_ORIENTATION = 'white',
248 CURRENT_POSITION = {},
251 DRAGGED_PIECE_LOCATION,
252 DRAGGED_PIECE_SOURCE,
253 DRAGGING_A_PIECE = false,
254 SPARE_PIECE_ELS_IDS = {},
258 //------------------------------------------------------------------------------
260 //------------------------------------------------------------------------------
263 function createId() {
264 return 'chesspiece-id-' + (id_counter++);
267 function deepCopy(thing) {
268 return JSON.parse(JSON.stringify(thing));
271 function parseSemVer(version) {
272 var tmp = version.split('.');
274 major: parseInt(tmp[0], 10),
275 minor: parseInt(tmp[1], 10),
276 patch: parseInt(tmp[2], 10)
280 // returns true if version is >= minimum
281 function compareSemVer(version, minimum) {
282 version = parseSemVer(version);
283 minimum = parseSemVer(minimum);
285 var versionNum = (version.major * 10000 * 10000) +
286 (version.minor * 10000) + version.patch;
287 var minimumNum = (minimum.major * 10000 * 10000) +
288 (minimum.minor * 10000) + minimum.patch;
290 return (versionNum >= minimumNum);
293 //------------------------------------------------------------------------------
294 // Validation / Errors
295 //------------------------------------------------------------------------------
298 * @param {!number} code
299 * @param {!string} msg
300 * @param {Object=} obj
302 function error(code, msg, obj) {
303 // do nothing if showErrors is not set
304 if (cfg.hasOwnProperty('showErrors') !== true ||
305 cfg.showErrors === false) {
309 var errorText = 'ChessBoard Error ' + code + ': ' + msg;
312 if (cfg.showErrors === 'console' &&
313 typeof console === 'object' &&
314 typeof console.log === 'function') {
315 console.log(errorText);
316 if (arguments.length >= 2) {
323 if (cfg.showErrors === 'alert') {
325 errorText += '\n\n' + JSON.stringify(obj);
327 window.alert(errorText);
332 if (typeof cfg.showErrors === 'function') {
333 cfg.showErrors(code, msg, obj);
337 // check dependencies
338 function checkDeps() {
339 // if containerId is a string, it must be the ID of a DOM node
340 if (typeof containerElOrId === 'string') {
342 if (containerElOrId === '') {
343 window.alert('ChessBoard Error 1001: ' +
344 'The first argument to ChessBoard() cannot be an empty string.' +
349 // make sure the container element exists in the DOM
350 var el = document.getElementById(containerElOrId);
352 window.alert('ChessBoard Error 1002: Element with id "' +
353 containerElOrId + '" does not exist in the DOM.' +
358 // set the containerEl
362 // else it must be a DOM node
364 containerEl = containerElOrId;
370 function validAnimationSpeed(speed) {
371 if (speed === 'fast' || speed === 'slow') {
375 if ((parseInt(speed, 10) + '') !== (speed + '')) {
382 // validate config / set default options
383 function expandConfig() {
384 if (typeof cfg === 'string' || validPositionObject(cfg) === true) {
390 // default for orientation is white
391 if (cfg.orientation !== 'black') {
392 cfg.orientation = 'white';
394 CURRENT_ORIENTATION = cfg.orientation;
396 // default for showNotation is true
397 if (cfg.showNotation !== false) {
398 cfg.showNotation = true;
401 // default for draggable is false
402 if (cfg.draggable !== true) {
403 cfg.draggable = false;
406 // default for dropOffBoard is 'snapback'
407 if (cfg.dropOffBoard !== 'trash') {
408 cfg.dropOffBoard = 'snapback';
411 // default for sparePieces is false
412 if (cfg.sparePieces !== true) {
413 cfg.sparePieces = false;
416 // draggable must be true if sparePieces is enabled
417 if (cfg.sparePieces === true) {
418 cfg.draggable = true;
421 // default piece theme is wikipedia
422 if (cfg.hasOwnProperty('pieceTheme') !== true ||
423 (typeof cfg.pieceTheme !== 'string' &&
424 typeof cfg.pieceTheme !== 'function')) {
425 cfg.pieceTheme = 'img/chesspieces/wikipedia/{piece}.png';
429 if (cfg.hasOwnProperty('appearSpeed') !== true ||
430 validAnimationSpeed(cfg.appearSpeed) !== true) {
431 cfg.appearSpeed = 200;
433 if (cfg.hasOwnProperty('moveSpeed') !== true ||
434 validAnimationSpeed(cfg.moveSpeed) !== true) {
437 if (cfg.hasOwnProperty('snapbackSpeed') !== true ||
438 validAnimationSpeed(cfg.snapbackSpeed) !== true) {
439 cfg.snapbackSpeed = 50;
441 if (cfg.hasOwnProperty('snapSpeed') !== true ||
442 validAnimationSpeed(cfg.snapSpeed) !== true) {
445 if (cfg.hasOwnProperty('trashSpeed') !== true ||
446 validAnimationSpeed(cfg.trashSpeed) !== true) {
447 cfg.trashSpeed = 100;
450 // make sure position is valid
451 if (cfg.hasOwnProperty('position') === true) {
452 if (cfg.position === 'start') {
453 CURRENT_POSITION = deepCopy(START_POSITION);
456 else if (validFen(cfg.position) === true) {
457 CURRENT_POSITION = fenToObj(cfg.position);
460 else if (validPositionObject(cfg.position) === true) {
461 CURRENT_POSITION = deepCopy(cfg.position);
465 error(7263, 'Invalid value passed to config.position.', cfg.position);
472 //------------------------------------------------------------------------------
474 //------------------------------------------------------------------------------
476 // calculates square size based on the width of the container
477 // got a little CSS black magic here, so let me explain:
478 // get the width of the container element (could be anything), reduce by 1 for
479 // fudge factor, and then keep reducing until we find an exact mod 8 for
481 function calculateSquareSize() {
482 var containerWidth = parseInt(getComputedStyle(containerEl).width, 10);
484 // defensive, prevent infinite loop
485 if (! containerWidth || containerWidth <= 0) {
490 var boardWidth = containerWidth - 1;
492 while (boardWidth % 8 !== 0 && boardWidth > 0) {
496 return (boardWidth / 8);
499 // create random IDs for elements
500 function createElIds() {
501 // squares on the board
502 for (var i = 0; i < COLUMNS.length; i++) {
503 for (var j = 1; j <= 8; j++) {
504 var square = COLUMNS[i] + j;
505 SQUARE_ELS_IDS[square] = square + '-' + createId();
510 var pieces = 'KQRBNP'.split('');
511 for (var i = 0; i < pieces.length; i++) {
512 var whitePiece = 'w' + pieces[i];
513 var blackPiece = 'b' + pieces[i];
514 SPARE_PIECE_ELS_IDS[whitePiece] = whitePiece + '-' + createId();
515 SPARE_PIECE_ELS_IDS[blackPiece] = blackPiece + '-' + createId();
519 //------------------------------------------------------------------------------
521 //------------------------------------------------------------------------------
523 function buildBoardContainer() {
524 var html = '<div class="' + CSS.chessboard + '">';
526 if (cfg.sparePieces === true) {
527 html += '<div class="' + CSS.sparePieces + ' ' +
528 CSS.sparePiecesTop + '"></div>';
531 html += '<div class="' + CSS.board + '"></div>';
533 if (cfg.sparePieces === true) {
534 html += '<div class="' + CSS.sparePieces + ' ' +
535 CSS.sparePiecesBottom + '"></div>';
544 var buildSquare = function(color, size, id) {
545 var html = '<div class="' + CSS.square + ' ' + CSSColor[color] + '" ' +
546 'style="width: ' + size + 'px; height: ' + size + 'px" ' +
549 if (cfg.showNotation === true) {
559 function buildBoard(orientation) {
560 if (orientation !== 'black') {
561 orientation = 'white';
566 // algebraic notation / orientation
567 var alpha = deepCopy(COLUMNS);
569 if (orientation === 'black') {
574 var squareColor = 'white';
575 for (var i = 0; i < 8; i++) {
576 html += '<div class="' + CSS.row + '">';
577 for (var j = 0; j < 8; j++) {
578 var square = alpha[j] + row;
580 html += '<div class="' + CSS.square + ' ' + CSSColor[squareColor] + ' ' +
581 'square-' + square + '" ' +
582 'style="width: ' + SQUARE_SIZE + 'px; height: ' + SQUARE_SIZE + 'px" ' +
583 'id="' + SQUARE_ELS_IDS[square] + '" ' +
584 'data-square="' + square + '">';
586 if (cfg.showNotation === true) {
588 if ((orientation === 'white' && row === 1) ||
589 (orientation === 'black' && row === 8)) {
590 html += '<div class="' + CSS.notation + ' ' + CSS.alpha + '">' +
596 html += '<div class="' + CSS.notation + ' ' + CSS.numeric + '">' +
601 html += '</div>'; // end .square
603 squareColor = (squareColor === 'white' ? 'black' : 'white');
605 html += '<div class="' + CSS.clearfix + '"></div></div>';
607 squareColor = (squareColor === 'white' ? 'black' : 'white');
609 if (orientation === 'white') {
620 function buildPieceImgSrc(piece) {
621 if (typeof cfg.pieceTheme === 'function') {
622 return cfg.pieceTheme(piece);
625 if (typeof cfg.pieceTheme === 'string') {
626 return cfg.pieceTheme.replace(/{piece}/g, piece);
629 // NOTE: this should never happen
630 error(8272, 'Unable to build image source for cfg.pieceTheme.');
635 * @param {!string} piece
636 * @param {boolean=} hidden
637 * @param {!string=} id
639 function buildPiece(piece, hidden, id) {
640 let img = document.createElement('img');
641 img.src = buildPieceImgSrc(piece);
642 if (id && typeof id === 'string') {
643 img.setAttribute('id', id);
645 img.setAttribute('alt', '');
646 img.classList.add(CSS.piece);
647 img.setAttribute('data-piece', piece);
648 img.style.width = SQUARE_SIZE + 'px';
649 img.style.height = SQUARE_SIZE + 'px';
650 if (hidden === true) {
651 img.style.display = 'none';
656 function buildSparePieces(color) {
657 var pieces = ['wK', 'wQ', 'wR', 'wB', 'wN', 'wP'];
658 if (color === 'black') {
659 pieces = ['bK', 'bQ', 'bR', 'bB', 'bN', 'bP'];
663 for (var i = 0; i < pieces.length; i++) {
664 html += buildPiece(pieces[i], false, SPARE_PIECE_ELS_IDS[pieces[i]]);
670 //------------------------------------------------------------------------------
672 //------------------------------------------------------------------------------
674 function offset(el) { // From https://youmightnotneedjquery.com/.
675 let box = el.getBoundingClientRect();
676 let docElem = document.documentElement;
678 top: box.top + window.pageYOffset - docElem.clientTop,
679 left: box.left + window.pageXOffset - docElem.clientLeft
683 function animateSquareToSquare(src, dest, piece, completeFn) {
684 // get information about the source and destination squares
685 var srcSquareEl = document.getElementById(SQUARE_ELS_IDS[src]);
686 var srcSquarePosition = offset(srcSquareEl);
687 var destSquareEl = document.getElementById(SQUARE_ELS_IDS[dest]);
688 var destSquarePosition = offset(destSquareEl);
690 // create the animated piece and absolutely position it
691 // over the source square
692 var animatedPieceId = createId();
693 document.body.append(buildPiece(piece, true, animatedPieceId));
694 var animatedPieceEl = document.getElementById(animatedPieceId);
695 animatedPieceEl.style.display = null;
696 animatedPieceEl.style.position = 'absolute';
697 animatedPieceEl.style.top = srcSquarePosition.top + 'px';
698 animatedPieceEl.style.left = srcSquarePosition.left + 'px';
700 // remove original piece(s) from source square
701 // TODO: multiple pieces should never really happen, but it will if we are moving
702 // while another animation still isn't done
703 srcSquareEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
706 var complete = function() {
707 // add the "real" piece to the destination square
708 destSquareEl.append(buildPiece(piece));
710 // remove the animated piece
711 animatedPieceEl.remove();
713 // run complete function
714 if (typeof completeFn === 'function') {
719 // animate the piece to the destination square
720 animatedPieceEl.addEventListener('transitionend', complete, {once: true});
721 requestAnimationFrame(() => {
722 animatedPieceEl.style.transitionProperty = 'top, left';
723 animatedPieceEl.style.transitionDuration = cfg.moveSpeed + 'ms';
724 animatedPieceEl.style.top = destSquarePosition.top + 'px';
725 animatedPieceEl.style.left = destSquarePosition.left + 'px';
729 function animateSparePieceToSquare(piece, dest, completeFn) {
730 var srcOffset = offset(document.getelementById(SPARE_PIECE_ELS_IDS[piece]));
731 var destSquareEl = document.getElementById(SQUARE_ELS_IDS[dest]);
732 var destOffset = offset(destSquareEl);
734 // create the animate piece
735 var pieceId = createId();
736 document.body.append(buildPiece(piece, true, pieceId));
737 var animatedPieceEl = document.getElementById(pieceId);
738 animatedPieceEl.style.display = '';
739 animatedPieceEl.style.position = 'absolute';
740 animatedPieceEl.style.left = srcOffset.left;
741 animatedPieceEl.style.top = srcOffset.top;
744 var complete = function() {
745 // add the "real" piece to the destination square
746 destSquareEl.querySelector('.' + CSS.piece).remove();
747 destSquareEl.append(buildPiece(piece));
749 // remove the animated piece
750 animatedPieceEl.remove();
752 // run complete function
753 if (typeof completeFn === 'function') {
758 // animate the piece to the destination square
759 // FIXME: support this for non-jquery
761 duration: cfg.moveSpeed,
764 //$(animatedPieceEl).animate(destOffset, opts);
767 function fadeIn(pieces, onFinish) {
768 pieces.forEach((piece) => {
769 piece.style.opacity = 0;
770 piece.style.display = null;
771 piece.addEventListener('transitionend', onFinish, {once: true});
773 requestAnimationFrame(() => {
774 pieces.forEach((piece) => {
775 piece.style.transitionProperty = 'opacity';
776 piece.style.transitionDuration = cfg.appearSpeed + 'ms';
777 piece.style.opacity = 1;
782 function fadeOut(pieces, onFinish) {
783 pieces.forEach((piece) => {
784 piece.style.opacity = 1;
785 piece.style.display = null;
786 piece.addEventListener('transitionend', onFinish, {once: true});
788 requestAnimationFrame(() => {
789 pieces.forEach((piece) => {
790 piece.style.transitionProperty = 'opacity';
791 piece.style.transitionDuration = cfg.trashSpeed + 'ms';
792 piece.style.opacity = 0;
797 // execute an array of animations
798 function doAnimations(a, oldPos, newPos) {
800 function onFinish(e) {
802 e.target.transitionProperty = null;
807 // exit if all the animations aren't finished
808 if (numFinished !== a.length) return;
810 drawPositionInstant();
812 // run their onMoveEnd function
813 if (cfg.hasOwnProperty('onMoveEnd') === true &&
814 typeof cfg.onMoveEnd === 'function') {
815 cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
819 requestAnimationFrame(() => { // Firefox workaround.
820 let fadeout_pieces = [];
821 let fadein_pieces = [];
823 for (var i = 0; i < a.length; i++) {
825 if (a[i].type === 'clear') {
826 document.getElementById(SQUARE_ELS_IDS[a[i].square]).querySelectorAll('.' + CSS.piece).forEach(
827 (piece) => fadeout_pieces.push(piece)
831 // add a piece (no spare pieces)
832 if (a[i].type === 'add' && cfg.sparePieces !== true) {
833 let square = document.getElementById(SQUARE_ELS_IDS[a[i].square]);
834 square.append(buildPiece(a[i].piece, true));
835 let piece = square.querySelector('.' + CSS.piece);
836 fadein_pieces.push(piece);
839 // add a piece from a spare piece
840 if (a[i].type === 'add' && cfg.sparePieces === true) {
841 animateSparePieceToSquare(a[i].piece, a[i].square, onFinish);
845 if (a[i].type === 'move') {
846 animateSquareToSquare(a[i].source, a[i].destination, a[i].piece,
851 // TODO: Batch moves as well, not just fade in/out.
852 // (We batch them because requestAnimationFrame seemingly costs real time.)
853 if (fadeout_pieces.length > 0) {
854 fadeOut(fadeout_pieces, onFinish);
856 if (fadein_pieces.length > 0) {
857 fadeIn(fadein_pieces, onFinish);
862 // returns the distance between two squares
863 function squareDistance(s1, s2) {
865 var s1x = COLUMNS.indexOf(s1[0]) + 1;
866 var s1y = parseInt(s1[1], 10);
869 var s2x = COLUMNS.indexOf(s2[0]) + 1;
870 var s2y = parseInt(s2[1], 10);
872 var xDelta = Math.abs(s1x - s2x);
873 var yDelta = Math.abs(s1y - s2y);
875 if (xDelta >= yDelta) return xDelta;
879 // returns the square of the closest instance of piece
880 // returns false if no instance of piece is found in position
881 function findClosestPiece(position, piece, square) {
882 let best_square = false;
884 for (var i = 0; i < COLUMNS.length; i++) {
885 for (var j = 1; j <= 8; j++) {
886 let other_square = COLUMNS[i] + j;
888 if (position[other_square] === piece && square != other_square) {
889 let dist = squareDistance(square, other_square);
890 if (dist < best_dist) {
891 best_square = other_square;
901 // calculate an array of animations that need to happen in order to get
903 function calculateAnimations(pos1, pos2) {
904 // make copies of both
905 pos1 = deepCopy(pos1);
906 pos2 = deepCopy(pos2);
909 var squaresMovedTo = {};
911 // remove pieces that are the same in both positions
912 for (var i in pos2) {
913 if (pos2.hasOwnProperty(i) !== true) continue;
915 if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
921 // find all the "move" animations
922 for (var i in pos2) {
923 if (pos2.hasOwnProperty(i) !== true) continue;
925 var closestPiece = findClosestPiece(pos1, pos2[i], i);
926 if (closestPiece !== false) {
929 source: closestPiece,
934 delete pos1[closestPiece];
936 squaresMovedTo[i] = true;
940 // add pieces to pos2
941 for (var i in pos2) {
942 if (pos2.hasOwnProperty(i) !== true) continue;
953 // clear pieces from pos1
954 for (var i in pos1) {
955 if (pos1.hasOwnProperty(i) !== true) continue;
957 // do not clear a piece if it is on a square that is the result
958 // of a "move", ie: a piece capture
959 if (squaresMovedTo.hasOwnProperty(i) === true) continue;
973 //------------------------------------------------------------------------------
975 //------------------------------------------------------------------------------
977 function drawPositionInstant() {
979 boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
982 for (var i in CURRENT_POSITION) {
983 if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue;
985 document.getElementById(SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i]));
989 function drawBoard() {
990 boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
991 drawPositionInstant();
993 if (cfg.sparePieces === true) {
994 if (CURRENT_ORIENTATION === 'white') {
995 sparePiecesTopEl.innerHTML = buildSparePieces('black');
996 sparePiecesBottomEl.innerHTML = buildSparePieces('white');
999 sparePiecesTopEl.innerHTML = buildSparePieces('white');
1000 sparePiecesBottomEl.innerHTML = buildSparePieces('black');
1005 // given a position and a set of moves, return a new position
1006 // with the moves executed
1007 function calculatePositionFromMoves(position, moves) {
1008 position = deepCopy(position);
1010 for (var i in moves) {
1011 if (moves.hasOwnProperty(i) !== true) continue;
1013 // skip the move if the position doesn't have a piece on the source square
1014 if (position.hasOwnProperty(i) !== true) continue;
1016 var piece = position[i];
1018 position[moves[i]] = piece;
1024 function setCurrentPosition(position) {
1025 var oldPos = deepCopy(CURRENT_POSITION);
1026 var newPos = deepCopy(position);
1027 var oldFen = objToFen(oldPos);
1028 var newFen = objToFen(newPos);
1030 // do nothing if no change in position
1031 if (oldFen === newFen) return;
1033 // run their onChange function
1034 if (cfg.hasOwnProperty('onChange') === true &&
1035 typeof cfg.onChange === 'function') {
1036 cfg.onChange(oldPos, newPos);
1040 CURRENT_POSITION = position;
1043 function isXYOnSquare(x, y) {
1044 for (var i in SQUARE_ELS_OFFSETS) {
1045 if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue;
1047 var s = SQUARE_ELS_OFFSETS[i];
1048 if (x >= s.left && x < s.left + SQUARE_SIZE &&
1049 y >= s.top && y < s.top + SQUARE_SIZE) {
1057 // records the XY coords of every square into memory
1058 function captureSquareOffsets() {
1059 SQUARE_ELS_OFFSETS = {};
1061 for (var i in SQUARE_ELS_IDS) {
1062 if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue;
1064 SQUARE_ELS_OFFSETS[i] = offset(document.getElementById(SQUARE_ELS_IDS[i]));
1068 function removeSquareHighlights() {
1069 boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
1070 piece.classList.remove(CSS.highlight1);
1071 piece.classList.remove(CSS.highlight2);
1075 function snapbackDraggedPiece() {
1076 // there is no "snapback" for spare pieces
1077 if (DRAGGED_PIECE_SOURCE === 'spare') {
1078 trashDraggedPiece();
1082 removeSquareHighlights();
1084 // animation complete
1085 function complete() {
1086 drawPositionInstant();
1087 draggedPieceEl.style.display = 'none';
1089 // run their onSnapbackEnd function
1090 if (cfg.hasOwnProperty('onSnapbackEnd') === true &&
1091 typeof cfg.onSnapbackEnd === 'function') {
1092 cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
1093 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1097 // get source square position
1098 var sourceSquarePosition =
1099 offset(document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]));
1101 // animate the piece to the target square
1102 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1103 requestAnimationFrame(() => {
1104 draggedPieceEl.style.transitionProperty = 'top, left';
1105 draggedPieceEl.style.transitionDuration = cfg.snapbackSpeed + 'ms';
1106 draggedPieceEl.style.top = sourceSquarePosition.top + 'px';
1107 draggedPieceEl.style.left = sourceSquarePosition.left + 'px';
1111 DRAGGING_A_PIECE = false;
1114 function trashDraggedPiece() {
1115 removeSquareHighlights();
1117 // remove the source piece
1118 var newPosition = deepCopy(CURRENT_POSITION);
1119 delete newPosition[DRAGGED_PIECE_SOURCE];
1120 setCurrentPosition(newPosition);
1122 // redraw the position
1123 drawPositionInstant();
1125 // hide the dragged piece
1126 // FIXME: support this for non-jquery
1127 //$(draggedPieceEl).fadeOut(cfg.trashSpeed);
1130 DRAGGING_A_PIECE = false;
1133 function dropDraggedPieceOnSquare(square) {
1134 removeSquareHighlights();
1137 var newPosition = deepCopy(CURRENT_POSITION);
1138 delete newPosition[DRAGGED_PIECE_SOURCE];
1139 newPosition[square] = DRAGGED_PIECE;
1140 setCurrentPosition(newPosition);
1142 // get target square information
1143 var targetSquarePosition = offset(document.getElementById(SQUARE_ELS_IDS[square]));
1145 // animation complete
1146 var complete = function() {
1147 drawPositionInstant();
1148 draggedPieceEl.style.display = 'none';
1150 // execute their onSnapEnd function
1151 if (cfg.hasOwnProperty('onSnapEnd') === true &&
1152 typeof cfg.onSnapEnd === 'function') {
1153 requestAnimationFrame(() => { // HACK: so that we don't add event handlers from the callback...
1154 cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
1159 // snap the piece to the target square
1160 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1161 requestAnimationFrame(() => {
1162 draggedPieceEl.style.transitionProperty = 'top, left';
1163 draggedPieceEl.style.transitionDuration = cfg.snapSpeed + 'ms';
1164 draggedPieceEl.style.top = targetSquarePosition.top + 'px';
1165 draggedPieceEl.style.left = targetSquarePosition.left + 'px';
1169 DRAGGING_A_PIECE = false;
1172 function beginDraggingPiece(source, piece, x, y) {
1173 // run their custom onDragStart function
1174 // their custom onDragStart function can cancel drag start
1175 if (typeof cfg.onDragStart === 'function' &&
1176 cfg.onDragStart(source, piece,
1177 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
1182 DRAGGING_A_PIECE = true;
1183 DRAGGED_PIECE = piece;
1184 DRAGGED_PIECE_SOURCE = source;
1186 // if the piece came from spare pieces, location is offboard
1187 if (source === 'spare') {
1188 DRAGGED_PIECE_LOCATION = 'offboard';
1191 DRAGGED_PIECE_LOCATION = source;
1194 // capture the x, y coords of all squares in memory
1195 captureSquareOffsets();
1197 // create the dragged piece
1198 draggedPieceEl.setAttribute('src', buildPieceImgSrc(piece));
1199 draggedPieceEl.style.display = null;
1200 draggedPieceEl.style.position = 'absolute';
1201 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1202 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1204 if (source !== 'spare') {
1205 // highlight the source square and hide the piece
1206 let square = document.getElementById(SQUARE_ELS_IDS[source]);
1207 square.classList.add(CSS.highlight1);
1208 square.querySelector('.' + CSS.piece).style.display = 'none';
1212 function updateDraggedPiece(x, y) {
1213 // put the dragged piece over the mouse cursor
1214 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1215 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1218 var location = isXYOnSquare(x, y);
1220 // do nothing if the location has not changed
1221 if (location === DRAGGED_PIECE_LOCATION) return;
1223 // remove highlight from previous square
1224 if (validSquare(DRAGGED_PIECE_LOCATION) === true) {
1225 document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION])
1226 .classList.remove(CSS.highlight2);
1229 // add highlight to new square
1230 if (validSquare(location) === true) {
1231 document.getElementById(SQUARE_ELS_IDS[location]).classList.add(CSS.highlight2);
1235 if (typeof cfg.onDragMove === 'function') {
1236 cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1237 DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1238 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1242 DRAGGED_PIECE_LOCATION = location;
1245 function stopDraggedPiece(location) {
1246 // determine what the action should be
1247 var action = 'drop';
1248 if (location === 'offboard' && cfg.dropOffBoard === 'snapback') {
1249 action = 'snapback';
1251 if (location === 'offboard' && cfg.dropOffBoard === 'trash') {
1255 // run their onDrop function, which can potentially change the drop action
1256 if (cfg.hasOwnProperty('onDrop') === true &&
1257 typeof cfg.onDrop === 'function') {
1258 var newPosition = deepCopy(CURRENT_POSITION);
1260 // source piece is a spare piece and position is off the board
1261 //if (DRAGGED_PIECE_SOURCE === 'spare' && location === 'offboard') {...}
1262 // position has not changed; do nothing
1264 // source piece is a spare piece and position is on the board
1265 if (DRAGGED_PIECE_SOURCE === 'spare' && validSquare(location) === true) {
1266 // add the piece to the board
1267 newPosition[location] = DRAGGED_PIECE;
1270 // source piece was on the board and position is off the board
1271 if (validSquare(DRAGGED_PIECE_SOURCE) === true && location === 'offboard') {
1272 // remove the piece from the board
1273 delete newPosition[DRAGGED_PIECE_SOURCE];
1276 // source piece was on the board and position is on the board
1277 if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1278 validSquare(location) === true) {
1280 delete newPosition[DRAGGED_PIECE_SOURCE];
1281 newPosition[location] = DRAGGED_PIECE;
1284 var oldPosition = deepCopy(CURRENT_POSITION);
1286 var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE,
1287 newPosition, oldPosition, CURRENT_ORIENTATION);
1288 if (result === 'snapback' || result === 'trash') {
1294 if (action === 'snapback') {
1295 snapbackDraggedPiece();
1297 else if (action === 'trash') {
1298 trashDraggedPiece();
1300 else if (action === 'drop') {
1301 dropDraggedPieceOnSquare(location);
1305 //------------------------------------------------------------------------------
1307 //------------------------------------------------------------------------------
1310 widget.clear = function(useAnimation) {
1311 widget.position({}, useAnimation);
1315 // get or set config properties
1316 // TODO: write this, GitHub Issue #1
1317 widget.config = function(arg1, arg2) {
1318 // get the current config
1319 if (arguments.length === 0) {
1320 return deepCopy(cfg);
1325 // remove the widget from the page
1326 widget.destroy = function() {
1328 containerEl.innerHTML = '';
1329 draggedPieceEl.remove();
1332 // shorthand method to get the current FEN
1333 widget.fen = function() {
1334 return widget.position('fen');
1338 widget.flip = function() {
1339 widget.orientation('flip');
1343 // TODO: write this, GitHub Issue #5
1344 widget.highlight = function() {
1350 widget.move = function() {
1351 // no need to throw an error here; just do nothing
1352 if (arguments.length === 0) return;
1354 var useAnimation = true;
1356 // collect the moves into an object
1358 for (var i = 0; i < arguments.length; i++) {
1359 // any "false" to this function means no animations
1360 if (arguments[i] === false) {
1361 useAnimation = false;
1365 // skip invalid arguments
1366 if (validMove(arguments[i]) !== true) {
1367 error(2826, 'Invalid move passed to the move method.', arguments[i]);
1371 var tmp = arguments[i].split('-');
1372 moves[tmp[0]] = tmp[1];
1375 // calculate position from moves
1376 var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1379 widget.position(newPos, useAnimation);
1381 // return the new position object
1385 widget.orientation = function(arg) {
1386 // no arguments, return the current orientation
1387 if (arguments.length === 0) {
1388 return CURRENT_ORIENTATION;
1391 // set to white or black
1392 if (arg === 'white' || arg === 'black') {
1393 CURRENT_ORIENTATION = arg;
1399 if (arg === 'flip') {
1400 CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1405 error(5482, 'Invalid value passed to the orientation method.', arg);
1409 * @param {!string|!Object} position
1410 * @param {boolean=} useAnimation
1412 widget.position = function(position, useAnimation) {
1413 // no arguments, return the current position
1414 if (arguments.length === 0) {
1415 return deepCopy(CURRENT_POSITION);
1418 // get position as FEN
1419 if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1420 return objToFen(CURRENT_POSITION);
1423 // default for useAnimations is true
1424 if (useAnimation !== false) {
1425 useAnimation = true;
1429 if (typeof position === 'string' && position.toLowerCase() === 'start') {
1430 position = deepCopy(START_POSITION);
1433 // convert FEN to position object
1434 if (validFen(position) === true) {
1435 position = fenToObj(position);
1438 // validate position object
1439 if (validPositionObject(position) !== true) {
1440 error(6482, 'Invalid value passed to the position method.', position);
1444 if (useAnimation === true) {
1445 // start the animations
1446 doAnimations(calculateAnimations(CURRENT_POSITION, position),
1447 CURRENT_POSITION, position);
1449 // set the new position
1450 setCurrentPosition(position);
1454 setCurrentPosition(position);
1455 drawPositionInstant();
1459 widget.resize = function() {
1460 // calulate the new square size
1461 SQUARE_SIZE = calculateSquareSize();
1464 boardEl.style.width = (SQUARE_SIZE * 8) + 'px';
1466 // set drag piece size
1467 if (draggedPieceEl !== null) {
1468 draggedPieceEl.style.height = SQUARE_SIZE + 'px';
1469 draggedPieceEl.style.width = SQUARE_SIZE + 'px';
1473 if (cfg.sparePieces === true) {
1474 containerEl.querySelector('.' + CSS.sparePieces)
1475 .style.paddingLeft = (SQUARE_SIZE + BOARD_BORDER_SIZE) + 'px';
1482 // set the starting position
1483 widget.start = function(useAnimation) {
1484 widget.position('start', useAnimation);
1487 //------------------------------------------------------------------------------
1489 //------------------------------------------------------------------------------
1491 function isTouchDevice() {
1492 return ('ontouchstart' in document.documentElement);
1495 function mousedownSquare(e) {
1496 let target = e.target.closest('.' + CSS.square);
1501 // do nothing if we're not draggable
1502 if (cfg.draggable !== true) return;
1504 var square = target.getAttribute('data-square');
1506 // no piece on this square
1507 if (validSquare(square) !== true ||
1508 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1512 beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1515 function touchstartSquare(e) {
1516 let target = e.target.closest('.' + CSS.square);
1521 // do nothing if we're not draggable
1522 if (cfg.draggable !== true) return;
1524 var square = target.getAttribute('data-square');
1526 // no piece on this square
1527 if (validSquare(square) !== true ||
1528 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1532 beginDraggingPiece(square, CURRENT_POSITION[square],
1533 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1536 function mousedownSparePiece(e) {
1537 if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1541 // do nothing if sparePieces is not enabled
1542 if (cfg.sparePieces !== true) return;
1544 var piece = e.target.getAttribute('data-piece');
1546 beginDraggingPiece('spare', piece, e.pageX, e.pageY);
1549 function touchstartSparePiece(e) {
1550 if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1554 // do nothing if sparePieces is not enabled
1555 if (cfg.sparePieces !== true) return;
1557 var piece = e.target.getAttribute('data-piece');
1559 beginDraggingPiece('spare', piece,
1560 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1563 function mousemoveWindow(e) {
1564 // do nothing if we are not dragging a piece
1565 if (DRAGGING_A_PIECE !== true) return;
1567 updateDraggedPiece(e.pageX, e.pageY);
1570 function touchmoveWindow(e) {
1571 // do nothing if we are not dragging a piece
1572 if (DRAGGING_A_PIECE !== true) return;
1574 // prevent screen from scrolling
1577 updateDraggedPiece(e.changedTouches[0].pageX,
1578 e.changedTouches[0].pageY);
1581 function mouseupWindow(e) {
1582 // do nothing if we are not dragging a piece
1583 if (DRAGGING_A_PIECE !== true) return;
1586 var location = isXYOnSquare(e.pageX, e.pageY);
1588 stopDraggedPiece(location);
1591 function touchendWindow(e) {
1592 // do nothing if we are not dragging a piece
1593 if (DRAGGING_A_PIECE !== true) return;
1596 var location = isXYOnSquare(e.changedTouches[0].pageX,
1597 e.changedTouches[0].pageY);
1599 stopDraggedPiece(location);
1602 function mouseenterSquare(e) {
1603 let target = e.target.closest('.' + CSS.square);
1608 // do not fire this event if we are dragging a piece
1609 // NOTE: this should never happen, but it's a safeguard
1610 if (DRAGGING_A_PIECE !== false) return;
1612 if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1613 typeof cfg.onMouseoverSquare !== 'function') return;
1616 var square = target.getAttribute('data-square');
1618 // NOTE: this should never happen; defensive
1619 if (validSquare(square) !== true) return;
1621 // get the piece on this square
1623 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1624 piece = CURRENT_POSITION[square];
1627 // execute their function
1628 cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1629 CURRENT_ORIENTATION);
1632 function mouseleaveSquare(e) {
1633 let target = e.target.closest('.' + CSS.square);
1638 // do not fire this event if we are dragging a piece
1639 // NOTE: this should never happen, but it's a safeguard
1640 if (DRAGGING_A_PIECE !== false) return;
1642 if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1643 typeof cfg.onMouseoutSquare !== 'function') return;
1646 var square = target.getAttribute('data-square');
1648 // NOTE: this should never happen; defensive
1649 if (validSquare(square) !== true) return;
1651 // get the piece on this square
1653 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1654 piece = CURRENT_POSITION[square];
1657 // execute their function
1658 cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1659 CURRENT_ORIENTATION);
1662 //------------------------------------------------------------------------------
1664 //------------------------------------------------------------------------------
1666 function addEvents() {
1667 // prevent browser "image drag"
1668 let stopDefault = (e) => {
1669 if (e.target.matches('.' + CSS.piece)) {
1673 document.body.addEventListener('mousedown', stopDefault);
1674 document.body.addEventListener('mousemove', stopDefault);
1676 // mouse drag pieces
1677 boardEl.addEventListener('mousedown', mousedownSquare);
1678 containerEl.addEventListener('mousedown', mousedownSparePiece);
1680 // mouse enter / leave square
1681 boardEl.addEventListener('mouseenter', mouseenterSquare);
1682 boardEl.addEventListener('mouseleave', mouseleaveSquare);
1684 window.addEventListener('mousemove', mousemoveWindow);
1685 window.addEventListener('mouseup', mouseupWindow);
1687 // touch drag pieces
1688 if (isTouchDevice() === true) {
1689 boardEl.addEventListener('touchstart', touchstartSquare);
1690 containerEl.addEventListener('touchstart', touchstartSparePiece);
1691 window.addEventListener('touchmove', touchmoveWindow);
1692 window.addEventListener('touchend', touchendWindow);
1696 function initDom() {
1697 // build board and save it in memory
1698 containerEl.innerHTML = buildBoardContainer();
1699 boardEl = containerEl.querySelector('.' + CSS.board);
1701 if (cfg.sparePieces === true) {
1702 sparePiecesTopEl = containerEl.querySelector('.' + CSS.sparePiecesTop);
1703 sparePiecesBottomEl = containerEl.querySelector('.' + CSS.sparePiecesBottom);
1706 // create the drag piece
1707 var draggedPieceId = createId();
1708 document.body.append(buildPiece('wP', true, draggedPieceId));
1709 draggedPieceEl = document.getElementById(draggedPieceId);
1711 // get the border size
1712 BOARD_BORDER_SIZE = parseInt(boardEl.style.borderLeftWidth, 10);
1714 // set the size and draw the board
1719 if (checkDeps() !== true ||
1720 expandConfig() !== true) return;
1722 // create unique IDs for all the elements we will create
1732 // return the widget object
1735 }; // end window.ChessBoard
1737 // expose util functions
1738 window.ChessBoard.fenToObj = fenToObj;
1739 window.ChessBoard.objToFen = objToFen;
1741 })(); // end anonymous wrapper