4 * Copyright 2013 Chris Oakman
5 * Released under the MIT license
6 * http://chessboardjs.com/license
11 // start anonymous scope
15 //------------------------------------------------------------------------------
16 // Chess Util Functions
17 //------------------------------------------------------------------------------
18 var COLUMNS = 'abcdefgh'.split('');
20 function validMove(move) {
21 // move should be a string
22 if (typeof move !== 'string') return false;
24 // move should be in the form of "e2-e4", "f6-d5"
25 var tmp = move.split('-');
26 if (tmp.length !== 2) return false;
28 return (validSquare(tmp[0]) === true && validSquare(tmp[1]) === true);
31 function validSquare(square) {
32 if (typeof square !== 'string') return false;
33 return (square.search(/^[a-h][1-8]$/) !== -1);
36 function validPieceCode(code) {
37 if (typeof code !== 'string') return false;
38 return (code.search(/^[bw][KQRNBP]$/) !== -1);
41 // TODO: this whole function could probably be replaced with a single regex
42 function validFen(fen) {
43 if (typeof fen !== 'string') return false;
45 // cut off any move, castling, etc info from the end
46 // we're only interested in position information
47 fen = fen.replace(/ .+$/, '');
49 // FEN should be 8 sections separated by slashes
50 var chunks = fen.split('/');
51 if (chunks.length !== 8) return false;
53 // check the piece sections
54 for (var i = 0; i < 8; i++) {
55 if (chunks[i] === '' ||
56 chunks[i].length > 8 ||
57 chunks[i].search(/[^kqrbnpKQRNBP1-8]/) !== -1) {
65 function validPositionObject(pos) {
66 if (typeof pos !== 'object') return false;
69 if (pos.hasOwnProperty(i) !== true) continue;
71 if (validSquare(i) !== true || validPieceCode(pos[i]) !== true) {
79 // convert FEN piece code to bP, wK, etc
80 function fenToPieceCode(piece) {
82 if (piece.toLowerCase() === piece) {
83 return 'b' + piece.toUpperCase();
87 return 'w' + piece.toUpperCase();
90 // convert bP, wK, etc code to FEN structure
91 function pieceCodeToFen(piece) {
92 var tmp = piece.split('');
96 return tmp[1].toUpperCase();
100 return tmp[1].toLowerCase();
103 // convert FEN string to position object
104 // returns false if the FEN string is invalid
105 function fenToObj(fen) {
106 if (validFen(fen) !== true) {
110 // cut off any move, castling, etc info from the end
111 // we're only interested in position information
112 fen = fen.replace(/ .+$/, '');
114 var rows = fen.split('/');
118 for (var i = 0; i < 8; i++) {
119 var row = rows[i].split('');
122 // loop through each character in the FEN section
123 for (var j = 0; j < row.length; j++) {
124 // number / empty squares
125 if (row[j].search(/[1-8]/) !== -1) {
126 var emptySquares = parseInt(row[j], 10);
127 colIndex += emptySquares;
131 var square = COLUMNS[colIndex] + currentRow;
132 position[square] = fenToPieceCode(row[j]);
143 // position object to FEN string
144 // returns false if the obj is not a valid position object
145 function objToFen(obj) {
146 if (validPositionObject(obj) !== true) {
153 for (var i = 0; i < 8; i++) {
154 for (var j = 0; j < 8; j++) {
155 var square = COLUMNS[j] + currentRow;
158 if (obj.hasOwnProperty(square) === true) {
159 fen += pieceCodeToFen(obj[square]);
175 // squeeze the numbers together
176 // haha, I love this solution...
177 fen = fen.replace(/11111111/g, '8');
178 fen = fen.replace(/1111111/g, '7');
179 fen = fen.replace(/111111/g, '6');
180 fen = fen.replace(/11111/g, '5');
181 fen = fen.replace(/1111/g, '4');
182 fen = fen.replace(/111/g, '3');
183 fen = fen.replace(/11/g, '2');
192 window.ChessBoard = function(containerElOrId, cfg) {
197 //------------------------------------------------------------------------------
199 //------------------------------------------------------------------------------
201 var MINIMUM_JQUERY_VERSION = '1.7.0',
202 START_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR',
203 START_POSITION = fenToObj(START_FEN);
205 // use unique class names to prevent clashing with anything else on the page
206 // and simplify selectors
208 alpha: 'alpha-d2270',
209 board: 'board-b72b1',
210 chessboard: 'chessboard-63f37',
211 clearfix: 'clearfix-7da63',
212 highlight1: 'highlight1-32417',
213 highlight2: 'highlight2-9c5d2',
214 notation: 'notation-322f9',
215 numeric: 'numeric-fc462',
216 piece: 'piece-417db',
218 sparePieces: 'spare-pieces-7492f',
219 sparePiecesBottom: 'spare-pieces-bottom-ae20f',
220 sparePiecesTop: 'spare-pieces-top-4028b',
221 square: 'square-55d63'
224 CSSColor['white'] = 'white-1e1d7';
225 CSSColor['black'] = 'black-3c85d';
227 //------------------------------------------------------------------------------
228 // Module Scope Variables
229 //------------------------------------------------------------------------------
238 // constructor return object
241 //------------------------------------------------------------------------------
243 //------------------------------------------------------------------------------
245 var ANIMATION_HAPPENING = false,
246 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 //------------------------------------------------------------------------------
262 // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
263 function createId() {
264 return 'xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx'.replace(/x/g, function(c) {
265 var r = Math.random() * 16 | 0;
266 return r.toString(16);
270 function deepCopy(thing) {
271 return JSON.parse(JSON.stringify(thing));
274 function parseSemVer(version) {
275 var tmp = version.split('.');
277 major: parseInt(tmp[0], 10),
278 minor: parseInt(tmp[1], 10),
279 patch: parseInt(tmp[2], 10)
283 // returns true if version is >= minimum
284 function compareSemVer(version, minimum) {
285 version = parseSemVer(version);
286 minimum = parseSemVer(minimum);
288 var versionNum = (version.major * 10000 * 10000) +
289 (version.minor * 10000) + version.patch;
290 var minimumNum = (minimum.major * 10000 * 10000) +
291 (minimum.minor * 10000) + minimum.patch;
293 return (versionNum >= minimumNum);
296 //------------------------------------------------------------------------------
297 // Validation / Errors
298 //------------------------------------------------------------------------------
301 * @param {!number} code
302 * @param {!string} msg
303 * @param {Object=} obj
305 function error(code, msg, obj) {
306 // do nothing if showErrors is not set
307 if (cfg.hasOwnProperty('showErrors') !== true ||
308 cfg.showErrors === false) {
312 var errorText = 'ChessBoard Error ' + code + ': ' + msg;
315 if (cfg.showErrors === 'console' &&
316 typeof console === 'object' &&
317 typeof console.log === 'function') {
318 console.log(errorText);
319 if (arguments.length >= 2) {
326 if (cfg.showErrors === 'alert') {
328 errorText += '\n\n' + JSON.stringify(obj);
330 window.alert(errorText);
335 if (typeof cfg.showErrors === 'function') {
336 cfg.showErrors(code, msg, obj);
340 // check dependencies
341 function checkDeps() {
342 // if containerId is a string, it must be the ID of a DOM node
343 if (typeof containerElOrId === 'string') {
345 if (containerElOrId === '') {
346 window.alert('ChessBoard Error 1001: ' +
347 'The first argument to ChessBoard() cannot be an empty string.' +
352 // make sure the container element exists in the DOM
353 var el = document.getElementById(containerElOrId);
355 window.alert('ChessBoard Error 1002: Element with id "' +
356 containerElOrId + '" does not exist in the DOM.' +
361 // set the containerEl
365 // else it must be a DOM node
367 containerEl = containerElOrId;
372 typeof JSON.stringify !== 'function' ||
373 typeof JSON.parse !== 'function') {
374 window.alert('ChessBoard Error 1004: JSON does not exist. ' +
375 'Please include a JSON polyfill.\n\nExiting...');
379 // check for a compatible version of jQuery
380 if (! (typeof window.$ && $.fn && $.fn.jquery &&
381 compareSemVer($.fn.jquery, MINIMUM_JQUERY_VERSION) === true)) {
382 window.alert('ChessBoard Error 1005: Unable to find a valid version ' +
383 'of jQuery. Please include jQuery ' + MINIMUM_JQUERY_VERSION + ' or ' +
384 'higher on the page.\n\nExiting...');
391 function validAnimationSpeed(speed) {
392 if (speed === 'fast' || speed === 'slow') {
396 if ((parseInt(speed, 10) + '') !== (speed + '')) {
403 // validate config / set default options
404 function expandConfig() {
405 if (typeof cfg === 'string' || validPositionObject(cfg) === true) {
411 // default for orientation is white
412 if (cfg.orientation !== 'black') {
413 cfg.orientation = 'white';
415 CURRENT_ORIENTATION = cfg.orientation;
417 // default for showNotation is true
418 if (cfg.showNotation !== false) {
419 cfg.showNotation = true;
422 // default for draggable is false
423 if (cfg.draggable !== true) {
424 cfg.draggable = false;
427 // default for dropOffBoard is 'snapback'
428 if (cfg.dropOffBoard !== 'trash') {
429 cfg.dropOffBoard = 'snapback';
432 // default for sparePieces is false
433 if (cfg.sparePieces !== true) {
434 cfg.sparePieces = false;
437 // draggable must be true if sparePieces is enabled
438 if (cfg.sparePieces === true) {
439 cfg.draggable = true;
442 // default piece theme is wikipedia
443 if (cfg.hasOwnProperty('pieceTheme') !== true ||
444 (typeof cfg.pieceTheme !== 'string' &&
445 typeof cfg.pieceTheme !== 'function')) {
446 cfg.pieceTheme = 'img/chesspieces/wikipedia/{piece}.png';
450 if (cfg.hasOwnProperty('appearSpeed') !== true ||
451 validAnimationSpeed(cfg.appearSpeed) !== true) {
452 cfg.appearSpeed = 200;
454 if (cfg.hasOwnProperty('moveSpeed') !== true ||
455 validAnimationSpeed(cfg.moveSpeed) !== true) {
458 if (cfg.hasOwnProperty('snapbackSpeed') !== true ||
459 validAnimationSpeed(cfg.snapbackSpeed) !== true) {
460 cfg.snapbackSpeed = 50;
462 if (cfg.hasOwnProperty('snapSpeed') !== true ||
463 validAnimationSpeed(cfg.snapSpeed) !== true) {
466 if (cfg.hasOwnProperty('trashSpeed') !== true ||
467 validAnimationSpeed(cfg.trashSpeed) !== true) {
468 cfg.trashSpeed = 100;
471 // make sure position is valid
472 if (cfg.hasOwnProperty('position') === true) {
473 if (cfg.position === 'start') {
474 CURRENT_POSITION = deepCopy(START_POSITION);
477 else if (validFen(cfg.position) === true) {
478 CURRENT_POSITION = fenToObj(cfg.position);
481 else if (validPositionObject(cfg.position) === true) {
482 CURRENT_POSITION = deepCopy(cfg.position);
486 error(7263, 'Invalid value passed to config.position.', cfg.position);
493 //------------------------------------------------------------------------------
495 //------------------------------------------------------------------------------
497 // calculates square size based on the width of the container
498 // got a little CSS black magic here, so let me explain:
499 // get the width of the container element (could be anything), reduce by 1 for
500 // fudge factor, and then keep reducing until we find an exact mod 8 for
502 function calculateSquareSize() {
503 var containerWidth = parseInt(getComputedStyle(containerEl).width, 10);
505 // defensive, prevent infinite loop
506 if (! containerWidth || containerWidth <= 0) {
511 var boardWidth = containerWidth - 1;
513 while (boardWidth % 8 !== 0 && boardWidth > 0) {
517 return (boardWidth / 8);
520 // create random IDs for elements
521 function createElIds() {
522 // squares on the board
523 for (var i = 0; i < COLUMNS.length; i++) {
524 for (var j = 1; j <= 8; j++) {
525 var square = COLUMNS[i] + j;
526 SQUARE_ELS_IDS[square] = square + '-' + createId();
531 var pieces = 'KQRBNP'.split('');
532 for (var i = 0; i < pieces.length; i++) {
533 var whitePiece = 'w' + pieces[i];
534 var blackPiece = 'b' + pieces[i];
535 SPARE_PIECE_ELS_IDS[whitePiece] = whitePiece + '-' + createId();
536 SPARE_PIECE_ELS_IDS[blackPiece] = blackPiece + '-' + createId();
540 //------------------------------------------------------------------------------
542 //------------------------------------------------------------------------------
544 function buildBoardContainer() {
545 var html = '<div class="' + CSS.chessboard + '">';
547 if (cfg.sparePieces === true) {
548 html += '<div class="' + CSS.sparePieces + ' ' +
549 CSS.sparePiecesTop + '"></div>';
552 html += '<div class="' + CSS.board + '"></div>';
554 if (cfg.sparePieces === true) {
555 html += '<div class="' + CSS.sparePieces + ' ' +
556 CSS.sparePiecesBottom + '"></div>';
565 var buildSquare = function(color, size, id) {
566 var html = '<div class="' + CSS.square + ' ' + CSSColor[color] + '" ' +
567 'style="width: ' + size + 'px; height: ' + size + 'px" ' +
570 if (cfg.showNotation === true) {
580 function buildBoard(orientation) {
581 if (orientation !== 'black') {
582 orientation = 'white';
587 // algebraic notation / orientation
588 var alpha = deepCopy(COLUMNS);
590 if (orientation === 'black') {
595 var squareColor = 'white';
596 for (var i = 0; i < 8; i++) {
597 html += '<div class="' + CSS.row + '">';
598 for (var j = 0; j < 8; j++) {
599 var square = alpha[j] + row;
601 html += '<div class="' + CSS.square + ' ' + CSSColor[squareColor] + ' ' +
602 'square-' + square + '" ' +
603 'style="width: ' + SQUARE_SIZE + 'px; height: ' + SQUARE_SIZE + 'px" ' +
604 'id="' + SQUARE_ELS_IDS[square] + '" ' +
605 'data-square="' + square + '">';
607 if (cfg.showNotation === true) {
609 if ((orientation === 'white' && row === 1) ||
610 (orientation === 'black' && row === 8)) {
611 html += '<div class="' + CSS.notation + ' ' + CSS.alpha + '">' +
617 html += '<div class="' + CSS.notation + ' ' + CSS.numeric + '">' +
622 html += '</div>'; // end .square
624 squareColor = (squareColor === 'white' ? 'black' : 'white');
626 html += '<div class="' + CSS.clearfix + '"></div></div>';
628 squareColor = (squareColor === 'white' ? 'black' : 'white');
630 if (orientation === 'white') {
641 function buildPieceImgSrc(piece) {
642 if (typeof cfg.pieceTheme === 'function') {
643 return cfg.pieceTheme(piece);
646 if (typeof cfg.pieceTheme === 'string') {
647 return cfg.pieceTheme.replace(/{piece}/g, piece);
650 // NOTE: this should never happen
651 error(8272, 'Unable to build image source for cfg.pieceTheme.');
656 * @param {!string} piece
657 * @param {boolean=} hidden
658 * @param {!string=} id
660 function buildPiece(piece, hidden, id) {
661 var html = '<img src="' + buildPieceImgSrc(piece) + '" ';
662 if (id && typeof id === 'string') {
663 html += 'id="' + id + '" ';
666 'class="' + CSS.piece + '" ' +
667 'data-piece="' + piece + '" ' +
668 'style="width: ' + SQUARE_SIZE + 'px;' +
669 'height: ' + SQUARE_SIZE + 'px;';
670 if (hidden === true) {
671 html += 'display:none;';
675 let elem = document.createElement('template');
676 elem.innerHTML = html;
680 function buildSparePieces(color) {
681 var pieces = ['wK', 'wQ', 'wR', 'wB', 'wN', 'wP'];
682 if (color === 'black') {
683 pieces = ['bK', 'bQ', 'bR', 'bB', 'bN', 'bP'];
687 for (var i = 0; i < pieces.length; i++) {
688 html += buildPiece(pieces[i], false, SPARE_PIECE_ELS_IDS[pieces[i]]);
694 //------------------------------------------------------------------------------
696 //------------------------------------------------------------------------------
698 function offset(el) { // From https://youmightnotneedjquery.com/.
699 let box = el.getBoundingClientRect();
700 let docElem = document.documentElement;
702 top: box.top + window.pageYOffset - docElem.clientTop,
703 left: box.left + window.pageXOffset - docElem.clientLeft
707 function animateSquareToSquare(src, dest, piece, completeFn) {
708 // get information about the source and destination squares
709 var srcSquareEl = document.getElementById(SQUARE_ELS_IDS[src]);
710 var srcSquarePosition = offset(srcSquareEl);
711 var destSquareEl = document.getElementById(SQUARE_ELS_IDS[dest]);
712 var destSquarePosition = offset(destSquareEl);
714 // create the animated piece and absolutely position it
715 // over the source square
716 var animatedPieceId = createId();
717 document.body.append(buildPiece(piece, true, animatedPieceId));
718 var animatedPieceEl = document.getElementById(animatedPieceId);
719 animatedPieceEl.style.display = null;
720 animatedPieceEl.style.position = 'absolute';
721 animatedPieceEl.style.top = srcSquarePosition.top + 'px';
722 animatedPieceEl.style.left = srcSquarePosition.left + 'px';
724 // remove original piece(s) from source square
725 // TODO: multiple pieces should never really happen, but it will if we are moving
726 // while another animation still isn't done
727 srcSquareEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
730 var complete = function() {
731 // add the "real" piece to the destination square
732 destSquareEl.append(buildPiece(piece));
734 // remove the animated piece
735 animatedPieceEl.remove();
737 // run complete function
738 if (typeof completeFn === 'function') {
743 // animate the piece to the destination square
744 animatedPieceEl.addEventListener('transitionend', complete, {once: true});
745 requestAnimationFrame(() => {
746 animatedPieceEl.style.transitionProperty = 'top left';
747 animatedPieceEl.style.transitionDuration = cfg.moveSpeed + 'ms';
748 animatedPieceEl.style.top = destSquarePosition.top + 'px';
749 animatedPieceEl.style.left = destSquarePosition.left + 'px';
753 function animateSparePieceToSquare(piece, dest, completeFn) {
754 var srcOffset = offset(document.getelementById(SPARE_PIECE_ELS_IDS[piece]));
755 var destSquareEl = document.getElementById(SQUARE_ELS_IDS[dest]);
756 var destOffset = offset(destSquareEl);
758 // create the animate piece
759 var pieceId = createId();
760 document.body.append(buildPiece(piece, true, pieceId));
761 var animatedPieceEl = document.getElementById(pieceId);
762 animatedPieceEl.style.display = '';
763 animatedPieceEl.style.position = 'absolute';
764 animatedPieceEl.style.left = srcOffset.left;
765 animatedPieceEl.style.top = srcOffset.top;
768 var complete = function() {
769 // add the "real" piece to the destination square
770 destSquareEl.querySelector('.' + CSS.piece).remove();
771 destSquareEl.append(buildPiece(piece));
773 // remove the animated piece
774 animatedPieceEl.remove();
776 // run complete function
777 if (typeof completeFn === 'function') {
782 // animate the piece to the destination square
783 // FIXME: support this for non-jquery
785 duration: cfg.moveSpeed,
788 $(animatedPieceEl).animate(destOffset, opts);
791 function fadeIn(piece, onFinish) {
792 piece.style.opacity = 0;
793 piece.style.display = null;
794 piece.addEventListener('transitionend', onFinish, {once: true});
795 requestAnimationFrame(() => {
796 piece.style.transitionProperty = 'opacity';
797 piece.style.transitionDuration = cfg.appearSpeed + 'ms';
798 piece.style.opacity = 1;
802 function fadeOut(piece, onFinish) {
803 piece.style.opacity = 1;
804 piece.style.display = null;
805 piece.addEventListener('transitionend', onFinish, {once: true});
806 requestAnimationFrame(() => {
807 piece.style.transitionProperty = 'opacity';
808 piece.style.transitionDuration = cfg.trashSpeed + 'ms';
809 piece.style.opacity = 0;
813 // execute an array of animations
814 function doAnimations(a, oldPos, newPos) {
815 ANIMATION_HAPPENING = true;
818 function onFinish(e) {
820 e.target.transitionProperty = null;
825 // exit if all the animations aren't finished
826 if (numFinished !== a.length) return;
828 drawPositionInstant();
829 ANIMATION_HAPPENING = false;
831 // run their onMoveEnd function
832 if (cfg.hasOwnProperty('onMoveEnd') === true &&
833 typeof cfg.onMoveEnd === 'function') {
834 cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
838 for (var i = 0; i < a.length; i++) {
840 if (a[i].type === 'clear') {
841 document.getElementById(SQUARE_ELS_IDS[a[i].square]).querySelectorAll('.' + CSS.piece).forEach(
842 (piece) => fadeOut(piece, onFinish)
846 // add a piece (no spare pieces)
847 if (a[i].type === 'add' && cfg.sparePieces !== true) {
848 let square = document.getElementById(SQUARE_ELS_IDS[a[i].square]);
849 square.append(buildPiece(a[i].piece, true));
850 let piece = square.querySelector('.' + CSS.piece);
851 fadeIn(piece, onFinish);
854 // add a piece from a spare piece
855 if (a[i].type === 'add' && cfg.sparePieces === true) {
856 animateSparePieceToSquare(a[i].piece, a[i].square, onFinish);
860 if (a[i].type === 'move') {
861 animateSquareToSquare(a[i].source, a[i].destination, a[i].piece,
867 // returns the distance between two squares
868 function squareDistance(s1, s2) {
870 var s1x = COLUMNS.indexOf(s1[0]) + 1;
871 var s1y = parseInt(s1[1], 10);
874 var s2x = COLUMNS.indexOf(s2[0]) + 1;
875 var s2y = parseInt(s2[1], 10);
877 var xDelta = Math.abs(s1x - s2x);
878 var yDelta = Math.abs(s1y - s2y);
880 if (xDelta >= yDelta) return xDelta;
884 // returns an array of closest squares from square
885 function createRadius(square) {
888 // calculate distance of all squares
889 for (var i = 0; i < 8; i++) {
890 for (var j = 0; j < 8; j++) {
891 var s = COLUMNS[i] + (j + 1);
893 // skip the square we're starting from
894 if (square === s) continue;
898 distance: squareDistance(square, s)
904 squares.sort(function(a, b) {
905 return a.distance - b.distance;
908 // just return the square code
910 for (var i = 0; i < squares.length; i++) {
911 squares2.push(squares[i].square);
917 // returns the square of the closest instance of piece
918 // returns false if no instance of piece is found in position
919 function findClosestPiece(position, piece, square) {
920 // create array of closest squares from square
921 var closestSquares = createRadius(square);
923 // search through the position in order of distance for the piece
924 for (var i = 0; i < closestSquares.length; i++) {
925 var s = closestSquares[i];
927 if (position.hasOwnProperty(s) === true && position[s] === piece) {
935 // calculate an array of animations that need to happen in order to get
937 function calculateAnimations(pos1, pos2) {
938 // make copies of both
939 pos1 = deepCopy(pos1);
940 pos2 = deepCopy(pos2);
943 var squaresMovedTo = {};
945 // remove pieces that are the same in both positions
946 for (var i in pos2) {
947 if (pos2.hasOwnProperty(i) !== true) continue;
949 if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
955 // find all the "move" animations
956 for (var i in pos2) {
957 if (pos2.hasOwnProperty(i) !== true) continue;
959 var closestPiece = findClosestPiece(pos1, pos2[i], i);
960 if (closestPiece !== false) {
963 source: closestPiece,
968 delete pos1[closestPiece];
970 squaresMovedTo[i] = true;
974 // add pieces to pos2
975 for (var i in pos2) {
976 if (pos2.hasOwnProperty(i) !== true) continue;
987 // clear pieces from pos1
988 for (var i in pos1) {
989 if (pos1.hasOwnProperty(i) !== true) continue;
991 // do not clear a piece if it is on a square that is the result
992 // of a "move", ie: a piece capture
993 if (squaresMovedTo.hasOwnProperty(i) === true) continue;
1007 //------------------------------------------------------------------------------
1009 //------------------------------------------------------------------------------
1011 function drawPositionInstant() {
1013 boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
1016 for (var i in CURRENT_POSITION) {
1017 if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue;
1019 document.getElementById(SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i]));
1023 function drawBoard() {
1024 boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
1025 drawPositionInstant();
1027 if (cfg.sparePieces === true) {
1028 if (CURRENT_ORIENTATION === 'white') {
1029 sparePiecesTopEl.innerHTML = buildSparePieces('black');
1030 sparePiecesBottomEl.innerHTML = buildSparePieces('white');
1033 sparePiecesTopEl.innerHTML = buildSparePieces('white');
1034 sparePiecesBottomEl.innerHTML = buildSparePieces('black');
1039 // given a position and a set of moves, return a new position
1040 // with the moves executed
1041 function calculatePositionFromMoves(position, moves) {
1042 position = deepCopy(position);
1044 for (var i in moves) {
1045 if (moves.hasOwnProperty(i) !== true) continue;
1047 // skip the move if the position doesn't have a piece on the source square
1048 if (position.hasOwnProperty(i) !== true) continue;
1050 var piece = position[i];
1052 position[moves[i]] = piece;
1058 function setCurrentPosition(position) {
1059 var oldPos = deepCopy(CURRENT_POSITION);
1060 var newPos = deepCopy(position);
1061 var oldFen = objToFen(oldPos);
1062 var newFen = objToFen(newPos);
1064 // do nothing if no change in position
1065 if (oldFen === newFen) return;
1067 // run their onChange function
1068 if (cfg.hasOwnProperty('onChange') === true &&
1069 typeof cfg.onChange === 'function') {
1070 cfg.onChange(oldPos, newPos);
1074 CURRENT_POSITION = position;
1077 function isXYOnSquare(x, y) {
1078 for (var i in SQUARE_ELS_OFFSETS) {
1079 if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue;
1081 var s = SQUARE_ELS_OFFSETS[i];
1082 if (x >= s.left && x < s.left + SQUARE_SIZE &&
1083 y >= s.top && y < s.top + SQUARE_SIZE) {
1091 // records the XY coords of every square into memory
1092 function captureSquareOffsets() {
1093 SQUARE_ELS_OFFSETS = {};
1095 for (var i in SQUARE_ELS_IDS) {
1096 if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue;
1098 SQUARE_ELS_OFFSETS[i] = offset(document.getElementById(SQUARE_ELS_IDS[i]));
1102 function removeSquareHighlights() {
1103 boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
1104 piece.classList.remove(CSS.highlight1);
1105 piece.classList.remove(CSS.highlight2);
1109 function snapbackDraggedPiece() {
1110 // there is no "snapback" for spare pieces
1111 if (DRAGGED_PIECE_SOURCE === 'spare') {
1112 trashDraggedPiece();
1116 removeSquareHighlights();
1118 // animation complete
1119 function complete() {
1120 drawPositionInstant();
1121 draggedPieceEl.style.display = 'none';
1123 // run their onSnapbackEnd function
1124 if (cfg.hasOwnProperty('onSnapbackEnd') === true &&
1125 typeof cfg.onSnapbackEnd === 'function') {
1126 cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
1127 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1131 // get source square position
1132 var sourceSquarePosition =
1133 offset(document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]));
1135 // animate the piece to the target square
1136 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1137 requestAnimationFrame(() => {
1138 draggedPieceEl.style.transitionProperty = 'top left';
1139 draggedPieceEl.style.transitionDuration = cfg.snapbackSpeed + 'ms';
1140 draggedPieceEl.style.top = sourceSquarePosition.top + 'px';
1141 draggedPieceEl.style.left = sourceSquarePosition.left + 'px';
1145 DRAGGING_A_PIECE = false;
1148 function trashDraggedPiece() {
1149 removeSquareHighlights();
1151 // remove the source piece
1152 var newPosition = deepCopy(CURRENT_POSITION);
1153 delete newPosition[DRAGGED_PIECE_SOURCE];
1154 setCurrentPosition(newPosition);
1156 // redraw the position
1157 drawPositionInstant();
1159 // hide the dragged piece
1160 // FIXME: support this for non-jquery
1161 $(draggedPieceEl).fadeOut(cfg.trashSpeed);
1164 DRAGGING_A_PIECE = false;
1167 function dropDraggedPieceOnSquare(square) {
1168 removeSquareHighlights();
1171 var newPosition = deepCopy(CURRENT_POSITION);
1172 delete newPosition[DRAGGED_PIECE_SOURCE];
1173 newPosition[square] = DRAGGED_PIECE;
1174 setCurrentPosition(newPosition);
1176 // get target square information
1177 var targetSquarePosition = offset(document.getElementById(SQUARE_ELS_IDS[square]));
1179 // animation complete
1180 var complete = function() {
1181 drawPositionInstant();
1182 draggedPieceEl.style.display = 'none';
1184 // execute their onSnapEnd function
1185 if (cfg.hasOwnProperty('onSnapEnd') === true &&
1186 typeof cfg.onSnapEnd === 'function') {
1187 requestAnimationFrame(() => { // HACK: so that we don't add event handlers from the callback...
1188 cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
1193 // snap the piece to the target square
1194 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1195 requestAnimationFrame(() => {
1196 draggedPieceEl.style.transitionProperty = 'top left';
1197 draggedPieceEl.style.transitionDuration = cfg.snapSpeed + 'ms';
1198 draggedPieceEl.style.top = targetSquarePosition.top + 'px';
1199 draggedPieceEl.style.left = targetSquarePosition.left + 'px';
1203 DRAGGING_A_PIECE = false;
1206 function beginDraggingPiece(source, piece, x, y) {
1207 // run their custom onDragStart function
1208 // their custom onDragStart function can cancel drag start
1209 if (typeof cfg.onDragStart === 'function' &&
1210 cfg.onDragStart(source, piece,
1211 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
1216 DRAGGING_A_PIECE = true;
1217 DRAGGED_PIECE = piece;
1218 DRAGGED_PIECE_SOURCE = source;
1220 // if the piece came from spare pieces, location is offboard
1221 if (source === 'spare') {
1222 DRAGGED_PIECE_LOCATION = 'offboard';
1225 DRAGGED_PIECE_LOCATION = source;
1228 // capture the x, y coords of all squares in memory
1229 captureSquareOffsets();
1231 // create the dragged piece
1232 draggedPieceEl.setAttribute('src', buildPieceImgSrc(piece));
1233 draggedPieceEl.style.display = null;
1234 draggedPieceEl.style.position = 'absolute';
1235 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1236 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1238 if (source !== 'spare') {
1239 // highlight the source square and hide the piece
1240 let square = document.getElementById(SQUARE_ELS_IDS[source]);
1241 square.classList.add(CSS.highlight1);
1242 square.querySelector('.' + CSS.piece).style.display = 'none';
1246 function updateDraggedPiece(x, y) {
1247 // put the dragged piece over the mouse cursor
1248 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1249 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1252 var location = isXYOnSquare(x, y);
1254 // do nothing if the location has not changed
1255 if (location === DRAGGED_PIECE_LOCATION) return;
1257 // remove highlight from previous square
1258 if (validSquare(DRAGGED_PIECE_LOCATION) === true) {
1259 document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION])
1260 .classList.remove(CSS.highlight2);
1263 // add highlight to new square
1264 if (validSquare(location) === true) {
1265 document.getElementById(SQUARE_ELS_IDS[location]).classList.add(CSS.highlight2);
1269 if (typeof cfg.onDragMove === 'function') {
1270 cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1271 DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1272 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1276 DRAGGED_PIECE_LOCATION = location;
1279 function stopDraggedPiece(location) {
1280 // determine what the action should be
1281 var action = 'drop';
1282 if (location === 'offboard' && cfg.dropOffBoard === 'snapback') {
1283 action = 'snapback';
1285 if (location === 'offboard' && cfg.dropOffBoard === 'trash') {
1289 // run their onDrop function, which can potentially change the drop action
1290 if (cfg.hasOwnProperty('onDrop') === true &&
1291 typeof cfg.onDrop === 'function') {
1292 var newPosition = deepCopy(CURRENT_POSITION);
1294 // source piece is a spare piece and position is off the board
1295 //if (DRAGGED_PIECE_SOURCE === 'spare' && location === 'offboard') {...}
1296 // position has not changed; do nothing
1298 // source piece is a spare piece and position is on the board
1299 if (DRAGGED_PIECE_SOURCE === 'spare' && validSquare(location) === true) {
1300 // add the piece to the board
1301 newPosition[location] = DRAGGED_PIECE;
1304 // source piece was on the board and position is off the board
1305 if (validSquare(DRAGGED_PIECE_SOURCE) === true && location === 'offboard') {
1306 // remove the piece from the board
1307 delete newPosition[DRAGGED_PIECE_SOURCE];
1310 // source piece was on the board and position is on the board
1311 if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1312 validSquare(location) === true) {
1314 delete newPosition[DRAGGED_PIECE_SOURCE];
1315 newPosition[location] = DRAGGED_PIECE;
1318 var oldPosition = deepCopy(CURRENT_POSITION);
1320 var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE,
1321 newPosition, oldPosition, CURRENT_ORIENTATION);
1322 if (result === 'snapback' || result === 'trash') {
1328 if (action === 'snapback') {
1329 snapbackDraggedPiece();
1331 else if (action === 'trash') {
1332 trashDraggedPiece();
1334 else if (action === 'drop') {
1335 dropDraggedPieceOnSquare(location);
1339 //------------------------------------------------------------------------------
1341 //------------------------------------------------------------------------------
1344 widget.clear = function(useAnimation) {
1345 widget.position({}, useAnimation);
1349 // get or set config properties
1350 // TODO: write this, GitHub Issue #1
1351 widget.config = function(arg1, arg2) {
1352 // get the current config
1353 if (arguments.length === 0) {
1354 return deepCopy(cfg);
1359 // remove the widget from the page
1360 widget.destroy = function() {
1362 containerEl.innerHTML = '';
1363 draggedPieceEl.remove();
1366 // shorthand method to get the current FEN
1367 widget.fen = function() {
1368 return widget.position('fen');
1372 widget.flip = function() {
1373 widget.orientation('flip');
1377 // TODO: write this, GitHub Issue #5
1378 widget.highlight = function() {
1384 widget.move = function() {
1385 // no need to throw an error here; just do nothing
1386 if (arguments.length === 0) return;
1388 var useAnimation = true;
1390 // collect the moves into an object
1392 for (var i = 0; i < arguments.length; i++) {
1393 // any "false" to this function means no animations
1394 if (arguments[i] === false) {
1395 useAnimation = false;
1399 // skip invalid arguments
1400 if (validMove(arguments[i]) !== true) {
1401 error(2826, 'Invalid move passed to the move method.', arguments[i]);
1405 var tmp = arguments[i].split('-');
1406 moves[tmp[0]] = tmp[1];
1409 // calculate position from moves
1410 var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1413 widget.position(newPos, useAnimation);
1415 // return the new position object
1419 widget.orientation = function(arg) {
1420 // no arguments, return the current orientation
1421 if (arguments.length === 0) {
1422 return CURRENT_ORIENTATION;
1425 // set to white or black
1426 if (arg === 'white' || arg === 'black') {
1427 CURRENT_ORIENTATION = arg;
1433 if (arg === 'flip') {
1434 CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1439 error(5482, 'Invalid value passed to the orientation method.', arg);
1443 * @param {!string|!Object} position
1444 * @param {boolean=} useAnimation
1446 widget.position = function(position, useAnimation) {
1447 // no arguments, return the current position
1448 if (arguments.length === 0) {
1449 return deepCopy(CURRENT_POSITION);
1452 // get position as FEN
1453 if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1454 return objToFen(CURRENT_POSITION);
1457 // default for useAnimations is true
1458 if (useAnimation !== false) {
1459 useAnimation = true;
1463 if (typeof position === 'string' && position.toLowerCase() === 'start') {
1464 position = deepCopy(START_POSITION);
1467 // convert FEN to position object
1468 if (validFen(position) === true) {
1469 position = fenToObj(position);
1472 // validate position object
1473 if (validPositionObject(position) !== true) {
1474 error(6482, 'Invalid value passed to the position method.', position);
1478 if (useAnimation === true) {
1479 // start the animations
1480 doAnimations(calculateAnimations(CURRENT_POSITION, position),
1481 CURRENT_POSITION, position);
1483 // set the new position
1484 setCurrentPosition(position);
1488 setCurrentPosition(position);
1489 drawPositionInstant();
1493 widget.resize = function() {
1494 // calulate the new square size
1495 SQUARE_SIZE = calculateSquareSize();
1498 boardEl.style.width = (SQUARE_SIZE * 8) + 'px';
1500 // set drag piece size
1501 if (draggedPieceEl !== null) {
1502 draggedPieceEl.style.height = SQUARE_SIZE + 'px';
1503 draggedPieceEl.style.width = SQUARE_SIZE + 'px';
1507 if (cfg.sparePieces === true) {
1508 containerEl.querySelector('.' + CSS.sparePieces)
1509 .style.paddingLeft = (SQUARE_SIZE + BOARD_BORDER_SIZE) + 'px';
1516 // set the starting position
1517 widget.start = function(useAnimation) {
1518 widget.position('start', useAnimation);
1521 //------------------------------------------------------------------------------
1523 //------------------------------------------------------------------------------
1525 function isTouchDevice() {
1526 return ('ontouchstart' in document.documentElement);
1529 function mousedownSquare(e) {
1530 let target = e.target.closest('.' + CSS.square);
1535 // do nothing if we're not draggable
1536 if (cfg.draggable !== true) return;
1538 var square = target.getAttribute('data-square');
1540 // no piece on this square
1541 if (validSquare(square) !== true ||
1542 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1546 beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1549 function touchstartSquare(e) {
1550 let target = e.target.closest('.' + CSS.square);
1555 // do nothing if we're not draggable
1556 if (cfg.draggable !== true) return;
1558 var square = target.getAttribute('data-square');
1560 // no piece on this square
1561 if (validSquare(square) !== true ||
1562 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1566 e = e.originalEvent;
1567 beginDraggingPiece(square, CURRENT_POSITION[square],
1568 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1571 function mousedownSparePiece(e) {
1572 if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1576 // do nothing if sparePieces is not enabled
1577 if (cfg.sparePieces !== true) return;
1579 var piece = e.target.getAttribute('data-piece');
1581 beginDraggingPiece('spare', piece, e.pageX, e.pageY);
1584 function touchstartSparePiece(e) {
1585 if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1589 // do nothing if sparePieces is not enabled
1590 if (cfg.sparePieces !== true) return;
1592 var piece = e.target.getAttribute('data-piece');
1594 e = e.originalEvent;
1595 beginDraggingPiece('spare', piece,
1596 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1599 function mousemoveWindow(e) {
1600 // do nothing if we are not dragging a piece
1601 if (DRAGGING_A_PIECE !== true) return;
1603 updateDraggedPiece(e.pageX, e.pageY);
1606 function touchmoveWindow(e) {
1607 // do nothing if we are not dragging a piece
1608 if (DRAGGING_A_PIECE !== true) return;
1610 // prevent screen from scrolling
1613 updateDraggedPiece(e.originalEvent.changedTouches[0].pageX,
1614 e.originalEvent.changedTouches[0].pageY);
1617 function mouseupWindow(e) {
1618 // do nothing if we are not dragging a piece
1619 if (DRAGGING_A_PIECE !== true) return;
1622 var location = isXYOnSquare(e.pageX, e.pageY);
1624 stopDraggedPiece(location);
1627 function touchendWindow(e) {
1628 // do nothing if we are not dragging a piece
1629 if (DRAGGING_A_PIECE !== true) return;
1632 var location = isXYOnSquare(e.originalEvent.changedTouches[0].pageX,
1633 e.originalEvent.changedTouches[0].pageY);
1635 stopDraggedPiece(location);
1638 function mouseenterSquare(e) {
1639 let target = e.target.closest('.' + CSS.square);
1644 // do not fire this event if we are dragging a piece
1645 // NOTE: this should never happen, but it's a safeguard
1646 if (DRAGGING_A_PIECE !== false) return;
1648 if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1649 typeof cfg.onMouseoverSquare !== 'function') return;
1652 var square = target.getAttribute('data-square');
1654 // NOTE: this should never happen; defensive
1655 if (validSquare(square) !== true) return;
1657 // get the piece on this square
1659 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1660 piece = CURRENT_POSITION[square];
1663 // execute their function
1664 cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1665 CURRENT_ORIENTATION);
1668 function mouseleaveSquare(e) {
1669 let target = e.target.closest('.' + CSS.square);
1674 // do not fire this event if we are dragging a piece
1675 // NOTE: this should never happen, but it's a safeguard
1676 if (DRAGGING_A_PIECE !== false) return;
1678 if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1679 typeof cfg.onMouseoutSquare !== 'function') return;
1682 var square = target.getAttribute('data-square');
1684 // NOTE: this should never happen; defensive
1685 if (validSquare(square) !== true) return;
1687 // get the piece on this square
1689 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1690 piece = CURRENT_POSITION[square];
1693 // execute their function
1694 cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1695 CURRENT_ORIENTATION);
1698 //------------------------------------------------------------------------------
1700 //------------------------------------------------------------------------------
1702 function addEvents() {
1703 // prevent browser "image drag"
1704 let stopDefault = (e) => {
1705 if (e.target.matches('.' + CSS.piece)) {
1709 document.body.addEventListener('mousedown', stopDefault);
1710 document.body.addEventListener('mousemove', stopDefault);
1712 // mouse drag pieces
1713 boardEl.addEventListener('mousedown', mousedownSquare);
1714 containerEl.addEventListener('mousedown', mousedownSparePiece);
1716 // mouse enter / leave square
1717 boardEl.addEventListener('mouseenter', mouseenterSquare);
1718 boardEl.addEventListener('mouseleave', mouseleaveSquare);
1720 window.addEventListener('mousemove', mousemoveWindow);
1721 window.addEventListener('mouseup', mouseupWindow);
1723 // touch drag pieces
1724 if (isTouchDevice() === true) {
1725 boardEl.addEventListener('touchstart', touchstartSquare);
1726 containerEl.addEventListener('touchstart', touchstartSparePiece);
1727 window.addEventListener('touchmove', touchmoveWindow);
1728 window.addEventListener('touchend', touchendWindow);
1732 function initDom() {
1733 // build board and save it in memory
1734 containerEl.innerHTML = buildBoardContainer();
1735 boardEl = containerEl.querySelector('.' + CSS.board);
1737 if (cfg.sparePieces === true) {
1738 sparePiecesTopEl = containerEl.querySelector('.' + CSS.sparePiecesTop);
1739 sparePiecesBottomEl = containerEl.querySelector('.' + CSS.sparePiecesBottom);
1742 // create the drag piece
1743 var draggedPieceId = createId();
1744 document.body.append(buildPiece('wP', true, draggedPieceId));
1745 draggedPieceEl = document.getElementById(draggedPieceId);
1747 // get the border size
1748 BOARD_BORDER_SIZE = parseInt(boardEl.style.borderLeftWidth, 10);
1750 // set the size and draw the board
1755 if (checkDeps() !== true ||
1756 expandConfig() !== true) return;
1758 // create unique IDs for all the elements we will create
1768 // return the widget object
1771 }; // end window.ChessBoard
1773 // expose util functions
1774 window.ChessBoard.fenToObj = fenToObj;
1775 window.ChessBoard.objToFen = objToFen;
1777 })(); // end anonymous wrapper