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 = '';
720 animatedPieceEl.style.position = 'absolute';
721 animatedPieceEl.style.top = srcSquarePosition.top;
722 animatedPieceEl.style.left = srcSquarePosition.left;
724 // remove original piece from source square
725 srcSquareEl.querySelector('.' + CSS.piece).remove();
728 var complete = function() {
729 // add the "real" piece to the destination square
730 destSquareEl.append(buildPiece(piece));
732 // remove the animated piece
733 animatedPieceEl.remove();
735 // run complete function
736 if (typeof completeFn === 'function') {
741 // animate the piece to the destination square
743 duration: cfg.moveSpeed,
746 $(animatedPieceEl).animate(destSquarePosition, opts);
749 function animateSparePieceToSquare(piece, dest, completeFn) {
750 var srcOffset = offset(document.getelementById(SPARE_PIECE_ELS_IDS[piece]));
751 var destSquareEl = document.getElementById(SQUARE_ELS_IDS[dest]);
752 var destOffset = offset(destSquareEl);
754 // create the animate piece
755 var pieceId = createId();
756 document.body.append(buildPiece(piece, true, pieceId));
757 var animatedPieceEl = document.getElementById(pieceId);
758 animatedPieceEl.style.display = '';
759 animatedPieceEl.style.position = 'absolute';
760 animatedPieceEl.style.left = srcOffset.left;
761 animatedPieceEl.style.top = srcOffset.top;
764 var complete = function() {
765 // add the "real" piece to the destination square
766 destSquareEl.querySelector('.' + CSS.piece).remove();
767 destSquareEl.append(buildPiece(piece));
769 // remove the animated piece
770 animatedPieceEl.remove();
772 // run complete function
773 if (typeof completeFn === 'function') {
778 // animate the piece to the destination square
780 duration: cfg.moveSpeed,
783 $(animatedPieceEl).animate(destOffset, opts);
786 // execute an array of animations
787 function doAnimations(a, oldPos, newPos) {
788 ANIMATION_HAPPENING = true;
791 function onFinish() {
794 // exit if all the animations aren't finished
795 if (numFinished !== a.length) return;
797 drawPositionInstant();
798 ANIMATION_HAPPENING = false;
800 // run their onMoveEnd function
801 if (cfg.hasOwnProperty('onMoveEnd') === true &&
802 typeof cfg.onMoveEnd === 'function') {
803 cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
807 for (var i = 0; i < a.length; i++) {
809 if (a[i].type === 'clear') {
810 $('#' + SQUARE_ELS_IDS[a[i].square] + ' .' + CSS.piece)
811 .fadeOut(cfg.trashSpeed, onFinish);
814 // add a piece (no spare pieces)
815 if (a[i].type === 'add' && cfg.sparePieces !== true) {
816 $('#' + SQUARE_ELS_IDS[a[i].square])
817 .append(buildPiece(a[i].piece, true))
818 .find('.' + CSS.piece)
819 .fadeIn(cfg.appearSpeed, onFinish);
822 // add a piece from a spare piece
823 if (a[i].type === 'add' && cfg.sparePieces === true) {
824 animateSparePieceToSquare(a[i].piece, a[i].square, onFinish);
828 if (a[i].type === 'move') {
829 animateSquareToSquare(a[i].source, a[i].destination, a[i].piece,
835 // returns the distance between two squares
836 function squareDistance(s1, s2) {
838 var s1x = COLUMNS.indexOf(s1[0]) + 1;
839 var s1y = parseInt(s1[1], 10);
842 var s2x = COLUMNS.indexOf(s2[0]) + 1;
843 var s2y = parseInt(s2[1], 10);
845 var xDelta = Math.abs(s1x - s2x);
846 var yDelta = Math.abs(s1y - s2y);
848 if (xDelta >= yDelta) return xDelta;
852 // returns an array of closest squares from square
853 function createRadius(square) {
856 // calculate distance of all squares
857 for (var i = 0; i < 8; i++) {
858 for (var j = 0; j < 8; j++) {
859 var s = COLUMNS[i] + (j + 1);
861 // skip the square we're starting from
862 if (square === s) continue;
866 distance: squareDistance(square, s)
872 squares.sort(function(a, b) {
873 return a.distance - b.distance;
876 // just return the square code
878 for (var i = 0; i < squares.length; i++) {
879 squares2.push(squares[i].square);
885 // returns the square of the closest instance of piece
886 // returns false if no instance of piece is found in position
887 function findClosestPiece(position, piece, square) {
888 // create array of closest squares from square
889 var closestSquares = createRadius(square);
891 // search through the position in order of distance for the piece
892 for (var i = 0; i < closestSquares.length; i++) {
893 var s = closestSquares[i];
895 if (position.hasOwnProperty(s) === true && position[s] === piece) {
903 // calculate an array of animations that need to happen in order to get
905 function calculateAnimations(pos1, pos2) {
906 // make copies of both
907 pos1 = deepCopy(pos1);
908 pos2 = deepCopy(pos2);
911 var squaresMovedTo = {};
913 // remove pieces that are the same in both positions
914 for (var i in pos2) {
915 if (pos2.hasOwnProperty(i) !== true) continue;
917 if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
923 // find all the "move" animations
924 for (var i in pos2) {
925 if (pos2.hasOwnProperty(i) !== true) continue;
927 var closestPiece = findClosestPiece(pos1, pos2[i], i);
928 if (closestPiece !== false) {
931 source: closestPiece,
936 delete pos1[closestPiece];
938 squaresMovedTo[i] = true;
942 // add pieces to pos2
943 for (var i in pos2) {
944 if (pos2.hasOwnProperty(i) !== true) continue;
955 // clear pieces from pos1
956 for (var i in pos1) {
957 if (pos1.hasOwnProperty(i) !== true) continue;
959 // do not clear a piece if it is on a square that is the result
960 // of a "move", ie: a piece capture
961 if (squaresMovedTo.hasOwnProperty(i) === true) continue;
975 //------------------------------------------------------------------------------
977 //------------------------------------------------------------------------------
979 function drawPositionInstant() {
981 boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
984 for (var i in CURRENT_POSITION) {
985 if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue;
987 document.getElementById(SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i]));
991 function drawBoard() {
992 boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
993 drawPositionInstant();
995 if (cfg.sparePieces === true) {
996 if (CURRENT_ORIENTATION === 'white') {
997 sparePiecesTopEl.innerHTML = buildSparePieces('black');
998 sparePiecesBottomEl.innerHTML = buildSparePieces('white');
1001 sparePiecesTopEl.innerHTML = buildSparePieces('white');
1002 sparePiecesBottomEl.innerHTML = buildSparePieces('black');
1007 // given a position and a set of moves, return a new position
1008 // with the moves executed
1009 function calculatePositionFromMoves(position, moves) {
1010 position = deepCopy(position);
1012 for (var i in moves) {
1013 if (moves.hasOwnProperty(i) !== true) continue;
1015 // skip the move if the position doesn't have a piece on the source square
1016 if (position.hasOwnProperty(i) !== true) continue;
1018 var piece = position[i];
1020 position[moves[i]] = piece;
1026 function setCurrentPosition(position) {
1027 var oldPos = deepCopy(CURRENT_POSITION);
1028 var newPos = deepCopy(position);
1029 var oldFen = objToFen(oldPos);
1030 var newFen = objToFen(newPos);
1032 // do nothing if no change in position
1033 if (oldFen === newFen) return;
1035 // run their onChange function
1036 if (cfg.hasOwnProperty('onChange') === true &&
1037 typeof cfg.onChange === 'function') {
1038 cfg.onChange(oldPos, newPos);
1042 CURRENT_POSITION = position;
1045 function isXYOnSquare(x, y) {
1046 for (var i in SQUARE_ELS_OFFSETS) {
1047 if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue;
1049 var s = SQUARE_ELS_OFFSETS[i];
1050 if (x >= s.left && x < s.left + SQUARE_SIZE &&
1051 y >= s.top && y < s.top + SQUARE_SIZE) {
1059 // records the XY coords of every square into memory
1060 function captureSquareOffsets() {
1061 SQUARE_ELS_OFFSETS = {};
1063 for (var i in SQUARE_ELS_IDS) {
1064 if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue;
1066 SQUARE_ELS_OFFSETS[i] = offset(document.getElementById(SQUARE_ELS_IDS[i]));
1070 function removeSquareHighlights() {
1071 boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
1072 piece.classList.remove(CSS.highlight1);
1073 piece.classList.remove(CSS.highlight2);
1077 function snapbackDraggedPiece() {
1078 // there is no "snapback" for spare pieces
1079 if (DRAGGED_PIECE_SOURCE === 'spare') {
1080 trashDraggedPiece();
1084 removeSquareHighlights();
1086 // animation complete
1087 function complete() {
1088 drawPositionInstant();
1089 draggedPieceEl.style.display = 'none';
1091 // run their onSnapbackEnd function
1092 if (cfg.hasOwnProperty('onSnapbackEnd') === true &&
1093 typeof cfg.onSnapbackEnd === 'function') {
1094 cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
1095 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1099 // get source square position
1100 var sourceSquarePosition =
1101 offset(document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]));
1103 // animate the piece to the target square
1105 duration: cfg.snapbackSpeed,
1108 $(draggedPieceEl).animate(sourceSquarePosition, opts);
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 $(draggedPieceEl).fadeOut(cfg.trashSpeed);
1129 DRAGGING_A_PIECE = false;
1132 function dropDraggedPieceOnSquare(square) {
1133 removeSquareHighlights();
1136 var newPosition = deepCopy(CURRENT_POSITION);
1137 delete newPosition[DRAGGED_PIECE_SOURCE];
1138 newPosition[square] = DRAGGED_PIECE;
1139 setCurrentPosition(newPosition);
1141 // get target square information
1142 var targetSquarePosition = offset(document.getElementById(SQUARE_ELS_IDS[square]));
1144 // animation complete
1145 var complete = function() {
1146 drawPositionInstant();
1147 draggedPieceEl.style.display = 'none';
1149 // execute their onSnapEnd function
1150 if (cfg.hasOwnProperty('onSnapEnd') === true &&
1151 typeof cfg.onSnapEnd === 'function') {
1152 cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
1156 // snap the piece to the target square
1158 duration: cfg.snapSpeed,
1161 $(draggedPieceEl).animate(targetSquarePosition, opts);
1164 DRAGGING_A_PIECE = false;
1167 function beginDraggingPiece(source, piece, x, y) {
1168 // run their custom onDragStart function
1169 // their custom onDragStart function can cancel drag start
1170 if (typeof cfg.onDragStart === 'function' &&
1171 cfg.onDragStart(source, piece,
1172 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
1177 DRAGGING_A_PIECE = true;
1178 DRAGGED_PIECE = piece;
1179 DRAGGED_PIECE_SOURCE = source;
1181 // if the piece came from spare pieces, location is offboard
1182 if (source === 'spare') {
1183 DRAGGED_PIECE_LOCATION = 'offboard';
1186 DRAGGED_PIECE_LOCATION = source;
1189 // capture the x, y coords of all squares in memory
1190 captureSquareOffsets();
1192 // create the dragged piece
1193 draggedPieceEl.setAttribute('src', buildPieceImgSrc(piece));
1194 draggedPieceEl.style.display = null;
1195 draggedPieceEl.style.position = 'absolute';
1196 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1197 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1199 if (source !== 'spare') {
1200 // highlight the source square and hide the piece
1201 let square = document.getElementById(SQUARE_ELS_IDS[source]);
1202 square.classList.add(CSS.highlight1);
1203 square.querySelector('.' + CSS.piece).style.display = 'none';
1207 function updateDraggedPiece(x, y) {
1208 // put the dragged piece over the mouse cursor
1209 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1210 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1213 var location = isXYOnSquare(x, y);
1215 // do nothing if the location has not changed
1216 if (location === DRAGGED_PIECE_LOCATION) return;
1218 // remove highlight from previous square
1219 if (validSquare(DRAGGED_PIECE_LOCATION) === true) {
1220 document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION])
1221 .classList.remove(CSS.highlight2);
1224 // add highlight to new square
1225 if (validSquare(location) === true) {
1226 document.getElementById(SQUARE_ELS_IDS[location]).classList.add(CSS.highlight2);
1230 if (typeof cfg.onDragMove === 'function') {
1231 cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1232 DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1233 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1237 DRAGGED_PIECE_LOCATION = location;
1240 function stopDraggedPiece(location) {
1241 // determine what the action should be
1242 var action = 'drop';
1243 if (location === 'offboard' && cfg.dropOffBoard === 'snapback') {
1244 action = 'snapback';
1246 if (location === 'offboard' && cfg.dropOffBoard === 'trash') {
1250 // run their onDrop function, which can potentially change the drop action
1251 if (cfg.hasOwnProperty('onDrop') === true &&
1252 typeof cfg.onDrop === 'function') {
1253 var newPosition = deepCopy(CURRENT_POSITION);
1255 // source piece is a spare piece and position is off the board
1256 //if (DRAGGED_PIECE_SOURCE === 'spare' && location === 'offboard') {...}
1257 // position has not changed; do nothing
1259 // source piece is a spare piece and position is on the board
1260 if (DRAGGED_PIECE_SOURCE === 'spare' && validSquare(location) === true) {
1261 // add the piece to the board
1262 newPosition[location] = DRAGGED_PIECE;
1265 // source piece was on the board and position is off the board
1266 if (validSquare(DRAGGED_PIECE_SOURCE) === true && location === 'offboard') {
1267 // remove the piece from the board
1268 delete newPosition[DRAGGED_PIECE_SOURCE];
1271 // source piece was on the board and position is on the board
1272 if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1273 validSquare(location) === true) {
1275 delete newPosition[DRAGGED_PIECE_SOURCE];
1276 newPosition[location] = DRAGGED_PIECE;
1279 var oldPosition = deepCopy(CURRENT_POSITION);
1281 var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE,
1282 newPosition, oldPosition, CURRENT_ORIENTATION);
1283 if (result === 'snapback' || result === 'trash') {
1289 if (action === 'snapback') {
1290 snapbackDraggedPiece();
1292 else if (action === 'trash') {
1293 trashDraggedPiece();
1295 else if (action === 'drop') {
1296 dropDraggedPieceOnSquare(location);
1300 //------------------------------------------------------------------------------
1302 //------------------------------------------------------------------------------
1305 widget.clear = function(useAnimation) {
1306 widget.position({}, useAnimation);
1310 // get or set config properties
1311 // TODO: write this, GitHub Issue #1
1312 widget.config = function(arg1, arg2) {
1313 // get the current config
1314 if (arguments.length === 0) {
1315 return deepCopy(cfg);
1320 // remove the widget from the page
1321 widget.destroy = function() {
1323 containerEl.innerHTML = '';
1324 draggedPieceEl.remove();
1327 // shorthand method to get the current FEN
1328 widget.fen = function() {
1329 return widget.position('fen');
1333 widget.flip = function() {
1334 widget.orientation('flip');
1338 // TODO: write this, GitHub Issue #5
1339 widget.highlight = function() {
1345 widget.move = function() {
1346 // no need to throw an error here; just do nothing
1347 if (arguments.length === 0) return;
1349 var useAnimation = true;
1351 // collect the moves into an object
1353 for (var i = 0; i < arguments.length; i++) {
1354 // any "false" to this function means no animations
1355 if (arguments[i] === false) {
1356 useAnimation = false;
1360 // skip invalid arguments
1361 if (validMove(arguments[i]) !== true) {
1362 error(2826, 'Invalid move passed to the move method.', arguments[i]);
1366 var tmp = arguments[i].split('-');
1367 moves[tmp[0]] = tmp[1];
1370 // calculate position from moves
1371 var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1374 widget.position(newPos, useAnimation);
1376 // return the new position object
1380 widget.orientation = function(arg) {
1381 // no arguments, return the current orientation
1382 if (arguments.length === 0) {
1383 return CURRENT_ORIENTATION;
1386 // set to white or black
1387 if (arg === 'white' || arg === 'black') {
1388 CURRENT_ORIENTATION = arg;
1394 if (arg === 'flip') {
1395 CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1400 error(5482, 'Invalid value passed to the orientation method.', arg);
1404 * @param {!string|!Object} position
1405 * @param {boolean=} useAnimation
1407 widget.position = function(position, useAnimation) {
1408 // no arguments, return the current position
1409 if (arguments.length === 0) {
1410 return deepCopy(CURRENT_POSITION);
1413 // get position as FEN
1414 if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1415 return objToFen(CURRENT_POSITION);
1418 // default for useAnimations is true
1419 if (useAnimation !== false) {
1420 useAnimation = true;
1424 if (typeof position === 'string' && position.toLowerCase() === 'start') {
1425 position = deepCopy(START_POSITION);
1428 // convert FEN to position object
1429 if (validFen(position) === true) {
1430 position = fenToObj(position);
1433 // validate position object
1434 if (validPositionObject(position) !== true) {
1435 error(6482, 'Invalid value passed to the position method.', position);
1439 if (useAnimation === true) {
1440 // start the animations
1441 doAnimations(calculateAnimations(CURRENT_POSITION, position),
1442 CURRENT_POSITION, position);
1444 // set the new position
1445 setCurrentPosition(position);
1449 setCurrentPosition(position);
1450 drawPositionInstant();
1454 widget.resize = function() {
1455 // calulate the new square size
1456 SQUARE_SIZE = calculateSquareSize();
1459 boardEl.style.width = (SQUARE_SIZE * 8) + 'px';
1461 // set drag piece size
1462 if (draggedPieceEl !== null) {
1463 draggedPieceEl.style.height = SQUARE_SIZE + 'px';
1464 draggedPieceEl.style.width = SQUARE_SIZE + 'px';
1468 if (cfg.sparePieces === true) {
1469 containerEl.querySelector('.' + CSS.sparePieces)
1470 .style.paddingLeft = (SQUARE_SIZE + BOARD_BORDER_SIZE) + 'px';
1477 // set the starting position
1478 widget.start = function(useAnimation) {
1479 widget.position('start', useAnimation);
1482 //------------------------------------------------------------------------------
1484 //------------------------------------------------------------------------------
1486 function isTouchDevice() {
1487 return ('ontouchstart' in document.documentElement);
1490 function mousedownSquare(e) {
1491 let target = e.target.closest('.' + CSS.square);
1496 // do nothing if we're not draggable
1497 if (cfg.draggable !== true) return;
1499 var square = target.getAttribute('data-square');
1501 // no piece on this square
1502 if (validSquare(square) !== true ||
1503 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1507 beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1510 function touchstartSquare(e) {
1511 let target = e.target.closest('.' + CSS.square);
1516 // do nothing if we're not draggable
1517 if (cfg.draggable !== true) return;
1519 var square = target.getAttribute('data-square');
1521 // no piece on this square
1522 if (validSquare(square) !== true ||
1523 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1527 e = e.originalEvent;
1528 beginDraggingPiece(square, CURRENT_POSITION[square],
1529 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1532 function mousedownSparePiece(e) {
1533 if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1537 // do nothing if sparePieces is not enabled
1538 if (cfg.sparePieces !== true) return;
1540 var piece = e.target.getAttribute('data-piece');
1542 beginDraggingPiece('spare', piece, e.pageX, e.pageY);
1545 function touchstartSparePiece(e) {
1546 if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1550 // do nothing if sparePieces is not enabled
1551 if (cfg.sparePieces !== true) return;
1553 var piece = e.target.getAttribute('data-piece');
1555 e = e.originalEvent;
1556 beginDraggingPiece('spare', piece,
1557 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1560 function mousemoveWindow(e) {
1561 // do nothing if we are not dragging a piece
1562 if (DRAGGING_A_PIECE !== true) return;
1564 updateDraggedPiece(e.pageX, e.pageY);
1567 function touchmoveWindow(e) {
1568 // do nothing if we are not dragging a piece
1569 if (DRAGGING_A_PIECE !== true) return;
1571 // prevent screen from scrolling
1574 updateDraggedPiece(e.originalEvent.changedTouches[0].pageX,
1575 e.originalEvent.changedTouches[0].pageY);
1578 function mouseupWindow(e) {
1579 // do nothing if we are not dragging a piece
1580 if (DRAGGING_A_PIECE !== true) return;
1583 var location = isXYOnSquare(e.pageX, e.pageY);
1585 stopDraggedPiece(location);
1588 function touchendWindow(e) {
1589 // do nothing if we are not dragging a piece
1590 if (DRAGGING_A_PIECE !== true) return;
1593 var location = isXYOnSquare(e.originalEvent.changedTouches[0].pageX,
1594 e.originalEvent.changedTouches[0].pageY);
1596 stopDraggedPiece(location);
1599 function mouseenterSquare(e) {
1600 let target = e.target.closest('.' + CSS.square);
1605 // do not fire this event if we are dragging a piece
1606 // NOTE: this should never happen, but it's a safeguard
1607 if (DRAGGING_A_PIECE !== false) return;
1609 if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1610 typeof cfg.onMouseoverSquare !== 'function') return;
1613 var square = target.getAttribute('data-square');
1615 // NOTE: this should never happen; defensive
1616 if (validSquare(square) !== true) return;
1618 // get the piece on this square
1620 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1621 piece = CURRENT_POSITION[square];
1624 // execute their function
1625 cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1626 CURRENT_ORIENTATION);
1629 function mouseleaveSquare(e) {
1630 let target = e.target.closest('.' + CSS.square);
1635 // do not fire this event if we are dragging a piece
1636 // NOTE: this should never happen, but it's a safeguard
1637 if (DRAGGING_A_PIECE !== false) return;
1639 if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1640 typeof cfg.onMouseoutSquare !== 'function') return;
1643 var square = target.getAttribute('data-square');
1645 // NOTE: this should never happen; defensive
1646 if (validSquare(square) !== true) return;
1648 // get the piece on this square
1650 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1651 piece = CURRENT_POSITION[square];
1654 // execute their function
1655 cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1656 CURRENT_ORIENTATION);
1659 //------------------------------------------------------------------------------
1661 //------------------------------------------------------------------------------
1663 function addEvents() {
1664 // prevent browser "image drag"
1665 let stopDefault = (e) => {
1666 if (e.target.matches('.' + CSS.piece)) {
1670 document.body.addEventListener('mousedown', stopDefault);
1671 document.body.addEventListener('mousemove', stopDefault);
1673 // mouse drag pieces
1674 boardEl.addEventListener('mousedown', mousedownSquare);
1675 containerEl.addEventListener('mousedown', mousedownSparePiece);
1677 // mouse enter / leave square
1678 boardEl.addEventListener('mouseenter', mouseenterSquare);
1679 boardEl.addEventListener('mouseleave', mouseleaveSquare);
1681 window.addEventListener('mousemove', mousemoveWindow);
1682 window.addEventListener('mouseup', mouseupWindow);
1684 // touch drag pieces
1685 if (isTouchDevice() === true) {
1686 boardEl.addEventListener('touchstart', touchstartSquare);
1687 containerEl.addEventListener('touchstart', touchstartSparePiece);
1688 window.addEventListener('touchmove', touchmoveWindow);
1689 window.addEventListener('touchend', touchendWindow);
1693 function initDom() {
1694 // build board and save it in memory
1695 containerEl.innerHTML = buildBoardContainer();
1696 boardEl = containerEl.querySelector('.' + CSS.board);
1698 if (cfg.sparePieces === true) {
1699 sparePiecesTopEl = containerEl.querySelector('.' + CSS.sparePiecesTop);
1700 sparePiecesBottomEl = containerEl.querySelector('.' + CSS.sparePiecesBottom);
1703 // create the drag piece
1704 var draggedPieceId = createId();
1705 document.body.append(buildPiece('wP', true, draggedPieceId));
1706 draggedPieceEl = document.getElementById(draggedPieceId);
1708 // get the border size
1709 BOARD_BORDER_SIZE = parseInt(boardEl.style.borderLeftWidth, 10);
1711 // set the size and draw the board
1716 if (checkDeps() !== true ||
1717 expandConfig() !== true) return;
1719 // create unique IDs for all the elements we will create
1729 // return the widget object
1732 }; // end window.ChessBoard
1734 // expose util functions
1735 window.ChessBoard.fenToObj = fenToObj;
1736 window.ChessBoard.objToFen = objToFen;
1738 })(); // end anonymous wrapper