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 ANIMATION_HAPPENING = false,
247 BOARD_BORDER_SIZE = 2,
248 CURRENT_ORIENTATION = 'white',
249 CURRENT_POSITION = {},
252 DRAGGED_PIECE_LOCATION,
253 DRAGGED_PIECE_SOURCE,
254 DRAGGING_A_PIECE = false,
255 SPARE_PIECE_ELS_IDS = {},
259 //------------------------------------------------------------------------------
261 //------------------------------------------------------------------------------
263 // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
264 function createId() {
265 return 'xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx'.replace(/x/g, function(c) {
266 var r = Math.random() * 16 | 0;
267 return r.toString(16);
271 function deepCopy(thing) {
272 return JSON.parse(JSON.stringify(thing));
275 function parseSemVer(version) {
276 var tmp = version.split('.');
278 major: parseInt(tmp[0], 10),
279 minor: parseInt(tmp[1], 10),
280 patch: parseInt(tmp[2], 10)
284 // returns true if version is >= minimum
285 function compareSemVer(version, minimum) {
286 version = parseSemVer(version);
287 minimum = parseSemVer(minimum);
289 var versionNum = (version.major * 10000 * 10000) +
290 (version.minor * 10000) + version.patch;
291 var minimumNum = (minimum.major * 10000 * 10000) +
292 (minimum.minor * 10000) + minimum.patch;
294 return (versionNum >= minimumNum);
297 //------------------------------------------------------------------------------
298 // Validation / Errors
299 //------------------------------------------------------------------------------
302 * @param {!number} code
303 * @param {!string} msg
304 * @param {Object=} obj
306 function error(code, msg, obj) {
307 // do nothing if showErrors is not set
308 if (cfg.hasOwnProperty('showErrors') !== true ||
309 cfg.showErrors === false) {
313 var errorText = 'ChessBoard Error ' + code + ': ' + msg;
316 if (cfg.showErrors === 'console' &&
317 typeof console === 'object' &&
318 typeof console.log === 'function') {
319 console.log(errorText);
320 if (arguments.length >= 2) {
327 if (cfg.showErrors === 'alert') {
329 errorText += '\n\n' + JSON.stringify(obj);
331 window.alert(errorText);
336 if (typeof cfg.showErrors === 'function') {
337 cfg.showErrors(code, msg, obj);
341 // check dependencies
342 function checkDeps() {
343 // if containerId is a string, it must be the ID of a DOM node
344 if (typeof containerElOrId === 'string') {
346 if (containerElOrId === '') {
347 window.alert('ChessBoard Error 1001: ' +
348 'The first argument to ChessBoard() cannot be an empty string.' +
353 // make sure the container element exists in the DOM
354 var el = document.getElementById(containerElOrId);
356 window.alert('ChessBoard Error 1002: Element with id "' +
357 containerElOrId + '" does not exist in the DOM.' +
362 // set the containerEl
366 // else it must be a DOM node
368 containerEl = containerElOrId;
374 function validAnimationSpeed(speed) {
375 if (speed === 'fast' || speed === 'slow') {
379 if ((parseInt(speed, 10) + '') !== (speed + '')) {
386 // validate config / set default options
387 function expandConfig() {
388 if (typeof cfg === 'string' || validPositionObject(cfg) === true) {
394 // default for orientation is white
395 if (cfg.orientation !== 'black') {
396 cfg.orientation = 'white';
398 CURRENT_ORIENTATION = cfg.orientation;
400 // default for showNotation is true
401 if (cfg.showNotation !== false) {
402 cfg.showNotation = true;
405 // default for draggable is false
406 if (cfg.draggable !== true) {
407 cfg.draggable = false;
410 // default for dropOffBoard is 'snapback'
411 if (cfg.dropOffBoard !== 'trash') {
412 cfg.dropOffBoard = 'snapback';
415 // default for sparePieces is false
416 if (cfg.sparePieces !== true) {
417 cfg.sparePieces = false;
420 // draggable must be true if sparePieces is enabled
421 if (cfg.sparePieces === true) {
422 cfg.draggable = true;
425 // default piece theme is wikipedia
426 if (cfg.hasOwnProperty('pieceTheme') !== true ||
427 (typeof cfg.pieceTheme !== 'string' &&
428 typeof cfg.pieceTheme !== 'function')) {
429 cfg.pieceTheme = 'img/chesspieces/wikipedia/{piece}.png';
433 if (cfg.hasOwnProperty('appearSpeed') !== true ||
434 validAnimationSpeed(cfg.appearSpeed) !== true) {
435 cfg.appearSpeed = 200;
437 if (cfg.hasOwnProperty('moveSpeed') !== true ||
438 validAnimationSpeed(cfg.moveSpeed) !== true) {
441 if (cfg.hasOwnProperty('snapbackSpeed') !== true ||
442 validAnimationSpeed(cfg.snapbackSpeed) !== true) {
443 cfg.snapbackSpeed = 50;
445 if (cfg.hasOwnProperty('snapSpeed') !== true ||
446 validAnimationSpeed(cfg.snapSpeed) !== true) {
449 if (cfg.hasOwnProperty('trashSpeed') !== true ||
450 validAnimationSpeed(cfg.trashSpeed) !== true) {
451 cfg.trashSpeed = 100;
454 // make sure position is valid
455 if (cfg.hasOwnProperty('position') === true) {
456 if (cfg.position === 'start') {
457 CURRENT_POSITION = deepCopy(START_POSITION);
460 else if (validFen(cfg.position) === true) {
461 CURRENT_POSITION = fenToObj(cfg.position);
464 else if (validPositionObject(cfg.position) === true) {
465 CURRENT_POSITION = deepCopy(cfg.position);
469 error(7263, 'Invalid value passed to config.position.', cfg.position);
476 //------------------------------------------------------------------------------
478 //------------------------------------------------------------------------------
480 // calculates square size based on the width of the container
481 // got a little CSS black magic here, so let me explain:
482 // get the width of the container element (could be anything), reduce by 1 for
483 // fudge factor, and then keep reducing until we find an exact mod 8 for
485 function calculateSquareSize() {
486 var containerWidth = parseInt(getComputedStyle(containerEl).width, 10);
488 // defensive, prevent infinite loop
489 if (! containerWidth || containerWidth <= 0) {
494 var boardWidth = containerWidth - 1;
496 while (boardWidth % 8 !== 0 && boardWidth > 0) {
500 return (boardWidth / 8);
503 // create random IDs for elements
504 function createElIds() {
505 // squares on the board
506 for (var i = 0; i < COLUMNS.length; i++) {
507 for (var j = 1; j <= 8; j++) {
508 var square = COLUMNS[i] + j;
509 SQUARE_ELS_IDS[square] = square + '-' + createId();
514 var pieces = 'KQRBNP'.split('');
515 for (var i = 0; i < pieces.length; i++) {
516 var whitePiece = 'w' + pieces[i];
517 var blackPiece = 'b' + pieces[i];
518 SPARE_PIECE_ELS_IDS[whitePiece] = whitePiece + '-' + createId();
519 SPARE_PIECE_ELS_IDS[blackPiece] = blackPiece + '-' + createId();
523 //------------------------------------------------------------------------------
525 //------------------------------------------------------------------------------
527 function buildBoardContainer() {
528 var html = '<div class="' + CSS.chessboard + '">';
530 if (cfg.sparePieces === true) {
531 html += '<div class="' + CSS.sparePieces + ' ' +
532 CSS.sparePiecesTop + '"></div>';
535 html += '<div class="' + CSS.board + '"></div>';
537 if (cfg.sparePieces === true) {
538 html += '<div class="' + CSS.sparePieces + ' ' +
539 CSS.sparePiecesBottom + '"></div>';
548 var buildSquare = function(color, size, id) {
549 var html = '<div class="' + CSS.square + ' ' + CSSColor[color] + '" ' +
550 'style="width: ' + size + 'px; height: ' + size + 'px" ' +
553 if (cfg.showNotation === true) {
563 function buildBoard(orientation) {
564 if (orientation !== 'black') {
565 orientation = 'white';
570 // algebraic notation / orientation
571 var alpha = deepCopy(COLUMNS);
573 if (orientation === 'black') {
578 var squareColor = 'white';
579 for (var i = 0; i < 8; i++) {
580 html += '<div class="' + CSS.row + '">';
581 for (var j = 0; j < 8; j++) {
582 var square = alpha[j] + row;
584 html += '<div class="' + CSS.square + ' ' + CSSColor[squareColor] + ' ' +
585 'square-' + square + '" ' +
586 'style="width: ' + SQUARE_SIZE + 'px; height: ' + SQUARE_SIZE + 'px" ' +
587 'id="' + SQUARE_ELS_IDS[square] + '" ' +
588 'data-square="' + square + '">';
590 if (cfg.showNotation === true) {
592 if ((orientation === 'white' && row === 1) ||
593 (orientation === 'black' && row === 8)) {
594 html += '<div class="' + CSS.notation + ' ' + CSS.alpha + '">' +
600 html += '<div class="' + CSS.notation + ' ' + CSS.numeric + '">' +
605 html += '</div>'; // end .square
607 squareColor = (squareColor === 'white' ? 'black' : 'white');
609 html += '<div class="' + CSS.clearfix + '"></div></div>';
611 squareColor = (squareColor === 'white' ? 'black' : 'white');
613 if (orientation === 'white') {
624 function buildPieceImgSrc(piece) {
625 if (typeof cfg.pieceTheme === 'function') {
626 return cfg.pieceTheme(piece);
629 if (typeof cfg.pieceTheme === 'string') {
630 return cfg.pieceTheme.replace(/{piece}/g, piece);
633 // NOTE: this should never happen
634 error(8272, 'Unable to build image source for cfg.pieceTheme.');
639 * @param {!string} piece
640 * @param {boolean=} hidden
641 * @param {!string=} id
643 function buildPiece(piece, hidden, id) {
644 let img = document.createElement('img');
645 img.src = buildPieceImgSrc(piece);
646 if (id && typeof id === 'string') {
647 img.setAttribute('id', id);
649 img.setAttribute('alt', '');
650 img.classList.add(CSS.piece);
651 img.setAttribute('data-piece', piece);
652 img.style.width = SQUARE_SIZE + 'px';
653 img.style.height = SQUARE_SIZE + 'px';
654 if (hidden === true) {
655 img.style.display = 'none';
660 function buildSparePieces(color) {
661 var pieces = ['wK', 'wQ', 'wR', 'wB', 'wN', 'wP'];
662 if (color === 'black') {
663 pieces = ['bK', 'bQ', 'bR', 'bB', 'bN', 'bP'];
667 for (var i = 0; i < pieces.length; i++) {
668 html += buildPiece(pieces[i], false, SPARE_PIECE_ELS_IDS[pieces[i]]);
674 //------------------------------------------------------------------------------
676 //------------------------------------------------------------------------------
678 function offset(el) { // From https://youmightnotneedjquery.com/.
679 let box = el.getBoundingClientRect();
680 let docElem = document.documentElement;
682 top: box.top + window.pageYOffset - docElem.clientTop,
683 left: box.left + window.pageXOffset - docElem.clientLeft
687 function animateSquareToSquare(src, dest, piece, completeFn) {
688 // get information about the source and destination squares
689 var srcSquareEl = document.getElementById(SQUARE_ELS_IDS[src]);
690 var srcSquarePosition = offset(srcSquareEl);
691 var destSquareEl = document.getElementById(SQUARE_ELS_IDS[dest]);
692 var destSquarePosition = offset(destSquareEl);
694 // create the animated piece and absolutely position it
695 // over the source square
696 var animatedPieceId = createId();
697 document.body.append(buildPiece(piece, true, animatedPieceId));
698 var animatedPieceEl = document.getElementById(animatedPieceId);
699 animatedPieceEl.style.display = null;
700 animatedPieceEl.style.position = 'absolute';
701 animatedPieceEl.style.top = srcSquarePosition.top + 'px';
702 animatedPieceEl.style.left = srcSquarePosition.left + 'px';
704 // remove original piece(s) from source square
705 // TODO: multiple pieces should never really happen, but it will if we are moving
706 // while another animation still isn't done
707 srcSquareEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
710 var complete = function() {
711 // add the "real" piece to the destination square
712 destSquareEl.append(buildPiece(piece));
714 // remove the animated piece
715 animatedPieceEl.remove();
717 // run complete function
718 if (typeof completeFn === 'function') {
723 // animate the piece to the destination square
724 animatedPieceEl.addEventListener('transitionend', complete, {once: true});
725 requestAnimationFrame(() => {
726 animatedPieceEl.style.transitionProperty = 'top, left';
727 animatedPieceEl.style.transitionDuration = cfg.moveSpeed + 'ms';
728 animatedPieceEl.style.top = destSquarePosition.top + 'px';
729 animatedPieceEl.style.left = destSquarePosition.left + 'px';
733 function animateSparePieceToSquare(piece, dest, completeFn) {
734 var srcOffset = offset(document.getelementById(SPARE_PIECE_ELS_IDS[piece]));
735 var destSquareEl = document.getElementById(SQUARE_ELS_IDS[dest]);
736 var destOffset = offset(destSquareEl);
738 // create the animate piece
739 var pieceId = createId();
740 document.body.append(buildPiece(piece, true, pieceId));
741 var animatedPieceEl = document.getElementById(pieceId);
742 animatedPieceEl.style.display = '';
743 animatedPieceEl.style.position = 'absolute';
744 animatedPieceEl.style.left = srcOffset.left;
745 animatedPieceEl.style.top = srcOffset.top;
748 var complete = function() {
749 // add the "real" piece to the destination square
750 destSquareEl.querySelector('.' + CSS.piece).remove();
751 destSquareEl.append(buildPiece(piece));
753 // remove the animated piece
754 animatedPieceEl.remove();
756 // run complete function
757 if (typeof completeFn === 'function') {
762 // animate the piece to the destination square
763 // FIXME: support this for non-jquery
765 duration: cfg.moveSpeed,
768 //$(animatedPieceEl).animate(destOffset, opts);
771 function fadeIn(pieces, onFinish) {
772 pieces.forEach((piece) => {
773 piece.style.opacity = 0;
774 piece.style.display = null;
775 piece.addEventListener('transitionend', onFinish, {once: true});
777 requestAnimationFrame(() => {
778 pieces.forEach((piece) => {
779 piece.style.transitionProperty = 'opacity';
780 piece.style.transitionDuration = cfg.appearSpeed + 'ms';
781 piece.style.opacity = 1;
786 function fadeOut(pieces, onFinish) {
787 pieces.forEach((piece) => {
788 piece.style.opacity = 1;
789 piece.style.display = null;
790 piece.addEventListener('transitionend', onFinish, {once: true});
792 requestAnimationFrame(() => {
793 pieces.forEach((piece) => {
794 piece.style.transitionProperty = 'opacity';
795 piece.style.transitionDuration = cfg.trashSpeed + 'ms';
796 piece.style.opacity = 0;
801 // execute an array of animations
802 function doAnimations(a, oldPos, newPos) {
803 ANIMATION_HAPPENING = true;
806 function onFinish(e) {
808 e.target.transitionProperty = null;
813 // exit if all the animations aren't finished
814 if (numFinished !== a.length) return;
816 drawPositionInstant();
817 ANIMATION_HAPPENING = false;
819 // run their onMoveEnd function
820 if (cfg.hasOwnProperty('onMoveEnd') === true &&
821 typeof cfg.onMoveEnd === 'function') {
822 cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
826 requestAnimationFrame(() => { // Firefox workaround.
827 let fadeout_pieces = [];
828 let fadein_pieces = [];
830 for (var i = 0; i < a.length; i++) {
832 if (a[i].type === 'clear') {
833 document.getElementById(SQUARE_ELS_IDS[a[i].square]).querySelectorAll('.' + CSS.piece).forEach(
834 (piece) => fadeout_pieces.push(piece)
838 // add a piece (no spare pieces)
839 if (a[i].type === 'add' && cfg.sparePieces !== true) {
840 let square = document.getElementById(SQUARE_ELS_IDS[a[i].square]);
841 square.append(buildPiece(a[i].piece, true));
842 let piece = square.querySelector('.' + CSS.piece);
843 fadein_pieces.push(piece);
846 // add a piece from a spare piece
847 if (a[i].type === 'add' && cfg.sparePieces === true) {
848 animateSparePieceToSquare(a[i].piece, a[i].square, onFinish);
852 if (a[i].type === 'move') {
853 animateSquareToSquare(a[i].source, a[i].destination, a[i].piece,
858 // TODO: Batch moves as well, not just fade in/out.
859 // (We batch them because requestAnimationFrame seemingly costs real time.)
860 if (fadeout_pieces.length > 0) {
861 fadeOut(fadeout_pieces, onFinish);
863 if (fadein_pieces.length > 0) {
864 fadeIn(fadein_pieces, onFinish);
869 // returns the distance between two squares
870 function squareDistance(s1, s2) {
872 var s1x = COLUMNS.indexOf(s1[0]) + 1;
873 var s1y = parseInt(s1[1], 10);
876 var s2x = COLUMNS.indexOf(s2[0]) + 1;
877 var s2y = parseInt(s2[1], 10);
879 var xDelta = Math.abs(s1x - s2x);
880 var yDelta = Math.abs(s1y - s2y);
882 if (xDelta >= yDelta) return xDelta;
886 // returns the square of the closest instance of piece
887 // returns false if no instance of piece is found in position
888 function findClosestPiece(position, piece, square) {
889 let best_square = false;
891 for (var i = 0; i < COLUMNS.length; i++) {
892 for (var j = 1; j <= 8; j++) {
893 let other_square = COLUMNS[i] + j;
895 if (position[other_square] === piece && square != other_square) {
896 let dist = squareDistance(square, other_square);
897 if (dist < best_dist) {
898 best_square = other_square;
908 // calculate an array of animations that need to happen in order to get
910 function calculateAnimations(pos1, pos2) {
911 // make copies of both
912 pos1 = deepCopy(pos1);
913 pos2 = deepCopy(pos2);
916 var squaresMovedTo = {};
918 // remove pieces that are the same in both positions
919 for (var i in pos2) {
920 if (pos2.hasOwnProperty(i) !== true) continue;
922 if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
928 // find all the "move" animations
929 for (var i in pos2) {
930 if (pos2.hasOwnProperty(i) !== true) continue;
932 var closestPiece = findClosestPiece(pos1, pos2[i], i);
933 if (closestPiece !== false) {
936 source: closestPiece,
941 delete pos1[closestPiece];
943 squaresMovedTo[i] = true;
947 // add pieces to pos2
948 for (var i in pos2) {
949 if (pos2.hasOwnProperty(i) !== true) continue;
960 // clear pieces from pos1
961 for (var i in pos1) {
962 if (pos1.hasOwnProperty(i) !== true) continue;
964 // do not clear a piece if it is on a square that is the result
965 // of a "move", ie: a piece capture
966 if (squaresMovedTo.hasOwnProperty(i) === true) continue;
980 //------------------------------------------------------------------------------
982 //------------------------------------------------------------------------------
984 function drawPositionInstant() {
986 boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
989 for (var i in CURRENT_POSITION) {
990 if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue;
992 document.getElementById(SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i]));
996 function drawBoard() {
997 boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
998 drawPositionInstant();
1000 if (cfg.sparePieces === true) {
1001 if (CURRENT_ORIENTATION === 'white') {
1002 sparePiecesTopEl.innerHTML = buildSparePieces('black');
1003 sparePiecesBottomEl.innerHTML = buildSparePieces('white');
1006 sparePiecesTopEl.innerHTML = buildSparePieces('white');
1007 sparePiecesBottomEl.innerHTML = buildSparePieces('black');
1012 // given a position and a set of moves, return a new position
1013 // with the moves executed
1014 function calculatePositionFromMoves(position, moves) {
1015 position = deepCopy(position);
1017 for (var i in moves) {
1018 if (moves.hasOwnProperty(i) !== true) continue;
1020 // skip the move if the position doesn't have a piece on the source square
1021 if (position.hasOwnProperty(i) !== true) continue;
1023 var piece = position[i];
1025 position[moves[i]] = piece;
1031 function setCurrentPosition(position) {
1032 var oldPos = deepCopy(CURRENT_POSITION);
1033 var newPos = deepCopy(position);
1034 var oldFen = objToFen(oldPos);
1035 var newFen = objToFen(newPos);
1037 // do nothing if no change in position
1038 if (oldFen === newFen) return;
1040 // run their onChange function
1041 if (cfg.hasOwnProperty('onChange') === true &&
1042 typeof cfg.onChange === 'function') {
1043 cfg.onChange(oldPos, newPos);
1047 CURRENT_POSITION = position;
1050 function isXYOnSquare(x, y) {
1051 for (var i in SQUARE_ELS_OFFSETS) {
1052 if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue;
1054 var s = SQUARE_ELS_OFFSETS[i];
1055 if (x >= s.left && x < s.left + SQUARE_SIZE &&
1056 y >= s.top && y < s.top + SQUARE_SIZE) {
1064 // records the XY coords of every square into memory
1065 function captureSquareOffsets() {
1066 SQUARE_ELS_OFFSETS = {};
1068 for (var i in SQUARE_ELS_IDS) {
1069 if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue;
1071 SQUARE_ELS_OFFSETS[i] = offset(document.getElementById(SQUARE_ELS_IDS[i]));
1075 function removeSquareHighlights() {
1076 boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
1077 piece.classList.remove(CSS.highlight1);
1078 piece.classList.remove(CSS.highlight2);
1082 function snapbackDraggedPiece() {
1083 // there is no "snapback" for spare pieces
1084 if (DRAGGED_PIECE_SOURCE === 'spare') {
1085 trashDraggedPiece();
1089 removeSquareHighlights();
1091 // animation complete
1092 function complete() {
1093 drawPositionInstant();
1094 draggedPieceEl.style.display = 'none';
1096 // run their onSnapbackEnd function
1097 if (cfg.hasOwnProperty('onSnapbackEnd') === true &&
1098 typeof cfg.onSnapbackEnd === 'function') {
1099 cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
1100 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1104 // get source square position
1105 var sourceSquarePosition =
1106 offset(document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]));
1108 // animate the piece to the target square
1109 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1110 requestAnimationFrame(() => {
1111 draggedPieceEl.style.transitionProperty = 'top, left';
1112 draggedPieceEl.style.transitionDuration = cfg.snapbackSpeed + 'ms';
1113 draggedPieceEl.style.top = sourceSquarePosition.top + 'px';
1114 draggedPieceEl.style.left = sourceSquarePosition.left + 'px';
1118 DRAGGING_A_PIECE = false;
1121 function trashDraggedPiece() {
1122 removeSquareHighlights();
1124 // remove the source piece
1125 var newPosition = deepCopy(CURRENT_POSITION);
1126 delete newPosition[DRAGGED_PIECE_SOURCE];
1127 setCurrentPosition(newPosition);
1129 // redraw the position
1130 drawPositionInstant();
1132 // hide the dragged piece
1133 // FIXME: support this for non-jquery
1134 //$(draggedPieceEl).fadeOut(cfg.trashSpeed);
1137 DRAGGING_A_PIECE = false;
1140 function dropDraggedPieceOnSquare(square) {
1141 removeSquareHighlights();
1144 var newPosition = deepCopy(CURRENT_POSITION);
1145 delete newPosition[DRAGGED_PIECE_SOURCE];
1146 newPosition[square] = DRAGGED_PIECE;
1147 setCurrentPosition(newPosition);
1149 // get target square information
1150 var targetSquarePosition = offset(document.getElementById(SQUARE_ELS_IDS[square]));
1152 // animation complete
1153 var complete = function() {
1154 drawPositionInstant();
1155 draggedPieceEl.style.display = 'none';
1157 // execute their onSnapEnd function
1158 if (cfg.hasOwnProperty('onSnapEnd') === true &&
1159 typeof cfg.onSnapEnd === 'function') {
1160 requestAnimationFrame(() => { // HACK: so that we don't add event handlers from the callback...
1161 cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
1166 // snap the piece to the target square
1167 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1168 requestAnimationFrame(() => {
1169 draggedPieceEl.style.transitionProperty = 'top, left';
1170 draggedPieceEl.style.transitionDuration = cfg.snapSpeed + 'ms';
1171 draggedPieceEl.style.top = targetSquarePosition.top + 'px';
1172 draggedPieceEl.style.left = targetSquarePosition.left + 'px';
1176 DRAGGING_A_PIECE = false;
1179 function beginDraggingPiece(source, piece, x, y) {
1180 // run their custom onDragStart function
1181 // their custom onDragStart function can cancel drag start
1182 if (typeof cfg.onDragStart === 'function' &&
1183 cfg.onDragStart(source, piece,
1184 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
1189 DRAGGING_A_PIECE = true;
1190 DRAGGED_PIECE = piece;
1191 DRAGGED_PIECE_SOURCE = source;
1193 // if the piece came from spare pieces, location is offboard
1194 if (source === 'spare') {
1195 DRAGGED_PIECE_LOCATION = 'offboard';
1198 DRAGGED_PIECE_LOCATION = source;
1201 // capture the x, y coords of all squares in memory
1202 captureSquareOffsets();
1204 // create the dragged piece
1205 draggedPieceEl.setAttribute('src', buildPieceImgSrc(piece));
1206 draggedPieceEl.style.display = null;
1207 draggedPieceEl.style.position = 'absolute';
1208 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1209 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1211 if (source !== 'spare') {
1212 // highlight the source square and hide the piece
1213 let square = document.getElementById(SQUARE_ELS_IDS[source]);
1214 square.classList.add(CSS.highlight1);
1215 square.querySelector('.' + CSS.piece).style.display = 'none';
1219 function updateDraggedPiece(x, y) {
1220 // put the dragged piece over the mouse cursor
1221 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1222 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1225 var location = isXYOnSquare(x, y);
1227 // do nothing if the location has not changed
1228 if (location === DRAGGED_PIECE_LOCATION) return;
1230 // remove highlight from previous square
1231 if (validSquare(DRAGGED_PIECE_LOCATION) === true) {
1232 document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION])
1233 .classList.remove(CSS.highlight2);
1236 // add highlight to new square
1237 if (validSquare(location) === true) {
1238 document.getElementById(SQUARE_ELS_IDS[location]).classList.add(CSS.highlight2);
1242 if (typeof cfg.onDragMove === 'function') {
1243 cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1244 DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1245 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1249 DRAGGED_PIECE_LOCATION = location;
1252 function stopDraggedPiece(location) {
1253 // determine what the action should be
1254 var action = 'drop';
1255 if (location === 'offboard' && cfg.dropOffBoard === 'snapback') {
1256 action = 'snapback';
1258 if (location === 'offboard' && cfg.dropOffBoard === 'trash') {
1262 // run their onDrop function, which can potentially change the drop action
1263 if (cfg.hasOwnProperty('onDrop') === true &&
1264 typeof cfg.onDrop === 'function') {
1265 var newPosition = deepCopy(CURRENT_POSITION);
1267 // source piece is a spare piece and position is off the board
1268 //if (DRAGGED_PIECE_SOURCE === 'spare' && location === 'offboard') {...}
1269 // position has not changed; do nothing
1271 // source piece is a spare piece and position is on the board
1272 if (DRAGGED_PIECE_SOURCE === 'spare' && validSquare(location) === true) {
1273 // add the piece to the board
1274 newPosition[location] = DRAGGED_PIECE;
1277 // source piece was on the board and position is off the board
1278 if (validSquare(DRAGGED_PIECE_SOURCE) === true && location === 'offboard') {
1279 // remove the piece from the board
1280 delete newPosition[DRAGGED_PIECE_SOURCE];
1283 // source piece was on the board and position is on the board
1284 if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1285 validSquare(location) === true) {
1287 delete newPosition[DRAGGED_PIECE_SOURCE];
1288 newPosition[location] = DRAGGED_PIECE;
1291 var oldPosition = deepCopy(CURRENT_POSITION);
1293 var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE,
1294 newPosition, oldPosition, CURRENT_ORIENTATION);
1295 if (result === 'snapback' || result === 'trash') {
1301 if (action === 'snapback') {
1302 snapbackDraggedPiece();
1304 else if (action === 'trash') {
1305 trashDraggedPiece();
1307 else if (action === 'drop') {
1308 dropDraggedPieceOnSquare(location);
1312 //------------------------------------------------------------------------------
1314 //------------------------------------------------------------------------------
1317 widget.clear = function(useAnimation) {
1318 widget.position({}, useAnimation);
1322 // get or set config properties
1323 // TODO: write this, GitHub Issue #1
1324 widget.config = function(arg1, arg2) {
1325 // get the current config
1326 if (arguments.length === 0) {
1327 return deepCopy(cfg);
1332 // remove the widget from the page
1333 widget.destroy = function() {
1335 containerEl.innerHTML = '';
1336 draggedPieceEl.remove();
1339 // shorthand method to get the current FEN
1340 widget.fen = function() {
1341 return widget.position('fen');
1345 widget.flip = function() {
1346 widget.orientation('flip');
1350 // TODO: write this, GitHub Issue #5
1351 widget.highlight = function() {
1357 widget.move = function() {
1358 // no need to throw an error here; just do nothing
1359 if (arguments.length === 0) return;
1361 var useAnimation = true;
1363 // collect the moves into an object
1365 for (var i = 0; i < arguments.length; i++) {
1366 // any "false" to this function means no animations
1367 if (arguments[i] === false) {
1368 useAnimation = false;
1372 // skip invalid arguments
1373 if (validMove(arguments[i]) !== true) {
1374 error(2826, 'Invalid move passed to the move method.', arguments[i]);
1378 var tmp = arguments[i].split('-');
1379 moves[tmp[0]] = tmp[1];
1382 // calculate position from moves
1383 var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1386 widget.position(newPos, useAnimation);
1388 // return the new position object
1392 widget.orientation = function(arg) {
1393 // no arguments, return the current orientation
1394 if (arguments.length === 0) {
1395 return CURRENT_ORIENTATION;
1398 // set to white or black
1399 if (arg === 'white' || arg === 'black') {
1400 CURRENT_ORIENTATION = arg;
1406 if (arg === 'flip') {
1407 CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1412 error(5482, 'Invalid value passed to the orientation method.', arg);
1416 * @param {!string|!Object} position
1417 * @param {boolean=} useAnimation
1419 widget.position = function(position, useAnimation) {
1420 // no arguments, return the current position
1421 if (arguments.length === 0) {
1422 return deepCopy(CURRENT_POSITION);
1425 // get position as FEN
1426 if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1427 return objToFen(CURRENT_POSITION);
1430 // default for useAnimations is true
1431 if (useAnimation !== false) {
1432 useAnimation = true;
1436 if (typeof position === 'string' && position.toLowerCase() === 'start') {
1437 position = deepCopy(START_POSITION);
1440 // convert FEN to position object
1441 if (validFen(position) === true) {
1442 position = fenToObj(position);
1445 // validate position object
1446 if (validPositionObject(position) !== true) {
1447 error(6482, 'Invalid value passed to the position method.', position);
1451 if (useAnimation === true) {
1452 // start the animations
1453 doAnimations(calculateAnimations(CURRENT_POSITION, position),
1454 CURRENT_POSITION, position);
1456 // set the new position
1457 setCurrentPosition(position);
1461 setCurrentPosition(position);
1462 drawPositionInstant();
1466 widget.resize = function() {
1467 // calulate the new square size
1468 SQUARE_SIZE = calculateSquareSize();
1471 boardEl.style.width = (SQUARE_SIZE * 8) + 'px';
1473 // set drag piece size
1474 if (draggedPieceEl !== null) {
1475 draggedPieceEl.style.height = SQUARE_SIZE + 'px';
1476 draggedPieceEl.style.width = SQUARE_SIZE + 'px';
1480 if (cfg.sparePieces === true) {
1481 containerEl.querySelector('.' + CSS.sparePieces)
1482 .style.paddingLeft = (SQUARE_SIZE + BOARD_BORDER_SIZE) + 'px';
1489 // set the starting position
1490 widget.start = function(useAnimation) {
1491 widget.position('start', useAnimation);
1494 //------------------------------------------------------------------------------
1496 //------------------------------------------------------------------------------
1498 function isTouchDevice() {
1499 return ('ontouchstart' in document.documentElement);
1502 function mousedownSquare(e) {
1503 let target = e.target.closest('.' + CSS.square);
1508 // do nothing if we're not draggable
1509 if (cfg.draggable !== true) return;
1511 var square = target.getAttribute('data-square');
1513 // no piece on this square
1514 if (validSquare(square) !== true ||
1515 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1519 beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1522 function touchstartSquare(e) {
1523 let target = e.target.closest('.' + CSS.square);
1528 // do nothing if we're not draggable
1529 if (cfg.draggable !== true) return;
1531 var square = target.getAttribute('data-square');
1533 // no piece on this square
1534 if (validSquare(square) !== true ||
1535 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1539 beginDraggingPiece(square, CURRENT_POSITION[square],
1540 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1543 function mousedownSparePiece(e) {
1544 if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1548 // do nothing if sparePieces is not enabled
1549 if (cfg.sparePieces !== true) return;
1551 var piece = e.target.getAttribute('data-piece');
1553 beginDraggingPiece('spare', piece, e.pageX, e.pageY);
1556 function touchstartSparePiece(e) {
1557 if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1561 // do nothing if sparePieces is not enabled
1562 if (cfg.sparePieces !== true) return;
1564 var piece = e.target.getAttribute('data-piece');
1566 beginDraggingPiece('spare', piece,
1567 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1570 function mousemoveWindow(e) {
1571 // do nothing if we are not dragging a piece
1572 if (DRAGGING_A_PIECE !== true) return;
1574 updateDraggedPiece(e.pageX, e.pageY);
1577 function touchmoveWindow(e) {
1578 // do nothing if we are not dragging a piece
1579 if (DRAGGING_A_PIECE !== true) return;
1581 // prevent screen from scrolling
1584 updateDraggedPiece(e.changedTouches[0].pageX,
1585 e.changedTouches[0].pageY);
1588 function mouseupWindow(e) {
1589 // do nothing if we are not dragging a piece
1590 if (DRAGGING_A_PIECE !== true) return;
1593 var location = isXYOnSquare(e.pageX, e.pageY);
1595 stopDraggedPiece(location);
1598 function touchendWindow(e) {
1599 // do nothing if we are not dragging a piece
1600 if (DRAGGING_A_PIECE !== true) return;
1603 var location = isXYOnSquare(e.changedTouches[0].pageX,
1604 e.changedTouches[0].pageY);
1606 stopDraggedPiece(location);
1609 function mouseenterSquare(e) {
1610 let target = e.target.closest('.' + CSS.square);
1615 // do not fire this event if we are dragging a piece
1616 // NOTE: this should never happen, but it's a safeguard
1617 if (DRAGGING_A_PIECE !== false) return;
1619 if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1620 typeof cfg.onMouseoverSquare !== 'function') return;
1623 var square = target.getAttribute('data-square');
1625 // NOTE: this should never happen; defensive
1626 if (validSquare(square) !== true) return;
1628 // get the piece on this square
1630 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1631 piece = CURRENT_POSITION[square];
1634 // execute their function
1635 cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1636 CURRENT_ORIENTATION);
1639 function mouseleaveSquare(e) {
1640 let target = e.target.closest('.' + CSS.square);
1645 // do not fire this event if we are dragging a piece
1646 // NOTE: this should never happen, but it's a safeguard
1647 if (DRAGGING_A_PIECE !== false) return;
1649 if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1650 typeof cfg.onMouseoutSquare !== 'function') return;
1653 var square = target.getAttribute('data-square');
1655 // NOTE: this should never happen; defensive
1656 if (validSquare(square) !== true) return;
1658 // get the piece on this square
1660 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1661 piece = CURRENT_POSITION[square];
1664 // execute their function
1665 cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1666 CURRENT_ORIENTATION);
1669 //------------------------------------------------------------------------------
1671 //------------------------------------------------------------------------------
1673 function addEvents() {
1674 // prevent browser "image drag"
1675 let stopDefault = (e) => {
1676 if (e.target.matches('.' + CSS.piece)) {
1680 document.body.addEventListener('mousedown', stopDefault);
1681 document.body.addEventListener('mousemove', stopDefault);
1683 // mouse drag pieces
1684 boardEl.addEventListener('mousedown', mousedownSquare);
1685 containerEl.addEventListener('mousedown', mousedownSparePiece);
1687 // mouse enter / leave square
1688 boardEl.addEventListener('mouseenter', mouseenterSquare);
1689 boardEl.addEventListener('mouseleave', mouseleaveSquare);
1691 window.addEventListener('mousemove', mousemoveWindow);
1692 window.addEventListener('mouseup', mouseupWindow);
1694 // touch drag pieces
1695 if (isTouchDevice() === true) {
1696 boardEl.addEventListener('touchstart', touchstartSquare);
1697 containerEl.addEventListener('touchstart', touchstartSparePiece);
1698 window.addEventListener('touchmove', touchmoveWindow);
1699 window.addEventListener('touchend', touchendWindow);
1703 function initDom() {
1704 // build board and save it in memory
1705 containerEl.innerHTML = buildBoardContainer();
1706 boardEl = containerEl.querySelector('.' + CSS.board);
1708 if (cfg.sparePieces === true) {
1709 sparePiecesTopEl = containerEl.querySelector('.' + CSS.sparePiecesTop);
1710 sparePiecesBottomEl = containerEl.querySelector('.' + CSS.sparePiecesBottom);
1713 // create the drag piece
1714 var draggedPieceId = createId();
1715 document.body.append(buildPiece('wP', true, draggedPieceId));
1716 draggedPieceEl = document.getElementById(draggedPieceId);
1718 // get the border size
1719 BOARD_BORDER_SIZE = parseInt(boardEl.style.borderLeftWidth, 10);
1721 // set the size and draw the board
1726 if (checkDeps() !== true ||
1727 expandConfig() !== true) return;
1729 // create unique IDs for all the elements we will create
1739 // return the widget object
1742 }; // end window.ChessBoard
1744 // expose util functions
1745 window.ChessBoard.fenToObj = fenToObj;
1746 window.ChessBoard.objToFen = objToFen;
1748 })(); // end anonymous wrapper