2 * chessboard.js v0.3.0+asn
4 * Copyright 2013 Chris Oakman
5 * Portions copyright 2022 Steinar H. Gunderson
6 * Released under the MIT license
7 * http://chessboardjs.com/license
12 // start anonymous scope
16 //------------------------------------------------------------------------------
17 // Chess Util Functions
18 //------------------------------------------------------------------------------
19 var COLUMNS = 'abcdefgh'.split('');
21 function validMove(move) {
22 // move should be a string
23 if (typeof move !== 'string') return false;
25 // move should be in the form of "e2-e4", "f6-d5"
26 var tmp = move.split('-');
27 if (tmp.length !== 2) return false;
29 return (validSquare(tmp[0]) === true && validSquare(tmp[1]) === true);
32 function validSquare(square) {
33 if (typeof square !== 'string') return false;
34 return (square.search(/^[a-h][1-8]$/) !== -1);
37 function validPieceCode(code) {
38 if (typeof code !== 'string') return false;
39 return (code.search(/^[bw][KQRNBP]$/) !== -1);
42 // TODO: this whole function could probably be replaced with a single regex
43 function validFen(fen) {
44 if (typeof fen !== 'string') return false;
46 // cut off any move, castling, etc info from the end
47 // we're only interested in position information
48 fen = fen.replace(/ .+$/, '');
50 // FEN should be 8 sections separated by slashes
51 var chunks = fen.split('/');
52 if (chunks.length !== 8) return false;
54 // check the piece sections
55 for (var i = 0; i < 8; i++) {
56 if (chunks[i] === '' ||
57 chunks[i].length > 8 ||
58 chunks[i].search(/[^kqrbnpKQRNBP1-8]/) !== -1) {
66 function validPositionObject(pos) {
67 if (typeof pos !== 'object') return false;
70 if (pos.hasOwnProperty(i) !== true) continue;
72 if (validSquare(i) !== true || validPieceCode(pos[i]) !== true) {
80 // convert FEN piece code to bP, wK, etc
81 function fenToPieceCode(piece) {
83 if (piece.toLowerCase() === piece) {
84 return 'b' + piece.toUpperCase();
88 return 'w' + piece.toUpperCase();
91 // convert bP, wK, etc code to FEN structure
92 function pieceCodeToFen(piece) {
93 var tmp = piece.split('');
97 return tmp[1].toUpperCase();
101 return tmp[1].toLowerCase();
104 // convert FEN string to position object
105 // returns false if the FEN string is invalid
106 function fenToObj(fen) {
107 if (validFen(fen) !== true) {
111 // cut off any move, castling, etc info from the end
112 // we're only interested in position information
113 fen = fen.replace(/ .+$/, '');
115 var rows = fen.split('/');
119 for (var i = 0; i < 8; i++) {
120 var row = rows[i].split('');
123 // loop through each character in the FEN section
124 for (var j = 0; j < row.length; j++) {
125 // number / empty squares
126 if (row[j].search(/[1-8]/) !== -1) {
127 var emptySquares = parseInt(row[j], 10);
128 colIndex += emptySquares;
132 var square = COLUMNS[colIndex] + currentRow;
133 position[square] = fenToPieceCode(row[j]);
144 // position object to FEN string
145 // returns false if the obj is not a valid position object
146 function objToFen(obj) {
147 if (validPositionObject(obj) !== true) {
154 for (var i = 0; i < 8; i++) {
155 for (var j = 0; j < 8; j++) {
156 var square = COLUMNS[j] + currentRow;
159 if (obj.hasOwnProperty(square) === true) {
160 fen += pieceCodeToFen(obj[square]);
176 // squeeze the numbers together
177 // haha, I love this solution...
178 fen = fen.replace(/11111111/g, '8');
179 fen = fen.replace(/1111111/g, '7');
180 fen = fen.replace(/111111/g, '6');
181 fen = fen.replace(/11111/g, '5');
182 fen = fen.replace(/1111/g, '4');
183 fen = fen.replace(/111/g, '3');
184 fen = fen.replace(/11/g, '2');
193 window.ChessBoard = function(containerElOrId, cfg) {
198 //------------------------------------------------------------------------------
200 //------------------------------------------------------------------------------
202 var MINIMUM_JQUERY_VERSION = '1.7.0',
203 START_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR',
204 START_POSITION = fenToObj(START_FEN);
206 // use unique class names to prevent clashing with anything else on the page
207 // and simplify selectors
209 alpha: 'alpha-d2270',
210 board: 'board-b72b1',
211 chessboard: 'chessboard-63f37',
212 clearfix: 'clearfix-7da63',
213 highlight1: 'highlight1-32417',
214 highlight2: 'highlight2-9c5d2',
215 notation: 'notation-322f9',
216 numeric: 'numeric-fc462',
217 piece: 'piece-417db',
219 sparePieces: 'spare-pieces-7492f',
220 sparePiecesBottom: 'spare-pieces-bottom-ae20f',
221 sparePiecesTop: 'spare-pieces-top-4028b',
222 square: 'square-55d63'
225 CSSColor['white'] = 'white-1e1d7';
226 CSSColor['black'] = 'black-3c85d';
228 //------------------------------------------------------------------------------
229 // Module Scope Variables
230 //------------------------------------------------------------------------------
239 // constructor return object
242 //------------------------------------------------------------------------------
244 //------------------------------------------------------------------------------
246 var ANIMATION_HAPPENING = false,
247 BOARD_BORDER_SIZE = 2,
248 CURRENT_ORIENTATION = 'white',
249 CURRENT_POSITION = {},
252 DRAGGED_PIECE_LOCATION,
253 DRAGGED_PIECE_SOURCE,
254 DRAGGING_A_PIECE = false,
255 SPARE_PIECE_ELS_IDS = {},
259 //------------------------------------------------------------------------------
261 //------------------------------------------------------------------------------
263 // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
264 function createId() {
265 return 'xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx'.replace(/x/g, function(c) {
266 var r = Math.random() * 16 | 0;
267 return r.toString(16);
271 function deepCopy(thing) {
272 return JSON.parse(JSON.stringify(thing));
275 function parseSemVer(version) {
276 var tmp = version.split('.');
278 major: parseInt(tmp[0], 10),
279 minor: parseInt(tmp[1], 10),
280 patch: parseInt(tmp[2], 10)
284 // returns true if version is >= minimum
285 function compareSemVer(version, minimum) {
286 version = parseSemVer(version);
287 minimum = parseSemVer(minimum);
289 var versionNum = (version.major * 10000 * 10000) +
290 (version.minor * 10000) + version.patch;
291 var minimumNum = (minimum.major * 10000 * 10000) +
292 (minimum.minor * 10000) + minimum.patch;
294 return (versionNum >= minimumNum);
297 //------------------------------------------------------------------------------
298 // Validation / Errors
299 //------------------------------------------------------------------------------
302 * @param {!number} code
303 * @param {!string} msg
304 * @param {Object=} obj
306 function error(code, msg, obj) {
307 // do nothing if showErrors is not set
308 if (cfg.hasOwnProperty('showErrors') !== true ||
309 cfg.showErrors === false) {
313 var errorText = 'ChessBoard Error ' + code + ': ' + msg;
316 if (cfg.showErrors === 'console' &&
317 typeof console === 'object' &&
318 typeof console.log === 'function') {
319 console.log(errorText);
320 if (arguments.length >= 2) {
327 if (cfg.showErrors === 'alert') {
329 errorText += '\n\n' + JSON.stringify(obj);
331 window.alert(errorText);
336 if (typeof cfg.showErrors === 'function') {
337 cfg.showErrors(code, msg, obj);
341 // check dependencies
342 function checkDeps() {
343 // if containerId is a string, it must be the ID of a DOM node
344 if (typeof containerElOrId === 'string') {
346 if (containerElOrId === '') {
347 window.alert('ChessBoard Error 1001: ' +
348 'The first argument to ChessBoard() cannot be an empty string.' +
353 // make sure the container element exists in the DOM
354 var el = document.getElementById(containerElOrId);
356 window.alert('ChessBoard Error 1002: Element with id "' +
357 containerElOrId + '" does not exist in the DOM.' +
362 // set the containerEl
366 // else it must be a DOM node
368 containerEl = containerElOrId;
374 function validAnimationSpeed(speed) {
375 if (speed === 'fast' || speed === 'slow') {
379 if ((parseInt(speed, 10) + '') !== (speed + '')) {
386 // validate config / set default options
387 function expandConfig() {
388 if (typeof cfg === 'string' || validPositionObject(cfg) === true) {
394 // default for orientation is white
395 if (cfg.orientation !== 'black') {
396 cfg.orientation = 'white';
398 CURRENT_ORIENTATION = cfg.orientation;
400 // default for showNotation is true
401 if (cfg.showNotation !== false) {
402 cfg.showNotation = true;
405 // default for draggable is false
406 if (cfg.draggable !== true) {
407 cfg.draggable = false;
410 // default for dropOffBoard is 'snapback'
411 if (cfg.dropOffBoard !== 'trash') {
412 cfg.dropOffBoard = 'snapback';
415 // default for sparePieces is false
416 if (cfg.sparePieces !== true) {
417 cfg.sparePieces = false;
420 // draggable must be true if sparePieces is enabled
421 if (cfg.sparePieces === true) {
422 cfg.draggable = true;
425 // default piece theme is wikipedia
426 if (cfg.hasOwnProperty('pieceTheme') !== true ||
427 (typeof cfg.pieceTheme !== 'string' &&
428 typeof cfg.pieceTheme !== 'function')) {
429 cfg.pieceTheme = 'img/chesspieces/wikipedia/{piece}.png';
433 if (cfg.hasOwnProperty('appearSpeed') !== true ||
434 validAnimationSpeed(cfg.appearSpeed) !== true) {
435 cfg.appearSpeed = 200;
437 if (cfg.hasOwnProperty('moveSpeed') !== true ||
438 validAnimationSpeed(cfg.moveSpeed) !== true) {
441 if (cfg.hasOwnProperty('snapbackSpeed') !== true ||
442 validAnimationSpeed(cfg.snapbackSpeed) !== true) {
443 cfg.snapbackSpeed = 50;
445 if (cfg.hasOwnProperty('snapSpeed') !== true ||
446 validAnimationSpeed(cfg.snapSpeed) !== true) {
449 if (cfg.hasOwnProperty('trashSpeed') !== true ||
450 validAnimationSpeed(cfg.trashSpeed) !== true) {
451 cfg.trashSpeed = 100;
454 // make sure position is valid
455 if (cfg.hasOwnProperty('position') === true) {
456 if (cfg.position === 'start') {
457 CURRENT_POSITION = deepCopy(START_POSITION);
460 else if (validFen(cfg.position) === true) {
461 CURRENT_POSITION = fenToObj(cfg.position);
464 else if (validPositionObject(cfg.position) === true) {
465 CURRENT_POSITION = deepCopy(cfg.position);
469 error(7263, 'Invalid value passed to config.position.', cfg.position);
476 //------------------------------------------------------------------------------
478 //------------------------------------------------------------------------------
480 // calculates square size based on the width of the container
481 // got a little CSS black magic here, so let me explain:
482 // get the width of the container element (could be anything), reduce by 1 for
483 // fudge factor, and then keep reducing until we find an exact mod 8 for
485 function calculateSquareSize() {
486 var containerWidth = parseInt(getComputedStyle(containerEl).width, 10);
488 // defensive, prevent infinite loop
489 if (! containerWidth || containerWidth <= 0) {
494 var boardWidth = containerWidth - 1;
496 while (boardWidth % 8 !== 0 && boardWidth > 0) {
500 return (boardWidth / 8);
503 // create random IDs for elements
504 function createElIds() {
505 // squares on the board
506 for (var i = 0; i < COLUMNS.length; i++) {
507 for (var j = 1; j <= 8; j++) {
508 var square = COLUMNS[i] + j;
509 SQUARE_ELS_IDS[square] = square + '-' + createId();
514 var pieces = 'KQRBNP'.split('');
515 for (var i = 0; i < pieces.length; i++) {
516 var whitePiece = 'w' + pieces[i];
517 var blackPiece = 'b' + pieces[i];
518 SPARE_PIECE_ELS_IDS[whitePiece] = whitePiece + '-' + createId();
519 SPARE_PIECE_ELS_IDS[blackPiece] = blackPiece + '-' + createId();
523 //------------------------------------------------------------------------------
525 //------------------------------------------------------------------------------
527 function buildBoardContainer() {
528 var html = '<div class="' + CSS.chessboard + '">';
530 if (cfg.sparePieces === true) {
531 html += '<div class="' + CSS.sparePieces + ' ' +
532 CSS.sparePiecesTop + '"></div>';
535 html += '<div class="' + CSS.board + '"></div>';
537 if (cfg.sparePieces === true) {
538 html += '<div class="' + CSS.sparePieces + ' ' +
539 CSS.sparePiecesBottom + '"></div>';
548 var buildSquare = function(color, size, id) {
549 var html = '<div class="' + CSS.square + ' ' + CSSColor[color] + '" ' +
550 'style="width: ' + size + 'px; height: ' + size + 'px" ' +
553 if (cfg.showNotation === true) {
563 function buildBoard(orientation) {
564 if (orientation !== 'black') {
565 orientation = 'white';
570 // algebraic notation / orientation
571 var alpha = deepCopy(COLUMNS);
573 if (orientation === 'black') {
578 var squareColor = 'white';
579 for (var i = 0; i < 8; i++) {
580 html += '<div class="' + CSS.row + '">';
581 for (var j = 0; j < 8; j++) {
582 var square = alpha[j] + row;
584 html += '<div class="' + CSS.square + ' ' + CSSColor[squareColor] + ' ' +
585 'square-' + square + '" ' +
586 'style="width: ' + SQUARE_SIZE + 'px; height: ' + SQUARE_SIZE + 'px" ' +
587 'id="' + SQUARE_ELS_IDS[square] + '" ' +
588 'data-square="' + square + '">';
590 if (cfg.showNotation === true) {
592 if ((orientation === 'white' && row === 1) ||
593 (orientation === 'black' && row === 8)) {
594 html += '<div class="' + CSS.notation + ' ' + CSS.alpha + '">' +
600 html += '<div class="' + CSS.notation + ' ' + CSS.numeric + '">' +
605 html += '</div>'; // end .square
607 squareColor = (squareColor === 'white' ? 'black' : 'white');
609 html += '<div class="' + CSS.clearfix + '"></div></div>';
611 squareColor = (squareColor === 'white' ? 'black' : 'white');
613 if (orientation === 'white') {
624 function buildPieceImgSrc(piece) {
625 if (typeof cfg.pieceTheme === 'function') {
626 return cfg.pieceTheme(piece);
629 if (typeof cfg.pieceTheme === 'string') {
630 return cfg.pieceTheme.replace(/{piece}/g, piece);
633 // NOTE: this should never happen
634 error(8272, 'Unable to build image source for cfg.pieceTheme.');
639 * @param {!string} piece
640 * @param {boolean=} hidden
641 * @param {!string=} id
643 function buildPiece(piece, hidden, id) {
644 var html = '<img src="' + buildPieceImgSrc(piece) + '" ';
645 if (id && typeof id === 'string') {
646 html += 'id="' + id + '" ';
649 'class="' + CSS.piece + '" ' +
650 'data-piece="' + piece + '" ' +
651 'style="width: ' + SQUARE_SIZE + 'px;' +
652 'height: ' + SQUARE_SIZE + 'px;';
653 if (hidden === true) {
654 html += 'display:none;';
658 let elem = document.createElement('template');
659 elem.innerHTML = html;
663 function buildSparePieces(color) {
664 var pieces = ['wK', 'wQ', 'wR', 'wB', 'wN', 'wP'];
665 if (color === 'black') {
666 pieces = ['bK', 'bQ', 'bR', 'bB', 'bN', 'bP'];
670 for (var i = 0; i < pieces.length; i++) {
671 html += buildPiece(pieces[i], false, SPARE_PIECE_ELS_IDS[pieces[i]]);
677 //------------------------------------------------------------------------------
679 //------------------------------------------------------------------------------
681 function offset(el) { // From https://youmightnotneedjquery.com/.
682 let box = el.getBoundingClientRect();
683 let docElem = document.documentElement;
685 top: box.top + window.pageYOffset - docElem.clientTop,
686 left: box.left + window.pageXOffset - docElem.clientLeft
690 function animateSquareToSquare(src, dest, piece, completeFn) {
691 // get information about the source and destination squares
692 var srcSquareEl = document.getElementById(SQUARE_ELS_IDS[src]);
693 var srcSquarePosition = offset(srcSquareEl);
694 var destSquareEl = document.getElementById(SQUARE_ELS_IDS[dest]);
695 var destSquarePosition = offset(destSquareEl);
697 // create the animated piece and absolutely position it
698 // over the source square
699 var animatedPieceId = createId();
700 document.body.append(buildPiece(piece, true, animatedPieceId));
701 var animatedPieceEl = document.getElementById(animatedPieceId);
702 animatedPieceEl.style.display = null;
703 animatedPieceEl.style.position = 'absolute';
704 animatedPieceEl.style.top = srcSquarePosition.top + 'px';
705 animatedPieceEl.style.left = srcSquarePosition.left + 'px';
707 // remove original piece(s) from source square
708 // TODO: multiple pieces should never really happen, but it will if we are moving
709 // while another animation still isn't done
710 srcSquareEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
713 var complete = function() {
714 // add the "real" piece to the destination square
715 destSquareEl.append(buildPiece(piece));
717 // remove the animated piece
718 animatedPieceEl.remove();
720 // run complete function
721 if (typeof completeFn === 'function') {
726 // animate the piece to the destination square
727 animatedPieceEl.addEventListener('transitionend', complete, {once: true});
728 requestAnimationFrame(() => {
729 animatedPieceEl.style.transitionProperty = 'top, left';
730 animatedPieceEl.style.transitionDuration = cfg.moveSpeed + 'ms';
731 animatedPieceEl.style.top = destSquarePosition.top + 'px';
732 animatedPieceEl.style.left = destSquarePosition.left + 'px';
736 function animateSparePieceToSquare(piece, dest, completeFn) {
737 var srcOffset = offset(document.getelementById(SPARE_PIECE_ELS_IDS[piece]));
738 var destSquareEl = document.getElementById(SQUARE_ELS_IDS[dest]);
739 var destOffset = offset(destSquareEl);
741 // create the animate piece
742 var pieceId = createId();
743 document.body.append(buildPiece(piece, true, pieceId));
744 var animatedPieceEl = document.getElementById(pieceId);
745 animatedPieceEl.style.display = '';
746 animatedPieceEl.style.position = 'absolute';
747 animatedPieceEl.style.left = srcOffset.left;
748 animatedPieceEl.style.top = srcOffset.top;
751 var complete = function() {
752 // add the "real" piece to the destination square
753 destSquareEl.querySelector('.' + CSS.piece).remove();
754 destSquareEl.append(buildPiece(piece));
756 // remove the animated piece
757 animatedPieceEl.remove();
759 // run complete function
760 if (typeof completeFn === 'function') {
765 // animate the piece to the destination square
766 // FIXME: support this for non-jquery
768 duration: cfg.moveSpeed,
771 //$(animatedPieceEl).animate(destOffset, opts);
774 function fadeIn(piece, onFinish) {
775 piece.style.opacity = 0;
776 piece.style.display = null;
777 piece.addEventListener('transitionend', onFinish, {once: true});
778 requestAnimationFrame(() => {
779 piece.style.transitionProperty = 'opacity';
780 piece.style.transitionDuration = cfg.appearSpeed + 'ms';
781 piece.style.opacity = 1;
785 function fadeOut(piece, onFinish) {
786 piece.style.opacity = 1;
787 piece.style.display = null;
788 piece.addEventListener('transitionend', onFinish, {once: true});
789 requestAnimationFrame(() => {
790 piece.style.transitionProperty = 'opacity';
791 piece.style.transitionDuration = cfg.trashSpeed + 'ms';
792 piece.style.opacity = 0;
796 // execute an array of animations
797 function doAnimations(a, oldPos, newPos) {
798 ANIMATION_HAPPENING = true;
801 function onFinish(e) {
803 e.target.transitionProperty = null;
808 // exit if all the animations aren't finished
809 if (numFinished !== a.length) return;
811 drawPositionInstant();
812 ANIMATION_HAPPENING = false;
814 // run their onMoveEnd function
815 if (cfg.hasOwnProperty('onMoveEnd') === true &&
816 typeof cfg.onMoveEnd === 'function') {
817 cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
821 requestAnimationFrame(() => { // Firefox workaround.
822 for (var i = 0; i < a.length; i++) {
824 if (a[i].type === 'clear') {
825 document.getElementById(SQUARE_ELS_IDS[a[i].square]).querySelectorAll('.' + CSS.piece).forEach(
826 (piece) => fadeOut(piece, onFinish)
830 // add a piece (no spare pieces)
831 if (a[i].type === 'add' && cfg.sparePieces !== true) {
832 let square = document.getElementById(SQUARE_ELS_IDS[a[i].square]);
833 square.append(buildPiece(a[i].piece, true));
834 let piece = square.querySelector('.' + CSS.piece);
835 fadeIn(piece, onFinish);
838 // add a piece from a spare piece
839 if (a[i].type === 'add' && cfg.sparePieces === true) {
840 animateSparePieceToSquare(a[i].piece, a[i].square, onFinish);
844 if (a[i].type === 'move') {
845 animateSquareToSquare(a[i].source, a[i].destination, a[i].piece,
852 // returns the distance between two squares
853 function squareDistance(s1, s2) {
855 var s1x = COLUMNS.indexOf(s1[0]) + 1;
856 var s1y = parseInt(s1[1], 10);
859 var s2x = COLUMNS.indexOf(s2[0]) + 1;
860 var s2y = parseInt(s2[1], 10);
862 var xDelta = Math.abs(s1x - s2x);
863 var yDelta = Math.abs(s1y - s2y);
865 if (xDelta >= yDelta) return xDelta;
869 // returns an array of closest squares from square
870 function createRadius(square) {
873 // calculate distance of all squares
874 for (var i = 0; i < 8; i++) {
875 for (var j = 0; j < 8; j++) {
876 var s = COLUMNS[i] + (j + 1);
878 // skip the square we're starting from
879 if (square === s) continue;
883 distance: squareDistance(square, s)
889 squares.sort(function(a, b) {
890 return a.distance - b.distance;
893 // just return the square code
895 for (var i = 0; i < squares.length; i++) {
896 squares2.push(squares[i].square);
902 // returns the square of the closest instance of piece
903 // returns false if no instance of piece is found in position
904 function findClosestPiece(position, piece, square) {
905 // create array of closest squares from square
906 var closestSquares = createRadius(square);
908 // search through the position in order of distance for the piece
909 for (var i = 0; i < closestSquares.length; i++) {
910 var s = closestSquares[i];
912 if (position.hasOwnProperty(s) === true && position[s] === piece) {
920 // calculate an array of animations that need to happen in order to get
922 function calculateAnimations(pos1, pos2) {
923 // make copies of both
924 pos1 = deepCopy(pos1);
925 pos2 = deepCopy(pos2);
928 var squaresMovedTo = {};
930 // remove pieces that are the same in both positions
931 for (var i in pos2) {
932 if (pos2.hasOwnProperty(i) !== true) continue;
934 if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
940 // find all the "move" animations
941 for (var i in pos2) {
942 if (pos2.hasOwnProperty(i) !== true) continue;
944 var closestPiece = findClosestPiece(pos1, pos2[i], i);
945 if (closestPiece !== false) {
948 source: closestPiece,
953 delete pos1[closestPiece];
955 squaresMovedTo[i] = true;
959 // add pieces to pos2
960 for (var i in pos2) {
961 if (pos2.hasOwnProperty(i) !== true) continue;
972 // clear pieces from pos1
973 for (var i in pos1) {
974 if (pos1.hasOwnProperty(i) !== true) continue;
976 // do not clear a piece if it is on a square that is the result
977 // of a "move", ie: a piece capture
978 if (squaresMovedTo.hasOwnProperty(i) === true) continue;
992 //------------------------------------------------------------------------------
994 //------------------------------------------------------------------------------
996 function drawPositionInstant() {
998 boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
1001 for (var i in CURRENT_POSITION) {
1002 if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue;
1004 document.getElementById(SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i]));
1008 function drawBoard() {
1009 boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
1010 drawPositionInstant();
1012 if (cfg.sparePieces === true) {
1013 if (CURRENT_ORIENTATION === 'white') {
1014 sparePiecesTopEl.innerHTML = buildSparePieces('black');
1015 sparePiecesBottomEl.innerHTML = buildSparePieces('white');
1018 sparePiecesTopEl.innerHTML = buildSparePieces('white');
1019 sparePiecesBottomEl.innerHTML = buildSparePieces('black');
1024 // given a position and a set of moves, return a new position
1025 // with the moves executed
1026 function calculatePositionFromMoves(position, moves) {
1027 position = deepCopy(position);
1029 for (var i in moves) {
1030 if (moves.hasOwnProperty(i) !== true) continue;
1032 // skip the move if the position doesn't have a piece on the source square
1033 if (position.hasOwnProperty(i) !== true) continue;
1035 var piece = position[i];
1037 position[moves[i]] = piece;
1043 function setCurrentPosition(position) {
1044 var oldPos = deepCopy(CURRENT_POSITION);
1045 var newPos = deepCopy(position);
1046 var oldFen = objToFen(oldPos);
1047 var newFen = objToFen(newPos);
1049 // do nothing if no change in position
1050 if (oldFen === newFen) return;
1052 // run their onChange function
1053 if (cfg.hasOwnProperty('onChange') === true &&
1054 typeof cfg.onChange === 'function') {
1055 cfg.onChange(oldPos, newPos);
1059 CURRENT_POSITION = position;
1062 function isXYOnSquare(x, y) {
1063 for (var i in SQUARE_ELS_OFFSETS) {
1064 if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue;
1066 var s = SQUARE_ELS_OFFSETS[i];
1067 if (x >= s.left && x < s.left + SQUARE_SIZE &&
1068 y >= s.top && y < s.top + SQUARE_SIZE) {
1076 // records the XY coords of every square into memory
1077 function captureSquareOffsets() {
1078 SQUARE_ELS_OFFSETS = {};
1080 for (var i in SQUARE_ELS_IDS) {
1081 if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue;
1083 SQUARE_ELS_OFFSETS[i] = offset(document.getElementById(SQUARE_ELS_IDS[i]));
1087 function removeSquareHighlights() {
1088 boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
1089 piece.classList.remove(CSS.highlight1);
1090 piece.classList.remove(CSS.highlight2);
1094 function snapbackDraggedPiece() {
1095 // there is no "snapback" for spare pieces
1096 if (DRAGGED_PIECE_SOURCE === 'spare') {
1097 trashDraggedPiece();
1101 removeSquareHighlights();
1103 // animation complete
1104 function complete() {
1105 drawPositionInstant();
1106 draggedPieceEl.style.display = 'none';
1108 // run their onSnapbackEnd function
1109 if (cfg.hasOwnProperty('onSnapbackEnd') === true &&
1110 typeof cfg.onSnapbackEnd === 'function') {
1111 cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
1112 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1116 // get source square position
1117 var sourceSquarePosition =
1118 offset(document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]));
1120 // animate the piece to the target square
1121 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1122 requestAnimationFrame(() => {
1123 draggedPieceEl.style.transitionProperty = 'top, left';
1124 draggedPieceEl.style.transitionDuration = cfg.snapbackSpeed + 'ms';
1125 draggedPieceEl.style.top = sourceSquarePosition.top + 'px';
1126 draggedPieceEl.style.left = sourceSquarePosition.left + 'px';
1130 DRAGGING_A_PIECE = false;
1133 function trashDraggedPiece() {
1134 removeSquareHighlights();
1136 // remove the source piece
1137 var newPosition = deepCopy(CURRENT_POSITION);
1138 delete newPosition[DRAGGED_PIECE_SOURCE];
1139 setCurrentPosition(newPosition);
1141 // redraw the position
1142 drawPositionInstant();
1144 // hide the dragged piece
1145 // FIXME: support this for non-jquery
1146 //$(draggedPieceEl).fadeOut(cfg.trashSpeed);
1149 DRAGGING_A_PIECE = false;
1152 function dropDraggedPieceOnSquare(square) {
1153 removeSquareHighlights();
1156 var newPosition = deepCopy(CURRENT_POSITION);
1157 delete newPosition[DRAGGED_PIECE_SOURCE];
1158 newPosition[square] = DRAGGED_PIECE;
1159 setCurrentPosition(newPosition);
1161 // get target square information
1162 var targetSquarePosition = offset(document.getElementById(SQUARE_ELS_IDS[square]));
1164 // animation complete
1165 var complete = function() {
1166 drawPositionInstant();
1167 draggedPieceEl.style.display = 'none';
1169 // execute their onSnapEnd function
1170 if (cfg.hasOwnProperty('onSnapEnd') === true &&
1171 typeof cfg.onSnapEnd === 'function') {
1172 requestAnimationFrame(() => { // HACK: so that we don't add event handlers from the callback...
1173 cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
1178 // snap the piece to the target square
1179 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1180 requestAnimationFrame(() => {
1181 draggedPieceEl.style.transitionProperty = 'top, left';
1182 draggedPieceEl.style.transitionDuration = cfg.snapSpeed + 'ms';
1183 draggedPieceEl.style.top = targetSquarePosition.top + 'px';
1184 draggedPieceEl.style.left = targetSquarePosition.left + 'px';
1188 DRAGGING_A_PIECE = false;
1191 function beginDraggingPiece(source, piece, x, y) {
1192 // run their custom onDragStart function
1193 // their custom onDragStart function can cancel drag start
1194 if (typeof cfg.onDragStart === 'function' &&
1195 cfg.onDragStart(source, piece,
1196 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
1201 DRAGGING_A_PIECE = true;
1202 DRAGGED_PIECE = piece;
1203 DRAGGED_PIECE_SOURCE = source;
1205 // if the piece came from spare pieces, location is offboard
1206 if (source === 'spare') {
1207 DRAGGED_PIECE_LOCATION = 'offboard';
1210 DRAGGED_PIECE_LOCATION = source;
1213 // capture the x, y coords of all squares in memory
1214 captureSquareOffsets();
1216 // create the dragged piece
1217 draggedPieceEl.setAttribute('src', buildPieceImgSrc(piece));
1218 draggedPieceEl.style.display = null;
1219 draggedPieceEl.style.position = 'absolute';
1220 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1221 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1223 if (source !== 'spare') {
1224 // highlight the source square and hide the piece
1225 let square = document.getElementById(SQUARE_ELS_IDS[source]);
1226 square.classList.add(CSS.highlight1);
1227 square.querySelector('.' + CSS.piece).style.display = 'none';
1231 function updateDraggedPiece(x, y) {
1232 // put the dragged piece over the mouse cursor
1233 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1234 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1237 var location = isXYOnSquare(x, y);
1239 // do nothing if the location has not changed
1240 if (location === DRAGGED_PIECE_LOCATION) return;
1242 // remove highlight from previous square
1243 if (validSquare(DRAGGED_PIECE_LOCATION) === true) {
1244 document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION])
1245 .classList.remove(CSS.highlight2);
1248 // add highlight to new square
1249 if (validSquare(location) === true) {
1250 document.getElementById(SQUARE_ELS_IDS[location]).classList.add(CSS.highlight2);
1254 if (typeof cfg.onDragMove === 'function') {
1255 cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1256 DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1257 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1261 DRAGGED_PIECE_LOCATION = location;
1264 function stopDraggedPiece(location) {
1265 // determine what the action should be
1266 var action = 'drop';
1267 if (location === 'offboard' && cfg.dropOffBoard === 'snapback') {
1268 action = 'snapback';
1270 if (location === 'offboard' && cfg.dropOffBoard === 'trash') {
1274 // run their onDrop function, which can potentially change the drop action
1275 if (cfg.hasOwnProperty('onDrop') === true &&
1276 typeof cfg.onDrop === 'function') {
1277 var newPosition = deepCopy(CURRENT_POSITION);
1279 // source piece is a spare piece and position is off the board
1280 //if (DRAGGED_PIECE_SOURCE === 'spare' && location === 'offboard') {...}
1281 // position has not changed; do nothing
1283 // source piece is a spare piece and position is on the board
1284 if (DRAGGED_PIECE_SOURCE === 'spare' && validSquare(location) === true) {
1285 // add the piece to the board
1286 newPosition[location] = DRAGGED_PIECE;
1289 // source piece was on the board and position is off the board
1290 if (validSquare(DRAGGED_PIECE_SOURCE) === true && location === 'offboard') {
1291 // remove the piece from the board
1292 delete newPosition[DRAGGED_PIECE_SOURCE];
1295 // source piece was on the board and position is on the board
1296 if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1297 validSquare(location) === true) {
1299 delete newPosition[DRAGGED_PIECE_SOURCE];
1300 newPosition[location] = DRAGGED_PIECE;
1303 var oldPosition = deepCopy(CURRENT_POSITION);
1305 var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE,
1306 newPosition, oldPosition, CURRENT_ORIENTATION);
1307 if (result === 'snapback' || result === 'trash') {
1313 if (action === 'snapback') {
1314 snapbackDraggedPiece();
1316 else if (action === 'trash') {
1317 trashDraggedPiece();
1319 else if (action === 'drop') {
1320 dropDraggedPieceOnSquare(location);
1324 //------------------------------------------------------------------------------
1326 //------------------------------------------------------------------------------
1329 widget.clear = function(useAnimation) {
1330 widget.position({}, useAnimation);
1334 // get or set config properties
1335 // TODO: write this, GitHub Issue #1
1336 widget.config = function(arg1, arg2) {
1337 // get the current config
1338 if (arguments.length === 0) {
1339 return deepCopy(cfg);
1344 // remove the widget from the page
1345 widget.destroy = function() {
1347 containerEl.innerHTML = '';
1348 draggedPieceEl.remove();
1351 // shorthand method to get the current FEN
1352 widget.fen = function() {
1353 return widget.position('fen');
1357 widget.flip = function() {
1358 widget.orientation('flip');
1362 // TODO: write this, GitHub Issue #5
1363 widget.highlight = function() {
1369 widget.move = function() {
1370 // no need to throw an error here; just do nothing
1371 if (arguments.length === 0) return;
1373 var useAnimation = true;
1375 // collect the moves into an object
1377 for (var i = 0; i < arguments.length; i++) {
1378 // any "false" to this function means no animations
1379 if (arguments[i] === false) {
1380 useAnimation = false;
1384 // skip invalid arguments
1385 if (validMove(arguments[i]) !== true) {
1386 error(2826, 'Invalid move passed to the move method.', arguments[i]);
1390 var tmp = arguments[i].split('-');
1391 moves[tmp[0]] = tmp[1];
1394 // calculate position from moves
1395 var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1398 widget.position(newPos, useAnimation);
1400 // return the new position object
1404 widget.orientation = function(arg) {
1405 // no arguments, return the current orientation
1406 if (arguments.length === 0) {
1407 return CURRENT_ORIENTATION;
1410 // set to white or black
1411 if (arg === 'white' || arg === 'black') {
1412 CURRENT_ORIENTATION = arg;
1418 if (arg === 'flip') {
1419 CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1424 error(5482, 'Invalid value passed to the orientation method.', arg);
1428 * @param {!string|!Object} position
1429 * @param {boolean=} useAnimation
1431 widget.position = function(position, useAnimation) {
1432 // no arguments, return the current position
1433 if (arguments.length === 0) {
1434 return deepCopy(CURRENT_POSITION);
1437 // get position as FEN
1438 if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1439 return objToFen(CURRENT_POSITION);
1442 // default for useAnimations is true
1443 if (useAnimation !== false) {
1444 useAnimation = true;
1448 if (typeof position === 'string' && position.toLowerCase() === 'start') {
1449 position = deepCopy(START_POSITION);
1452 // convert FEN to position object
1453 if (validFen(position) === true) {
1454 position = fenToObj(position);
1457 // validate position object
1458 if (validPositionObject(position) !== true) {
1459 error(6482, 'Invalid value passed to the position method.', position);
1463 if (useAnimation === true) {
1464 // start the animations
1465 doAnimations(calculateAnimations(CURRENT_POSITION, position),
1466 CURRENT_POSITION, position);
1468 // set the new position
1469 setCurrentPosition(position);
1473 setCurrentPosition(position);
1474 drawPositionInstant();
1478 widget.resize = function() {
1479 // calulate the new square size
1480 SQUARE_SIZE = calculateSquareSize();
1483 boardEl.style.width = (SQUARE_SIZE * 8) + 'px';
1485 // set drag piece size
1486 if (draggedPieceEl !== null) {
1487 draggedPieceEl.style.height = SQUARE_SIZE + 'px';
1488 draggedPieceEl.style.width = SQUARE_SIZE + 'px';
1492 if (cfg.sparePieces === true) {
1493 containerEl.querySelector('.' + CSS.sparePieces)
1494 .style.paddingLeft = (SQUARE_SIZE + BOARD_BORDER_SIZE) + 'px';
1501 // set the starting position
1502 widget.start = function(useAnimation) {
1503 widget.position('start', useAnimation);
1506 //------------------------------------------------------------------------------
1508 //------------------------------------------------------------------------------
1510 function isTouchDevice() {
1511 return ('ontouchstart' in document.documentElement);
1514 function mousedownSquare(e) {
1515 let target = e.target.closest('.' + CSS.square);
1520 // do nothing if we're not draggable
1521 if (cfg.draggable !== true) return;
1523 var square = target.getAttribute('data-square');
1525 // no piece on this square
1526 if (validSquare(square) !== true ||
1527 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1531 beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1534 function touchstartSquare(e) {
1535 let target = e.target.closest('.' + CSS.square);
1540 // do nothing if we're not draggable
1541 if (cfg.draggable !== true) return;
1543 var square = target.getAttribute('data-square');
1545 // no piece on this square
1546 if (validSquare(square) !== true ||
1547 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1551 e = e.originalEvent;
1552 beginDraggingPiece(square, CURRENT_POSITION[square],
1553 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1556 function mousedownSparePiece(e) {
1557 if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1561 // do nothing if sparePieces is not enabled
1562 if (cfg.sparePieces !== true) return;
1564 var piece = e.target.getAttribute('data-piece');
1566 beginDraggingPiece('spare', piece, e.pageX, e.pageY);
1569 function touchstartSparePiece(e) {
1570 if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1574 // do nothing if sparePieces is not enabled
1575 if (cfg.sparePieces !== true) return;
1577 var piece = e.target.getAttribute('data-piece');
1579 e = e.originalEvent;
1580 beginDraggingPiece('spare', piece,
1581 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1584 function mousemoveWindow(e) {
1585 // do nothing if we are not dragging a piece
1586 if (DRAGGING_A_PIECE !== true) return;
1588 updateDraggedPiece(e.pageX, e.pageY);
1591 function touchmoveWindow(e) {
1592 // do nothing if we are not dragging a piece
1593 if (DRAGGING_A_PIECE !== true) return;
1595 // prevent screen from scrolling
1598 updateDraggedPiece(e.originalEvent.changedTouches[0].pageX,
1599 e.originalEvent.changedTouches[0].pageY);
1602 function mouseupWindow(e) {
1603 // do nothing if we are not dragging a piece
1604 if (DRAGGING_A_PIECE !== true) return;
1607 var location = isXYOnSquare(e.pageX, e.pageY);
1609 stopDraggedPiece(location);
1612 function touchendWindow(e) {
1613 // do nothing if we are not dragging a piece
1614 if (DRAGGING_A_PIECE !== true) return;
1617 var location = isXYOnSquare(e.originalEvent.changedTouches[0].pageX,
1618 e.originalEvent.changedTouches[0].pageY);
1620 stopDraggedPiece(location);
1623 function mouseenterSquare(e) {
1624 let target = e.target.closest('.' + CSS.square);
1629 // do not fire this event if we are dragging a piece
1630 // NOTE: this should never happen, but it's a safeguard
1631 if (DRAGGING_A_PIECE !== false) return;
1633 if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1634 typeof cfg.onMouseoverSquare !== 'function') return;
1637 var square = target.getAttribute('data-square');
1639 // NOTE: this should never happen; defensive
1640 if (validSquare(square) !== true) return;
1642 // get the piece on this square
1644 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1645 piece = CURRENT_POSITION[square];
1648 // execute their function
1649 cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1650 CURRENT_ORIENTATION);
1653 function mouseleaveSquare(e) {
1654 let target = e.target.closest('.' + CSS.square);
1659 // do not fire this event if we are dragging a piece
1660 // NOTE: this should never happen, but it's a safeguard
1661 if (DRAGGING_A_PIECE !== false) return;
1663 if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1664 typeof cfg.onMouseoutSquare !== 'function') return;
1667 var square = target.getAttribute('data-square');
1669 // NOTE: this should never happen; defensive
1670 if (validSquare(square) !== true) return;
1672 // get the piece on this square
1674 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1675 piece = CURRENT_POSITION[square];
1678 // execute their function
1679 cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1680 CURRENT_ORIENTATION);
1683 //------------------------------------------------------------------------------
1685 //------------------------------------------------------------------------------
1687 function addEvents() {
1688 // prevent browser "image drag"
1689 let stopDefault = (e) => {
1690 if (e.target.matches('.' + CSS.piece)) {
1694 document.body.addEventListener('mousedown', stopDefault);
1695 document.body.addEventListener('mousemove', stopDefault);
1697 // mouse drag pieces
1698 boardEl.addEventListener('mousedown', mousedownSquare);
1699 containerEl.addEventListener('mousedown', mousedownSparePiece);
1701 // mouse enter / leave square
1702 boardEl.addEventListener('mouseenter', mouseenterSquare);
1703 boardEl.addEventListener('mouseleave', mouseleaveSquare);
1705 window.addEventListener('mousemove', mousemoveWindow);
1706 window.addEventListener('mouseup', mouseupWindow);
1708 // touch drag pieces
1709 if (isTouchDevice() === true) {
1710 boardEl.addEventListener('touchstart', touchstartSquare);
1711 containerEl.addEventListener('touchstart', touchstartSparePiece);
1712 window.addEventListener('touchmove', touchmoveWindow);
1713 window.addEventListener('touchend', touchendWindow);
1717 function initDom() {
1718 // build board and save it in memory
1719 containerEl.innerHTML = buildBoardContainer();
1720 boardEl = containerEl.querySelector('.' + CSS.board);
1722 if (cfg.sparePieces === true) {
1723 sparePiecesTopEl = containerEl.querySelector('.' + CSS.sparePiecesTop);
1724 sparePiecesBottomEl = containerEl.querySelector('.' + CSS.sparePiecesBottom);
1727 // create the drag piece
1728 var draggedPieceId = createId();
1729 document.body.append(buildPiece('wP', true, draggedPieceId));
1730 draggedPieceEl = document.getElementById(draggedPieceId);
1732 // get the border size
1733 BOARD_BORDER_SIZE = parseInt(boardEl.style.borderLeftWidth, 10);
1735 // set the size and draw the board
1740 if (checkDeps() !== true ||
1741 expandConfig() !== true) return;
1743 // create unique IDs for all the elements we will create
1753 // return the widget object
1756 }; // end window.ChessBoard
1758 // expose util functions
1759 window.ChessBoard.fenToObj = fenToObj;
1760 window.ChessBoard.objToFen = objToFen;
1762 })(); // end anonymous wrapper