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;
373 function validAnimationSpeed(speed) {
374 if (speed === 'fast' || speed === 'slow') {
378 if ((parseInt(speed, 10) + '') !== (speed + '')) {
385 // validate config / set default options
386 function expandConfig() {
387 if (typeof cfg === 'string' || validPositionObject(cfg) === true) {
393 // default for orientation is white
394 if (cfg.orientation !== 'black') {
395 cfg.orientation = 'white';
397 CURRENT_ORIENTATION = cfg.orientation;
399 // default for showNotation is true
400 if (cfg.showNotation !== false) {
401 cfg.showNotation = true;
404 // default for draggable is false
405 if (cfg.draggable !== true) {
406 cfg.draggable = false;
409 // default for dropOffBoard is 'snapback'
410 if (cfg.dropOffBoard !== 'trash') {
411 cfg.dropOffBoard = 'snapback';
414 // default for sparePieces is false
415 if (cfg.sparePieces !== true) {
416 cfg.sparePieces = false;
419 // draggable must be true if sparePieces is enabled
420 if (cfg.sparePieces === true) {
421 cfg.draggable = true;
424 // default piece theme is wikipedia
425 if (cfg.hasOwnProperty('pieceTheme') !== true ||
426 (typeof cfg.pieceTheme !== 'string' &&
427 typeof cfg.pieceTheme !== 'function')) {
428 cfg.pieceTheme = 'img/chesspieces/wikipedia/{piece}.png';
432 if (cfg.hasOwnProperty('appearSpeed') !== true ||
433 validAnimationSpeed(cfg.appearSpeed) !== true) {
434 cfg.appearSpeed = 200;
436 if (cfg.hasOwnProperty('moveSpeed') !== true ||
437 validAnimationSpeed(cfg.moveSpeed) !== true) {
440 if (cfg.hasOwnProperty('snapbackSpeed') !== true ||
441 validAnimationSpeed(cfg.snapbackSpeed) !== true) {
442 cfg.snapbackSpeed = 50;
444 if (cfg.hasOwnProperty('snapSpeed') !== true ||
445 validAnimationSpeed(cfg.snapSpeed) !== true) {
448 if (cfg.hasOwnProperty('trashSpeed') !== true ||
449 validAnimationSpeed(cfg.trashSpeed) !== true) {
450 cfg.trashSpeed = 100;
453 // make sure position is valid
454 if (cfg.hasOwnProperty('position') === true) {
455 if (cfg.position === 'start') {
456 CURRENT_POSITION = deepCopy(START_POSITION);
459 else if (validFen(cfg.position) === true) {
460 CURRENT_POSITION = fenToObj(cfg.position);
463 else if (validPositionObject(cfg.position) === true) {
464 CURRENT_POSITION = deepCopy(cfg.position);
468 error(7263, 'Invalid value passed to config.position.', cfg.position);
475 //------------------------------------------------------------------------------
477 //------------------------------------------------------------------------------
479 // calculates square size based on the width of the container
480 // got a little CSS black magic here, so let me explain:
481 // get the width of the container element (could be anything), reduce by 1 for
482 // fudge factor, and then keep reducing until we find an exact mod 8 for
484 function calculateSquareSize() {
485 var containerWidth = parseInt(getComputedStyle(containerEl).width, 10);
487 // defensive, prevent infinite loop
488 if (! containerWidth || containerWidth <= 0) {
493 var boardWidth = containerWidth - 1;
495 while (boardWidth % 8 !== 0 && boardWidth > 0) {
499 return (boardWidth / 8);
502 // create random IDs for elements
503 function createElIds() {
504 // squares on the board
505 for (var i = 0; i < COLUMNS.length; i++) {
506 for (var j = 1; j <= 8; j++) {
507 var square = COLUMNS[i] + j;
508 SQUARE_ELS_IDS[square] = square + '-' + createId();
513 var pieces = 'KQRBNP'.split('');
514 for (var i = 0; i < pieces.length; i++) {
515 var whitePiece = 'w' + pieces[i];
516 var blackPiece = 'b' + pieces[i];
517 SPARE_PIECE_ELS_IDS[whitePiece] = whitePiece + '-' + createId();
518 SPARE_PIECE_ELS_IDS[blackPiece] = blackPiece + '-' + createId();
522 //------------------------------------------------------------------------------
524 //------------------------------------------------------------------------------
526 function buildBoardContainer() {
527 var html = '<div class="' + CSS.chessboard + '">';
529 if (cfg.sparePieces === true) {
530 html += '<div class="' + CSS.sparePieces + ' ' +
531 CSS.sparePiecesTop + '"></div>';
534 html += '<div class="' + CSS.board + '"></div>';
536 if (cfg.sparePieces === true) {
537 html += '<div class="' + CSS.sparePieces + ' ' +
538 CSS.sparePiecesBottom + '"></div>';
547 var buildSquare = function(color, size, id) {
548 var html = '<div class="' + CSS.square + ' ' + CSSColor[color] + '" ' +
549 'style="width: ' + size + 'px; height: ' + size + 'px" ' +
552 if (cfg.showNotation === true) {
562 function buildBoard(orientation) {
563 if (orientation !== 'black') {
564 orientation = 'white';
569 // algebraic notation / orientation
570 var alpha = deepCopy(COLUMNS);
572 if (orientation === 'black') {
577 var squareColor = 'white';
578 for (var i = 0; i < 8; i++) {
579 html += '<div class="' + CSS.row + '">';
580 for (var j = 0; j < 8; j++) {
581 var square = alpha[j] + row;
583 html += '<div class="' + CSS.square + ' ' + CSSColor[squareColor] + ' ' +
584 'square-' + square + '" ' +
585 'style="width: ' + SQUARE_SIZE + 'px; height: ' + SQUARE_SIZE + 'px" ' +
586 'id="' + SQUARE_ELS_IDS[square] + '" ' +
587 'data-square="' + square + '">';
589 if (cfg.showNotation === true) {
591 if ((orientation === 'white' && row === 1) ||
592 (orientation === 'black' && row === 8)) {
593 html += '<div class="' + CSS.notation + ' ' + CSS.alpha + '">' +
599 html += '<div class="' + CSS.notation + ' ' + CSS.numeric + '">' +
604 html += '</div>'; // end .square
606 squareColor = (squareColor === 'white' ? 'black' : 'white');
608 html += '<div class="' + CSS.clearfix + '"></div></div>';
610 squareColor = (squareColor === 'white' ? 'black' : 'white');
612 if (orientation === 'white') {
623 function buildPieceImgSrc(piece) {
624 if (typeof cfg.pieceTheme === 'function') {
625 return cfg.pieceTheme(piece);
628 if (typeof cfg.pieceTheme === 'string') {
629 return cfg.pieceTheme.replace(/{piece}/g, piece);
632 // NOTE: this should never happen
633 error(8272, 'Unable to build image source for cfg.pieceTheme.');
638 * @param {!string} piece
639 * @param {boolean=} hidden
640 * @param {!string=} id
642 function buildPiece(piece, hidden, id) {
643 var html = '<img src="' + buildPieceImgSrc(piece) + '" ';
644 if (id && typeof id === 'string') {
645 html += 'id="' + id + '" ';
648 'class="' + CSS.piece + '" ' +
649 'data-piece="' + piece + '" ' +
650 'style="width: ' + SQUARE_SIZE + 'px;' +
651 'height: ' + SQUARE_SIZE + 'px;';
652 if (hidden === true) {
653 html += 'display:none;';
657 let elem = document.createElement('template');
658 elem.innerHTML = html;
662 function buildSparePieces(color) {
663 var pieces = ['wK', 'wQ', 'wR', 'wB', 'wN', 'wP'];
664 if (color === 'black') {
665 pieces = ['bK', 'bQ', 'bR', 'bB', 'bN', 'bP'];
669 for (var i = 0; i < pieces.length; i++) {
670 html += buildPiece(pieces[i], false, SPARE_PIECE_ELS_IDS[pieces[i]]);
676 //------------------------------------------------------------------------------
678 //------------------------------------------------------------------------------
680 function offset(el) { // From https://youmightnotneedjquery.com/.
681 let box = el.getBoundingClientRect();
682 let docElem = document.documentElement;
684 top: box.top + window.pageYOffset - docElem.clientTop,
685 left: box.left + window.pageXOffset - docElem.clientLeft
689 function animateSquareToSquare(src, dest, piece, completeFn) {
690 // get information about the source and destination squares
691 var srcSquareEl = document.getElementById(SQUARE_ELS_IDS[src]);
692 var srcSquarePosition = offset(srcSquareEl);
693 var destSquareEl = document.getElementById(SQUARE_ELS_IDS[dest]);
694 var destSquarePosition = offset(destSquareEl);
696 // create the animated piece and absolutely position it
697 // over the source square
698 var animatedPieceId = createId();
699 document.body.append(buildPiece(piece, true, animatedPieceId));
700 var animatedPieceEl = document.getElementById(animatedPieceId);
701 animatedPieceEl.style.display = null;
702 animatedPieceEl.style.position = 'absolute';
703 animatedPieceEl.style.top = srcSquarePosition.top + 'px';
704 animatedPieceEl.style.left = srcSquarePosition.left + 'px';
706 // remove original piece(s) from source square
707 // TODO: multiple pieces should never really happen, but it will if we are moving
708 // while another animation still isn't done
709 srcSquareEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
712 var complete = function() {
713 // add the "real" piece to the destination square
714 destSquareEl.append(buildPiece(piece));
716 // remove the animated piece
717 animatedPieceEl.remove();
719 // run complete function
720 if (typeof completeFn === 'function') {
725 // animate the piece to the destination square
726 animatedPieceEl.addEventListener('transitionend', complete, {once: true});
727 requestAnimationFrame(() => {
728 animatedPieceEl.style.transitionProperty = 'top left';
729 animatedPieceEl.style.transitionDuration = cfg.moveSpeed + 'ms';
730 animatedPieceEl.style.top = destSquarePosition.top + 'px';
731 animatedPieceEl.style.left = destSquarePosition.left + 'px';
735 function animateSparePieceToSquare(piece, dest, completeFn) {
736 var srcOffset = offset(document.getelementById(SPARE_PIECE_ELS_IDS[piece]));
737 var destSquareEl = document.getElementById(SQUARE_ELS_IDS[dest]);
738 var destOffset = offset(destSquareEl);
740 // create the animate piece
741 var pieceId = createId();
742 document.body.append(buildPiece(piece, true, pieceId));
743 var animatedPieceEl = document.getElementById(pieceId);
744 animatedPieceEl.style.display = '';
745 animatedPieceEl.style.position = 'absolute';
746 animatedPieceEl.style.left = srcOffset.left;
747 animatedPieceEl.style.top = srcOffset.top;
750 var complete = function() {
751 // add the "real" piece to the destination square
752 destSquareEl.querySelector('.' + CSS.piece).remove();
753 destSquareEl.append(buildPiece(piece));
755 // remove the animated piece
756 animatedPieceEl.remove();
758 // run complete function
759 if (typeof completeFn === 'function') {
764 // animate the piece to the destination square
765 // FIXME: support this for non-jquery
767 duration: cfg.moveSpeed,
770 $(animatedPieceEl).animate(destOffset, opts);
773 function fadeIn(piece, onFinish) {
774 piece.style.opacity = 0;
775 piece.style.display = null;
776 piece.addEventListener('transitionend', onFinish, {once: true});
777 requestAnimationFrame(() => {
778 piece.style.transitionProperty = 'opacity';
779 piece.style.transitionDuration = cfg.appearSpeed + 'ms';
780 piece.style.opacity = 1;
784 function fadeOut(piece, onFinish) {
785 piece.style.opacity = 1;
786 piece.style.display = null;
787 piece.addEventListener('transitionend', onFinish, {once: true});
788 requestAnimationFrame(() => {
789 piece.style.transitionProperty = 'opacity';
790 piece.style.transitionDuration = cfg.trashSpeed + 'ms';
791 piece.style.opacity = 0;
795 // execute an array of animations
796 function doAnimations(a, oldPos, newPos) {
797 ANIMATION_HAPPENING = true;
800 function onFinish(e) {
802 e.target.transitionProperty = null;
807 // exit if all the animations aren't finished
808 if (numFinished !== a.length) return;
810 drawPositionInstant();
811 ANIMATION_HAPPENING = false;
813 // run their onMoveEnd function
814 if (cfg.hasOwnProperty('onMoveEnd') === true &&
815 typeof cfg.onMoveEnd === 'function') {
816 cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
820 for (var i = 0; i < a.length; i++) {
822 if (a[i].type === 'clear') {
823 document.getElementById(SQUARE_ELS_IDS[a[i].square]).querySelectorAll('.' + CSS.piece).forEach(
824 (piece) => fadeOut(piece, onFinish)
828 // add a piece (no spare pieces)
829 if (a[i].type === 'add' && cfg.sparePieces !== true) {
830 let square = document.getElementById(SQUARE_ELS_IDS[a[i].square]);
831 square.append(buildPiece(a[i].piece, true));
832 let piece = square.querySelector('.' + CSS.piece);
833 fadeIn(piece, onFinish);
836 // add a piece from a spare piece
837 if (a[i].type === 'add' && cfg.sparePieces === true) {
838 animateSparePieceToSquare(a[i].piece, a[i].square, onFinish);
842 if (a[i].type === 'move') {
843 animateSquareToSquare(a[i].source, a[i].destination, a[i].piece,
849 // returns the distance between two squares
850 function squareDistance(s1, s2) {
852 var s1x = COLUMNS.indexOf(s1[0]) + 1;
853 var s1y = parseInt(s1[1], 10);
856 var s2x = COLUMNS.indexOf(s2[0]) + 1;
857 var s2y = parseInt(s2[1], 10);
859 var xDelta = Math.abs(s1x - s2x);
860 var yDelta = Math.abs(s1y - s2y);
862 if (xDelta >= yDelta) return xDelta;
866 // returns an array of closest squares from square
867 function createRadius(square) {
870 // calculate distance of all squares
871 for (var i = 0; i < 8; i++) {
872 for (var j = 0; j < 8; j++) {
873 var s = COLUMNS[i] + (j + 1);
875 // skip the square we're starting from
876 if (square === s) continue;
880 distance: squareDistance(square, s)
886 squares.sort(function(a, b) {
887 return a.distance - b.distance;
890 // just return the square code
892 for (var i = 0; i < squares.length; i++) {
893 squares2.push(squares[i].square);
899 // returns the square of the closest instance of piece
900 // returns false if no instance of piece is found in position
901 function findClosestPiece(position, piece, square) {
902 // create array of closest squares from square
903 var closestSquares = createRadius(square);
905 // search through the position in order of distance for the piece
906 for (var i = 0; i < closestSquares.length; i++) {
907 var s = closestSquares[i];
909 if (position.hasOwnProperty(s) === true && position[s] === piece) {
917 // calculate an array of animations that need to happen in order to get
919 function calculateAnimations(pos1, pos2) {
920 // make copies of both
921 pos1 = deepCopy(pos1);
922 pos2 = deepCopy(pos2);
925 var squaresMovedTo = {};
927 // remove pieces that are the same in both positions
928 for (var i in pos2) {
929 if (pos2.hasOwnProperty(i) !== true) continue;
931 if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
937 // find all the "move" animations
938 for (var i in pos2) {
939 if (pos2.hasOwnProperty(i) !== true) continue;
941 var closestPiece = findClosestPiece(pos1, pos2[i], i);
942 if (closestPiece !== false) {
945 source: closestPiece,
950 delete pos1[closestPiece];
952 squaresMovedTo[i] = true;
956 // add pieces to pos2
957 for (var i in pos2) {
958 if (pos2.hasOwnProperty(i) !== true) continue;
969 // clear pieces from pos1
970 for (var i in pos1) {
971 if (pos1.hasOwnProperty(i) !== true) continue;
973 // do not clear a piece if it is on a square that is the result
974 // of a "move", ie: a piece capture
975 if (squaresMovedTo.hasOwnProperty(i) === true) continue;
989 //------------------------------------------------------------------------------
991 //------------------------------------------------------------------------------
993 function drawPositionInstant() {
995 boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
998 for (var i in CURRENT_POSITION) {
999 if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue;
1001 document.getElementById(SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i]));
1005 function drawBoard() {
1006 boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
1007 drawPositionInstant();
1009 if (cfg.sparePieces === true) {
1010 if (CURRENT_ORIENTATION === 'white') {
1011 sparePiecesTopEl.innerHTML = buildSparePieces('black');
1012 sparePiecesBottomEl.innerHTML = buildSparePieces('white');
1015 sparePiecesTopEl.innerHTML = buildSparePieces('white');
1016 sparePiecesBottomEl.innerHTML = buildSparePieces('black');
1021 // given a position and a set of moves, return a new position
1022 // with the moves executed
1023 function calculatePositionFromMoves(position, moves) {
1024 position = deepCopy(position);
1026 for (var i in moves) {
1027 if (moves.hasOwnProperty(i) !== true) continue;
1029 // skip the move if the position doesn't have a piece on the source square
1030 if (position.hasOwnProperty(i) !== true) continue;
1032 var piece = position[i];
1034 position[moves[i]] = piece;
1040 function setCurrentPosition(position) {
1041 var oldPos = deepCopy(CURRENT_POSITION);
1042 var newPos = deepCopy(position);
1043 var oldFen = objToFen(oldPos);
1044 var newFen = objToFen(newPos);
1046 // do nothing if no change in position
1047 if (oldFen === newFen) return;
1049 // run their onChange function
1050 if (cfg.hasOwnProperty('onChange') === true &&
1051 typeof cfg.onChange === 'function') {
1052 cfg.onChange(oldPos, newPos);
1056 CURRENT_POSITION = position;
1059 function isXYOnSquare(x, y) {
1060 for (var i in SQUARE_ELS_OFFSETS) {
1061 if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue;
1063 var s = SQUARE_ELS_OFFSETS[i];
1064 if (x >= s.left && x < s.left + SQUARE_SIZE &&
1065 y >= s.top && y < s.top + SQUARE_SIZE) {
1073 // records the XY coords of every square into memory
1074 function captureSquareOffsets() {
1075 SQUARE_ELS_OFFSETS = {};
1077 for (var i in SQUARE_ELS_IDS) {
1078 if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue;
1080 SQUARE_ELS_OFFSETS[i] = offset(document.getElementById(SQUARE_ELS_IDS[i]));
1084 function removeSquareHighlights() {
1085 boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
1086 piece.classList.remove(CSS.highlight1);
1087 piece.classList.remove(CSS.highlight2);
1091 function snapbackDraggedPiece() {
1092 // there is no "snapback" for spare pieces
1093 if (DRAGGED_PIECE_SOURCE === 'spare') {
1094 trashDraggedPiece();
1098 removeSquareHighlights();
1100 // animation complete
1101 function complete() {
1102 drawPositionInstant();
1103 draggedPieceEl.style.display = 'none';
1105 // run their onSnapbackEnd function
1106 if (cfg.hasOwnProperty('onSnapbackEnd') === true &&
1107 typeof cfg.onSnapbackEnd === 'function') {
1108 cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
1109 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1113 // get source square position
1114 var sourceSquarePosition =
1115 offset(document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]));
1117 // animate the piece to the target square
1118 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1119 requestAnimationFrame(() => {
1120 draggedPieceEl.style.transitionProperty = 'top left';
1121 draggedPieceEl.style.transitionDuration = cfg.snapbackSpeed + 'ms';
1122 draggedPieceEl.style.top = sourceSquarePosition.top + 'px';
1123 draggedPieceEl.style.left = sourceSquarePosition.left + 'px';
1127 DRAGGING_A_PIECE = false;
1130 function trashDraggedPiece() {
1131 removeSquareHighlights();
1133 // remove the source piece
1134 var newPosition = deepCopy(CURRENT_POSITION);
1135 delete newPosition[DRAGGED_PIECE_SOURCE];
1136 setCurrentPosition(newPosition);
1138 // redraw the position
1139 drawPositionInstant();
1141 // hide the dragged piece
1142 // FIXME: support this for non-jquery
1143 $(draggedPieceEl).fadeOut(cfg.trashSpeed);
1146 DRAGGING_A_PIECE = false;
1149 function dropDraggedPieceOnSquare(square) {
1150 removeSquareHighlights();
1153 var newPosition = deepCopy(CURRENT_POSITION);
1154 delete newPosition[DRAGGED_PIECE_SOURCE];
1155 newPosition[square] = DRAGGED_PIECE;
1156 setCurrentPosition(newPosition);
1158 // get target square information
1159 var targetSquarePosition = offset(document.getElementById(SQUARE_ELS_IDS[square]));
1161 // animation complete
1162 var complete = function() {
1163 drawPositionInstant();
1164 draggedPieceEl.style.display = 'none';
1166 // execute their onSnapEnd function
1167 if (cfg.hasOwnProperty('onSnapEnd') === true &&
1168 typeof cfg.onSnapEnd === 'function') {
1169 requestAnimationFrame(() => { // HACK: so that we don't add event handlers from the callback...
1170 cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
1175 // snap the piece to the target square
1176 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1177 requestAnimationFrame(() => {
1178 draggedPieceEl.style.transitionProperty = 'top left';
1179 draggedPieceEl.style.transitionDuration = cfg.snapSpeed + 'ms';
1180 draggedPieceEl.style.top = targetSquarePosition.top + 'px';
1181 draggedPieceEl.style.left = targetSquarePosition.left + 'px';
1185 DRAGGING_A_PIECE = false;
1188 function beginDraggingPiece(source, piece, x, y) {
1189 // run their custom onDragStart function
1190 // their custom onDragStart function can cancel drag start
1191 if (typeof cfg.onDragStart === 'function' &&
1192 cfg.onDragStart(source, piece,
1193 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
1198 DRAGGING_A_PIECE = true;
1199 DRAGGED_PIECE = piece;
1200 DRAGGED_PIECE_SOURCE = source;
1202 // if the piece came from spare pieces, location is offboard
1203 if (source === 'spare') {
1204 DRAGGED_PIECE_LOCATION = 'offboard';
1207 DRAGGED_PIECE_LOCATION = source;
1210 // capture the x, y coords of all squares in memory
1211 captureSquareOffsets();
1213 // create the dragged piece
1214 draggedPieceEl.setAttribute('src', buildPieceImgSrc(piece));
1215 draggedPieceEl.style.display = null;
1216 draggedPieceEl.style.position = 'absolute';
1217 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1218 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1220 if (source !== 'spare') {
1221 // highlight the source square and hide the piece
1222 let square = document.getElementById(SQUARE_ELS_IDS[source]);
1223 square.classList.add(CSS.highlight1);
1224 square.querySelector('.' + CSS.piece).style.display = 'none';
1228 function updateDraggedPiece(x, y) {
1229 // put the dragged piece over the mouse cursor
1230 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1231 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1234 var location = isXYOnSquare(x, y);
1236 // do nothing if the location has not changed
1237 if (location === DRAGGED_PIECE_LOCATION) return;
1239 // remove highlight from previous square
1240 if (validSquare(DRAGGED_PIECE_LOCATION) === true) {
1241 document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION])
1242 .classList.remove(CSS.highlight2);
1245 // add highlight to new square
1246 if (validSquare(location) === true) {
1247 document.getElementById(SQUARE_ELS_IDS[location]).classList.add(CSS.highlight2);
1251 if (typeof cfg.onDragMove === 'function') {
1252 cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1253 DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1254 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1258 DRAGGED_PIECE_LOCATION = location;
1261 function stopDraggedPiece(location) {
1262 // determine what the action should be
1263 var action = 'drop';
1264 if (location === 'offboard' && cfg.dropOffBoard === 'snapback') {
1265 action = 'snapback';
1267 if (location === 'offboard' && cfg.dropOffBoard === 'trash') {
1271 // run their onDrop function, which can potentially change the drop action
1272 if (cfg.hasOwnProperty('onDrop') === true &&
1273 typeof cfg.onDrop === 'function') {
1274 var newPosition = deepCopy(CURRENT_POSITION);
1276 // source piece is a spare piece and position is off the board
1277 //if (DRAGGED_PIECE_SOURCE === 'spare' && location === 'offboard') {...}
1278 // position has not changed; do nothing
1280 // source piece is a spare piece and position is on the board
1281 if (DRAGGED_PIECE_SOURCE === 'spare' && validSquare(location) === true) {
1282 // add the piece to the board
1283 newPosition[location] = DRAGGED_PIECE;
1286 // source piece was on the board and position is off the board
1287 if (validSquare(DRAGGED_PIECE_SOURCE) === true && location === 'offboard') {
1288 // remove the piece from the board
1289 delete newPosition[DRAGGED_PIECE_SOURCE];
1292 // source piece was on the board and position is on the board
1293 if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1294 validSquare(location) === true) {
1296 delete newPosition[DRAGGED_PIECE_SOURCE];
1297 newPosition[location] = DRAGGED_PIECE;
1300 var oldPosition = deepCopy(CURRENT_POSITION);
1302 var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE,
1303 newPosition, oldPosition, CURRENT_ORIENTATION);
1304 if (result === 'snapback' || result === 'trash') {
1310 if (action === 'snapback') {
1311 snapbackDraggedPiece();
1313 else if (action === 'trash') {
1314 trashDraggedPiece();
1316 else if (action === 'drop') {
1317 dropDraggedPieceOnSquare(location);
1321 //------------------------------------------------------------------------------
1323 //------------------------------------------------------------------------------
1326 widget.clear = function(useAnimation) {
1327 widget.position({}, useAnimation);
1331 // get or set config properties
1332 // TODO: write this, GitHub Issue #1
1333 widget.config = function(arg1, arg2) {
1334 // get the current config
1335 if (arguments.length === 0) {
1336 return deepCopy(cfg);
1341 // remove the widget from the page
1342 widget.destroy = function() {
1344 containerEl.innerHTML = '';
1345 draggedPieceEl.remove();
1348 // shorthand method to get the current FEN
1349 widget.fen = function() {
1350 return widget.position('fen');
1354 widget.flip = function() {
1355 widget.orientation('flip');
1359 // TODO: write this, GitHub Issue #5
1360 widget.highlight = function() {
1366 widget.move = function() {
1367 // no need to throw an error here; just do nothing
1368 if (arguments.length === 0) return;
1370 var useAnimation = true;
1372 // collect the moves into an object
1374 for (var i = 0; i < arguments.length; i++) {
1375 // any "false" to this function means no animations
1376 if (arguments[i] === false) {
1377 useAnimation = false;
1381 // skip invalid arguments
1382 if (validMove(arguments[i]) !== true) {
1383 error(2826, 'Invalid move passed to the move method.', arguments[i]);
1387 var tmp = arguments[i].split('-');
1388 moves[tmp[0]] = tmp[1];
1391 // calculate position from moves
1392 var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1395 widget.position(newPos, useAnimation);
1397 // return the new position object
1401 widget.orientation = function(arg) {
1402 // no arguments, return the current orientation
1403 if (arguments.length === 0) {
1404 return CURRENT_ORIENTATION;
1407 // set to white or black
1408 if (arg === 'white' || arg === 'black') {
1409 CURRENT_ORIENTATION = arg;
1415 if (arg === 'flip') {
1416 CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1421 error(5482, 'Invalid value passed to the orientation method.', arg);
1425 * @param {!string|!Object} position
1426 * @param {boolean=} useAnimation
1428 widget.position = function(position, useAnimation) {
1429 // no arguments, return the current position
1430 if (arguments.length === 0) {
1431 return deepCopy(CURRENT_POSITION);
1434 // get position as FEN
1435 if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1436 return objToFen(CURRENT_POSITION);
1439 // default for useAnimations is true
1440 if (useAnimation !== false) {
1441 useAnimation = true;
1445 if (typeof position === 'string' && position.toLowerCase() === 'start') {
1446 position = deepCopy(START_POSITION);
1449 // convert FEN to position object
1450 if (validFen(position) === true) {
1451 position = fenToObj(position);
1454 // validate position object
1455 if (validPositionObject(position) !== true) {
1456 error(6482, 'Invalid value passed to the position method.', position);
1460 if (useAnimation === true) {
1461 // start the animations
1462 doAnimations(calculateAnimations(CURRENT_POSITION, position),
1463 CURRENT_POSITION, position);
1465 // set the new position
1466 setCurrentPosition(position);
1470 setCurrentPosition(position);
1471 drawPositionInstant();
1475 widget.resize = function() {
1476 // calulate the new square size
1477 SQUARE_SIZE = calculateSquareSize();
1480 boardEl.style.width = (SQUARE_SIZE * 8) + 'px';
1482 // set drag piece size
1483 if (draggedPieceEl !== null) {
1484 draggedPieceEl.style.height = SQUARE_SIZE + 'px';
1485 draggedPieceEl.style.width = SQUARE_SIZE + 'px';
1489 if (cfg.sparePieces === true) {
1490 containerEl.querySelector('.' + CSS.sparePieces)
1491 .style.paddingLeft = (SQUARE_SIZE + BOARD_BORDER_SIZE) + 'px';
1498 // set the starting position
1499 widget.start = function(useAnimation) {
1500 widget.position('start', useAnimation);
1503 //------------------------------------------------------------------------------
1505 //------------------------------------------------------------------------------
1507 function isTouchDevice() {
1508 return ('ontouchstart' in document.documentElement);
1511 function mousedownSquare(e) {
1512 let target = e.target.closest('.' + CSS.square);
1517 // do nothing if we're not draggable
1518 if (cfg.draggable !== true) return;
1520 var square = target.getAttribute('data-square');
1522 // no piece on this square
1523 if (validSquare(square) !== true ||
1524 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1528 beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1531 function touchstartSquare(e) {
1532 let target = e.target.closest('.' + CSS.square);
1537 // do nothing if we're not draggable
1538 if (cfg.draggable !== true) return;
1540 var square = target.getAttribute('data-square');
1542 // no piece on this square
1543 if (validSquare(square) !== true ||
1544 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1548 e = e.originalEvent;
1549 beginDraggingPiece(square, CURRENT_POSITION[square],
1550 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1553 function mousedownSparePiece(e) {
1554 if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1558 // do nothing if sparePieces is not enabled
1559 if (cfg.sparePieces !== true) return;
1561 var piece = e.target.getAttribute('data-piece');
1563 beginDraggingPiece('spare', piece, e.pageX, e.pageY);
1566 function touchstartSparePiece(e) {
1567 if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1571 // do nothing if sparePieces is not enabled
1572 if (cfg.sparePieces !== true) return;
1574 var piece = e.target.getAttribute('data-piece');
1576 e = e.originalEvent;
1577 beginDraggingPiece('spare', piece,
1578 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1581 function mousemoveWindow(e) {
1582 // do nothing if we are not dragging a piece
1583 if (DRAGGING_A_PIECE !== true) return;
1585 updateDraggedPiece(e.pageX, e.pageY);
1588 function touchmoveWindow(e) {
1589 // do nothing if we are not dragging a piece
1590 if (DRAGGING_A_PIECE !== true) return;
1592 // prevent screen from scrolling
1595 updateDraggedPiece(e.originalEvent.changedTouches[0].pageX,
1596 e.originalEvent.changedTouches[0].pageY);
1599 function mouseupWindow(e) {
1600 // do nothing if we are not dragging a piece
1601 if (DRAGGING_A_PIECE !== true) return;
1604 var location = isXYOnSquare(e.pageX, e.pageY);
1606 stopDraggedPiece(location);
1609 function touchendWindow(e) {
1610 // do nothing if we are not dragging a piece
1611 if (DRAGGING_A_PIECE !== true) return;
1614 var location = isXYOnSquare(e.originalEvent.changedTouches[0].pageX,
1615 e.originalEvent.changedTouches[0].pageY);
1617 stopDraggedPiece(location);
1620 function mouseenterSquare(e) {
1621 let target = e.target.closest('.' + CSS.square);
1626 // do not fire this event if we are dragging a piece
1627 // NOTE: this should never happen, but it's a safeguard
1628 if (DRAGGING_A_PIECE !== false) return;
1630 if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1631 typeof cfg.onMouseoverSquare !== 'function') return;
1634 var square = target.getAttribute('data-square');
1636 // NOTE: this should never happen; defensive
1637 if (validSquare(square) !== true) return;
1639 // get the piece on this square
1641 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1642 piece = CURRENT_POSITION[square];
1645 // execute their function
1646 cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1647 CURRENT_ORIENTATION);
1650 function mouseleaveSquare(e) {
1651 let target = e.target.closest('.' + CSS.square);
1656 // do not fire this event if we are dragging a piece
1657 // NOTE: this should never happen, but it's a safeguard
1658 if (DRAGGING_A_PIECE !== false) return;
1660 if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1661 typeof cfg.onMouseoutSquare !== 'function') return;
1664 var square = target.getAttribute('data-square');
1666 // NOTE: this should never happen; defensive
1667 if (validSquare(square) !== true) return;
1669 // get the piece on this square
1671 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1672 piece = CURRENT_POSITION[square];
1675 // execute their function
1676 cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1677 CURRENT_ORIENTATION);
1680 //------------------------------------------------------------------------------
1682 //------------------------------------------------------------------------------
1684 function addEvents() {
1685 // prevent browser "image drag"
1686 let stopDefault = (e) => {
1687 if (e.target.matches('.' + CSS.piece)) {
1691 document.body.addEventListener('mousedown', stopDefault);
1692 document.body.addEventListener('mousemove', stopDefault);
1694 // mouse drag pieces
1695 boardEl.addEventListener('mousedown', mousedownSquare);
1696 containerEl.addEventListener('mousedown', mousedownSparePiece);
1698 // mouse enter / leave square
1699 boardEl.addEventListener('mouseenter', mouseenterSquare);
1700 boardEl.addEventListener('mouseleave', mouseleaveSquare);
1702 window.addEventListener('mousemove', mousemoveWindow);
1703 window.addEventListener('mouseup', mouseupWindow);
1705 // touch drag pieces
1706 if (isTouchDevice() === true) {
1707 boardEl.addEventListener('touchstart', touchstartSquare);
1708 containerEl.addEventListener('touchstart', touchstartSparePiece);
1709 window.addEventListener('touchmove', touchmoveWindow);
1710 window.addEventListener('touchend', touchendWindow);
1714 function initDom() {
1715 // build board and save it in memory
1716 containerEl.innerHTML = buildBoardContainer();
1717 boardEl = containerEl.querySelector('.' + CSS.board);
1719 if (cfg.sparePieces === true) {
1720 sparePiecesTopEl = containerEl.querySelector('.' + CSS.sparePiecesTop);
1721 sparePiecesBottomEl = containerEl.querySelector('.' + CSS.sparePiecesBottom);
1724 // create the drag piece
1725 var draggedPieceId = createId();
1726 document.body.append(buildPiece('wP', true, draggedPieceId));
1727 draggedPieceEl = document.getElementById(draggedPieceId);
1729 // get the border size
1730 BOARD_BORDER_SIZE = parseInt(boardEl.style.borderLeftWidth, 10);
1732 // set the size and draw the board
1737 if (checkDeps() !== true ||
1738 expandConfig() !== true) return;
1740 // create unique IDs for all the elements we will create
1750 // return the widget object
1753 }; // end window.ChessBoard
1755 // expose util functions
1756 window.ChessBoard.fenToObj = fenToObj;
1757 window.ChessBoard.objToFen = objToFen;
1759 })(); // end anonymous wrapper