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 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 let img = document.createElement('img');
644 img.src = buildPieceImgSrc(piece);
645 if (id && typeof id === 'string') {
646 img.setAttribute('id', id);
648 img.setAttribute('alt', '');
649 img.classList.add(CSS.piece);
650 img.setAttribute('data-piece', piece);
651 img.style.width = SQUARE_SIZE + 'px';
652 img.style.height = SQUARE_SIZE + 'px';
653 if (hidden === true) {
654 img.style.display = 'none';
659 function buildSparePieces(color) {
660 var pieces = ['wK', 'wQ', 'wR', 'wB', 'wN', 'wP'];
661 if (color === 'black') {
662 pieces = ['bK', 'bQ', 'bR', 'bB', 'bN', 'bP'];
666 for (var i = 0; i < pieces.length; i++) {
667 html += buildPiece(pieces[i], false, SPARE_PIECE_ELS_IDS[pieces[i]]);
673 //------------------------------------------------------------------------------
675 //------------------------------------------------------------------------------
677 function offset(el) { // From https://youmightnotneedjquery.com/.
678 let box = el.getBoundingClientRect();
679 let docElem = document.documentElement;
681 top: box.top + window.pageYOffset - docElem.clientTop,
682 left: box.left + window.pageXOffset - docElem.clientLeft
686 function animateSquareToSquare(src, dest, piece, completeFn) {
687 // get information about the source and destination squares
688 var srcSquareEl = document.getElementById(SQUARE_ELS_IDS[src]);
689 var srcSquarePosition = offset(srcSquareEl);
690 var destSquareEl = document.getElementById(SQUARE_ELS_IDS[dest]);
691 var destSquarePosition = offset(destSquareEl);
693 // create the animated piece and absolutely position it
694 // over the source square
695 var animatedPieceId = createId();
696 document.body.append(buildPiece(piece, true, animatedPieceId));
697 var animatedPieceEl = document.getElementById(animatedPieceId);
698 animatedPieceEl.style.display = null;
699 animatedPieceEl.style.position = 'absolute';
700 animatedPieceEl.style.top = srcSquarePosition.top + 'px';
701 animatedPieceEl.style.left = srcSquarePosition.left + 'px';
703 // remove original piece(s) from source square
704 // TODO: multiple pieces should never really happen, but it will if we are moving
705 // while another animation still isn't done
706 srcSquareEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
709 var complete = function() {
710 // add the "real" piece to the destination square
711 destSquareEl.append(buildPiece(piece));
713 // remove the animated piece
714 animatedPieceEl.remove();
716 // run complete function
717 if (typeof completeFn === 'function') {
722 // animate the piece to the destination square
723 animatedPieceEl.addEventListener('transitionend', complete, {once: true});
724 requestAnimationFrame(() => {
725 animatedPieceEl.style.transitionProperty = 'top, left';
726 animatedPieceEl.style.transitionDuration = cfg.moveSpeed + 'ms';
727 animatedPieceEl.style.top = destSquarePosition.top + 'px';
728 animatedPieceEl.style.left = destSquarePosition.left + 'px';
732 function animateSparePieceToSquare(piece, dest, completeFn) {
733 var srcOffset = offset(document.getelementById(SPARE_PIECE_ELS_IDS[piece]));
734 var destSquareEl = document.getElementById(SQUARE_ELS_IDS[dest]);
735 var destOffset = offset(destSquareEl);
737 // create the animate piece
738 var pieceId = createId();
739 document.body.append(buildPiece(piece, true, pieceId));
740 var animatedPieceEl = document.getElementById(pieceId);
741 animatedPieceEl.style.display = '';
742 animatedPieceEl.style.position = 'absolute';
743 animatedPieceEl.style.left = srcOffset.left;
744 animatedPieceEl.style.top = srcOffset.top;
747 var complete = function() {
748 // add the "real" piece to the destination square
749 destSquareEl.querySelector('.' + CSS.piece).remove();
750 destSquareEl.append(buildPiece(piece));
752 // remove the animated piece
753 animatedPieceEl.remove();
755 // run complete function
756 if (typeof completeFn === 'function') {
761 // animate the piece to the destination square
762 // FIXME: support this for non-jquery
764 duration: cfg.moveSpeed,
767 //$(animatedPieceEl).animate(destOffset, opts);
770 function fadeIn(pieces, onFinish) {
771 pieces.forEach((piece) => {
772 piece.style.opacity = 0;
773 piece.style.display = null;
774 piece.addEventListener('transitionend', onFinish, {once: true});
776 requestAnimationFrame(() => {
777 pieces.forEach((piece) => {
778 piece.style.transitionProperty = 'opacity';
779 piece.style.transitionDuration = cfg.appearSpeed + 'ms';
780 piece.style.opacity = 1;
785 function fadeOut(pieces, onFinish) {
786 pieces.forEach((piece) => {
787 piece.style.opacity = 1;
788 piece.style.display = null;
789 piece.addEventListener('transitionend', onFinish, {once: true});
791 requestAnimationFrame(() => {
792 pieces.forEach((piece) => {
793 piece.style.transitionProperty = 'opacity';
794 piece.style.transitionDuration = cfg.trashSpeed + 'ms';
795 piece.style.opacity = 0;
800 // execute an array of animations
801 function doAnimations(a, oldPos, newPos) {
803 function onFinish(e) {
805 e.target.transitionProperty = null;
810 // exit if all the animations aren't finished
811 if (numFinished !== a.length) return;
813 drawPositionInstant();
815 // run their onMoveEnd function
816 if (cfg.hasOwnProperty('onMoveEnd') === true &&
817 typeof cfg.onMoveEnd === 'function') {
818 cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
822 requestAnimationFrame(() => { // Firefox workaround.
823 let fadeout_pieces = [];
824 let fadein_pieces = [];
826 for (var i = 0; i < a.length; i++) {
828 if (a[i].type === 'clear') {
829 document.getElementById(SQUARE_ELS_IDS[a[i].square]).querySelectorAll('.' + CSS.piece).forEach(
830 (piece) => fadeout_pieces.push(piece)
834 // add a piece (no spare pieces)
835 if (a[i].type === 'add' && cfg.sparePieces !== true) {
836 let square = document.getElementById(SQUARE_ELS_IDS[a[i].square]);
837 square.append(buildPiece(a[i].piece, true));
838 let piece = square.querySelector('.' + CSS.piece);
839 fadein_pieces.push(piece);
842 // add a piece from a spare piece
843 if (a[i].type === 'add' && cfg.sparePieces === true) {
844 animateSparePieceToSquare(a[i].piece, a[i].square, onFinish);
848 if (a[i].type === 'move') {
849 animateSquareToSquare(a[i].source, a[i].destination, a[i].piece,
854 // TODO: Batch moves as well, not just fade in/out.
855 // (We batch them because requestAnimationFrame seemingly costs real time.)
856 if (fadeout_pieces.length > 0) {
857 fadeOut(fadeout_pieces, onFinish);
859 if (fadein_pieces.length > 0) {
860 fadeIn(fadein_pieces, onFinish);
865 // returns the distance between two squares
866 function squareDistance(s1, s2) {
868 var s1x = COLUMNS.indexOf(s1[0]) + 1;
869 var s1y = parseInt(s1[1], 10);
872 var s2x = COLUMNS.indexOf(s2[0]) + 1;
873 var s2y = parseInt(s2[1], 10);
875 var xDelta = Math.abs(s1x - s2x);
876 var yDelta = Math.abs(s1y - s2y);
878 if (xDelta >= yDelta) return xDelta;
882 // returns the square of the closest instance of piece
883 // returns false if no instance of piece is found in position
884 function findClosestPiece(position, piece, square) {
885 let best_square = false;
887 for (var i = 0; i < COLUMNS.length; i++) {
888 for (var j = 1; j <= 8; j++) {
889 let other_square = COLUMNS[i] + j;
891 if (position[other_square] === piece && square != other_square) {
892 let dist = squareDistance(square, other_square);
893 if (dist < best_dist) {
894 best_square = other_square;
904 // calculate an array of animations that need to happen in order to get
906 function calculateAnimations(pos1, pos2) {
907 // make copies of both
908 pos1 = deepCopy(pos1);
909 pos2 = deepCopy(pos2);
912 var squaresMovedTo = {};
914 // remove pieces that are the same in both positions
915 for (var i in pos2) {
916 if (pos2.hasOwnProperty(i) !== true) continue;
918 if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
924 // find all the "move" animations
925 for (var i in pos2) {
926 if (pos2.hasOwnProperty(i) !== true) continue;
928 var closestPiece = findClosestPiece(pos1, pos2[i], i);
929 if (closestPiece !== false) {
932 source: closestPiece,
937 delete pos1[closestPiece];
939 squaresMovedTo[i] = true;
943 // add pieces to pos2
944 for (var i in pos2) {
945 if (pos2.hasOwnProperty(i) !== true) continue;
956 // clear pieces from pos1
957 for (var i in pos1) {
958 if (pos1.hasOwnProperty(i) !== true) continue;
960 // do not clear a piece if it is on a square that is the result
961 // of a "move", ie: a piece capture
962 if (squaresMovedTo.hasOwnProperty(i) === true) continue;
976 //------------------------------------------------------------------------------
978 //------------------------------------------------------------------------------
980 function drawPositionInstant() {
982 boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
985 for (var i in CURRENT_POSITION) {
986 if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue;
988 document.getElementById(SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i]));
992 function drawBoard() {
993 boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
994 drawPositionInstant();
996 if (cfg.sparePieces === true) {
997 if (CURRENT_ORIENTATION === 'white') {
998 sparePiecesTopEl.innerHTML = buildSparePieces('black');
999 sparePiecesBottomEl.innerHTML = buildSparePieces('white');
1002 sparePiecesTopEl.innerHTML = buildSparePieces('white');
1003 sparePiecesBottomEl.innerHTML = buildSparePieces('black');
1008 // given a position and a set of moves, return a new position
1009 // with the moves executed
1010 function calculatePositionFromMoves(position, moves) {
1011 position = deepCopy(position);
1013 for (var i in moves) {
1014 if (moves.hasOwnProperty(i) !== true) continue;
1016 // skip the move if the position doesn't have a piece on the source square
1017 if (position.hasOwnProperty(i) !== true) continue;
1019 var piece = position[i];
1021 position[moves[i]] = piece;
1027 function setCurrentPosition(position) {
1028 var oldPos = deepCopy(CURRENT_POSITION);
1029 var newPos = deepCopy(position);
1030 var oldFen = objToFen(oldPos);
1031 var newFen = objToFen(newPos);
1033 // do nothing if no change in position
1034 if (oldFen === newFen) return;
1036 // run their onChange function
1037 if (cfg.hasOwnProperty('onChange') === true &&
1038 typeof cfg.onChange === 'function') {
1039 cfg.onChange(oldPos, newPos);
1043 CURRENT_POSITION = position;
1046 function isXYOnSquare(x, y) {
1047 for (var i in SQUARE_ELS_OFFSETS) {
1048 if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue;
1050 var s = SQUARE_ELS_OFFSETS[i];
1051 if (x >= s.left && x < s.left + SQUARE_SIZE &&
1052 y >= s.top && y < s.top + SQUARE_SIZE) {
1060 // records the XY coords of every square into memory
1061 function captureSquareOffsets() {
1062 SQUARE_ELS_OFFSETS = {};
1064 for (var i in SQUARE_ELS_IDS) {
1065 if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue;
1067 SQUARE_ELS_OFFSETS[i] = offset(document.getElementById(SQUARE_ELS_IDS[i]));
1071 function removeSquareHighlights() {
1072 boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
1073 piece.classList.remove(CSS.highlight1);
1074 piece.classList.remove(CSS.highlight2);
1078 function snapbackDraggedPiece() {
1079 // there is no "snapback" for spare pieces
1080 if (DRAGGED_PIECE_SOURCE === 'spare') {
1081 trashDraggedPiece();
1085 removeSquareHighlights();
1087 // animation complete
1088 function complete() {
1089 drawPositionInstant();
1090 draggedPieceEl.style.display = 'none';
1092 // run their onSnapbackEnd function
1093 if (cfg.hasOwnProperty('onSnapbackEnd') === true &&
1094 typeof cfg.onSnapbackEnd === 'function') {
1095 cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
1096 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1100 // get source square position
1101 var sourceSquarePosition =
1102 offset(document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]));
1104 // animate the piece to the target square
1105 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1106 requestAnimationFrame(() => {
1107 draggedPieceEl.style.transitionProperty = 'top, left';
1108 draggedPieceEl.style.transitionDuration = cfg.snapbackSpeed + 'ms';
1109 draggedPieceEl.style.top = sourceSquarePosition.top + 'px';
1110 draggedPieceEl.style.left = sourceSquarePosition.left + 'px';
1114 DRAGGING_A_PIECE = false;
1117 function trashDraggedPiece() {
1118 removeSquareHighlights();
1120 // remove the source piece
1121 var newPosition = deepCopy(CURRENT_POSITION);
1122 delete newPosition[DRAGGED_PIECE_SOURCE];
1123 setCurrentPosition(newPosition);
1125 // redraw the position
1126 drawPositionInstant();
1128 // hide the dragged piece
1129 // FIXME: support this for non-jquery
1130 //$(draggedPieceEl).fadeOut(cfg.trashSpeed);
1133 DRAGGING_A_PIECE = false;
1136 function dropDraggedPieceOnSquare(square) {
1137 removeSquareHighlights();
1140 var newPosition = deepCopy(CURRENT_POSITION);
1141 delete newPosition[DRAGGED_PIECE_SOURCE];
1142 newPosition[square] = DRAGGED_PIECE;
1143 setCurrentPosition(newPosition);
1145 // get target square information
1146 var targetSquarePosition = offset(document.getElementById(SQUARE_ELS_IDS[square]));
1148 // animation complete
1149 var complete = function() {
1150 drawPositionInstant();
1151 draggedPieceEl.style.display = 'none';
1153 // execute their onSnapEnd function
1154 if (cfg.hasOwnProperty('onSnapEnd') === true &&
1155 typeof cfg.onSnapEnd === 'function') {
1156 requestAnimationFrame(() => { // HACK: so that we don't add event handlers from the callback...
1157 cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
1162 // snap the piece to the target square
1163 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1164 requestAnimationFrame(() => {
1165 draggedPieceEl.style.transitionProperty = 'top, left';
1166 draggedPieceEl.style.transitionDuration = cfg.snapSpeed + 'ms';
1167 draggedPieceEl.style.top = targetSquarePosition.top + 'px';
1168 draggedPieceEl.style.left = targetSquarePosition.left + 'px';
1172 DRAGGING_A_PIECE = false;
1175 function beginDraggingPiece(source, piece, x, y) {
1176 // run their custom onDragStart function
1177 // their custom onDragStart function can cancel drag start
1178 if (typeof cfg.onDragStart === 'function' &&
1179 cfg.onDragStart(source, piece,
1180 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
1185 DRAGGING_A_PIECE = true;
1186 DRAGGED_PIECE = piece;
1187 DRAGGED_PIECE_SOURCE = source;
1189 // if the piece came from spare pieces, location is offboard
1190 if (source === 'spare') {
1191 DRAGGED_PIECE_LOCATION = 'offboard';
1194 DRAGGED_PIECE_LOCATION = source;
1197 // capture the x, y coords of all squares in memory
1198 captureSquareOffsets();
1200 // create the dragged piece
1201 draggedPieceEl.setAttribute('src', buildPieceImgSrc(piece));
1202 draggedPieceEl.style.display = null;
1203 draggedPieceEl.style.position = 'absolute';
1204 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1205 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1207 if (source !== 'spare') {
1208 // highlight the source square and hide the piece
1209 let square = document.getElementById(SQUARE_ELS_IDS[source]);
1210 square.classList.add(CSS.highlight1);
1211 square.querySelector('.' + CSS.piece).style.display = 'none';
1215 function updateDraggedPiece(x, y) {
1216 // put the dragged piece over the mouse cursor
1217 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1218 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1221 var location = isXYOnSquare(x, y);
1223 // do nothing if the location has not changed
1224 if (location === DRAGGED_PIECE_LOCATION) return;
1226 // remove highlight from previous square
1227 if (validSquare(DRAGGED_PIECE_LOCATION) === true) {
1228 document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION])
1229 .classList.remove(CSS.highlight2);
1232 // add highlight to new square
1233 if (validSquare(location) === true) {
1234 document.getElementById(SQUARE_ELS_IDS[location]).classList.add(CSS.highlight2);
1238 if (typeof cfg.onDragMove === 'function') {
1239 cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1240 DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1241 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1245 DRAGGED_PIECE_LOCATION = location;
1248 function stopDraggedPiece(location) {
1249 // determine what the action should be
1250 var action = 'drop';
1251 if (location === 'offboard' && cfg.dropOffBoard === 'snapback') {
1252 action = 'snapback';
1254 if (location === 'offboard' && cfg.dropOffBoard === 'trash') {
1258 // run their onDrop function, which can potentially change the drop action
1259 if (cfg.hasOwnProperty('onDrop') === true &&
1260 typeof cfg.onDrop === 'function') {
1261 var newPosition = deepCopy(CURRENT_POSITION);
1263 // source piece is a spare piece and position is off the board
1264 //if (DRAGGED_PIECE_SOURCE === 'spare' && location === 'offboard') {...}
1265 // position has not changed; do nothing
1267 // source piece is a spare piece and position is on the board
1268 if (DRAGGED_PIECE_SOURCE === 'spare' && validSquare(location) === true) {
1269 // add the piece to the board
1270 newPosition[location] = DRAGGED_PIECE;
1273 // source piece was on the board and position is off the board
1274 if (validSquare(DRAGGED_PIECE_SOURCE) === true && location === 'offboard') {
1275 // remove the piece from the board
1276 delete newPosition[DRAGGED_PIECE_SOURCE];
1279 // source piece was on the board and position is on the board
1280 if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1281 validSquare(location) === true) {
1283 delete newPosition[DRAGGED_PIECE_SOURCE];
1284 newPosition[location] = DRAGGED_PIECE;
1287 var oldPosition = deepCopy(CURRENT_POSITION);
1289 var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE,
1290 newPosition, oldPosition, CURRENT_ORIENTATION);
1291 if (result === 'snapback' || result === 'trash') {
1297 if (action === 'snapback') {
1298 snapbackDraggedPiece();
1300 else if (action === 'trash') {
1301 trashDraggedPiece();
1303 else if (action === 'drop') {
1304 dropDraggedPieceOnSquare(location);
1308 //------------------------------------------------------------------------------
1310 //------------------------------------------------------------------------------
1313 widget.clear = function(useAnimation) {
1314 widget.position({}, useAnimation);
1318 // get or set config properties
1319 // TODO: write this, GitHub Issue #1
1320 widget.config = function(arg1, arg2) {
1321 // get the current config
1322 if (arguments.length === 0) {
1323 return deepCopy(cfg);
1328 // remove the widget from the page
1329 widget.destroy = function() {
1331 containerEl.innerHTML = '';
1332 draggedPieceEl.remove();
1335 // shorthand method to get the current FEN
1336 widget.fen = function() {
1337 return widget.position('fen');
1341 widget.flip = function() {
1342 widget.orientation('flip');
1346 // TODO: write this, GitHub Issue #5
1347 widget.highlight = function() {
1353 widget.move = function() {
1354 // no need to throw an error here; just do nothing
1355 if (arguments.length === 0) return;
1357 var useAnimation = true;
1359 // collect the moves into an object
1361 for (var i = 0; i < arguments.length; i++) {
1362 // any "false" to this function means no animations
1363 if (arguments[i] === false) {
1364 useAnimation = false;
1368 // skip invalid arguments
1369 if (validMove(arguments[i]) !== true) {
1370 error(2826, 'Invalid move passed to the move method.', arguments[i]);
1374 var tmp = arguments[i].split('-');
1375 moves[tmp[0]] = tmp[1];
1378 // calculate position from moves
1379 var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1382 widget.position(newPos, useAnimation);
1384 // return the new position object
1388 widget.orientation = function(arg) {
1389 // no arguments, return the current orientation
1390 if (arguments.length === 0) {
1391 return CURRENT_ORIENTATION;
1394 // set to white or black
1395 if (arg === 'white' || arg === 'black') {
1396 CURRENT_ORIENTATION = arg;
1402 if (arg === 'flip') {
1403 CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1408 error(5482, 'Invalid value passed to the orientation method.', arg);
1412 * @param {!string|!Object} position
1413 * @param {boolean=} useAnimation
1415 widget.position = function(position, useAnimation) {
1416 // no arguments, return the current position
1417 if (arguments.length === 0) {
1418 return deepCopy(CURRENT_POSITION);
1421 // get position as FEN
1422 if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1423 return objToFen(CURRENT_POSITION);
1426 // default for useAnimations is true
1427 if (useAnimation !== false) {
1428 useAnimation = true;
1432 if (typeof position === 'string' && position.toLowerCase() === 'start') {
1433 position = deepCopy(START_POSITION);
1436 // convert FEN to position object
1437 if (validFen(position) === true) {
1438 position = fenToObj(position);
1441 // validate position object
1442 if (validPositionObject(position) !== true) {
1443 error(6482, 'Invalid value passed to the position method.', position);
1447 if (useAnimation === true) {
1448 // start the animations
1449 doAnimations(calculateAnimations(CURRENT_POSITION, position),
1450 CURRENT_POSITION, position);
1452 // set the new position
1453 setCurrentPosition(position);
1457 setCurrentPosition(position);
1458 drawPositionInstant();
1462 widget.resize = function() {
1463 // calulate the new square size
1464 SQUARE_SIZE = calculateSquareSize();
1467 boardEl.style.width = (SQUARE_SIZE * 8) + 'px';
1469 // set drag piece size
1470 if (draggedPieceEl !== null) {
1471 draggedPieceEl.style.height = SQUARE_SIZE + 'px';
1472 draggedPieceEl.style.width = SQUARE_SIZE + 'px';
1476 if (cfg.sparePieces === true) {
1477 containerEl.querySelector('.' + CSS.sparePieces)
1478 .style.paddingLeft = (SQUARE_SIZE + BOARD_BORDER_SIZE) + 'px';
1485 // set the starting position
1486 widget.start = function(useAnimation) {
1487 widget.position('start', useAnimation);
1490 //------------------------------------------------------------------------------
1492 //------------------------------------------------------------------------------
1494 function isTouchDevice() {
1495 return ('ontouchstart' in document.documentElement);
1498 function mousedownSquare(e) {
1499 let target = e.target.closest('.' + CSS.square);
1504 // do nothing if we're not draggable
1505 if (cfg.draggable !== true) return;
1507 var square = target.getAttribute('data-square');
1509 // no piece on this square
1510 if (validSquare(square) !== true ||
1511 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1515 beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1518 function touchstartSquare(e) {
1519 let target = e.target.closest('.' + CSS.square);
1524 // do nothing if we're not draggable
1525 if (cfg.draggable !== true) return;
1527 var square = target.getAttribute('data-square');
1529 // no piece on this square
1530 if (validSquare(square) !== true ||
1531 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1535 beginDraggingPiece(square, CURRENT_POSITION[square],
1536 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1539 function mousedownSparePiece(e) {
1540 if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1544 // do nothing if sparePieces is not enabled
1545 if (cfg.sparePieces !== true) return;
1547 var piece = e.target.getAttribute('data-piece');
1549 beginDraggingPiece('spare', piece, e.pageX, e.pageY);
1552 function touchstartSparePiece(e) {
1553 if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1557 // do nothing if sparePieces is not enabled
1558 if (cfg.sparePieces !== true) return;
1560 var piece = e.target.getAttribute('data-piece');
1562 beginDraggingPiece('spare', piece,
1563 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1566 function mousemoveWindow(e) {
1567 // do nothing if we are not dragging a piece
1568 if (DRAGGING_A_PIECE !== true) return;
1570 updateDraggedPiece(e.pageX, e.pageY);
1573 function touchmoveWindow(e) {
1574 // do nothing if we are not dragging a piece
1575 if (DRAGGING_A_PIECE !== true) return;
1577 // prevent screen from scrolling
1580 updateDraggedPiece(e.changedTouches[0].pageX,
1581 e.changedTouches[0].pageY);
1584 function mouseupWindow(e) {
1585 // do nothing if we are not dragging a piece
1586 if (DRAGGING_A_PIECE !== true) return;
1589 var location = isXYOnSquare(e.pageX, e.pageY);
1591 stopDraggedPiece(location);
1594 function touchendWindow(e) {
1595 // do nothing if we are not dragging a piece
1596 if (DRAGGING_A_PIECE !== true) return;
1599 var location = isXYOnSquare(e.changedTouches[0].pageX,
1600 e.changedTouches[0].pageY);
1602 stopDraggedPiece(location);
1605 function mouseenterSquare(e) {
1606 let target = e.target.closest('.' + CSS.square);
1611 // do not fire this event if we are dragging a piece
1612 // NOTE: this should never happen, but it's a safeguard
1613 if (DRAGGING_A_PIECE !== false) return;
1615 if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1616 typeof cfg.onMouseoverSquare !== 'function') return;
1619 var square = target.getAttribute('data-square');
1621 // NOTE: this should never happen; defensive
1622 if (validSquare(square) !== true) return;
1624 // get the piece on this square
1626 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1627 piece = CURRENT_POSITION[square];
1630 // execute their function
1631 cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1632 CURRENT_ORIENTATION);
1635 function mouseleaveSquare(e) {
1636 let target = e.target.closest('.' + CSS.square);
1641 // do not fire this event if we are dragging a piece
1642 // NOTE: this should never happen, but it's a safeguard
1643 if (DRAGGING_A_PIECE !== false) return;
1645 if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1646 typeof cfg.onMouseoutSquare !== 'function') return;
1649 var square = target.getAttribute('data-square');
1651 // NOTE: this should never happen; defensive
1652 if (validSquare(square) !== true) return;
1654 // get the piece on this square
1656 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1657 piece = CURRENT_POSITION[square];
1660 // execute their function
1661 cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1662 CURRENT_ORIENTATION);
1665 //------------------------------------------------------------------------------
1667 //------------------------------------------------------------------------------
1669 function addEvents() {
1670 // prevent browser "image drag"
1671 let stopDefault = (e) => {
1672 if (e.target.matches('.' + CSS.piece)) {
1676 document.body.addEventListener('mousedown', stopDefault);
1677 document.body.addEventListener('mousemove', stopDefault);
1679 // mouse drag pieces
1680 boardEl.addEventListener('mousedown', mousedownSquare);
1681 containerEl.addEventListener('mousedown', mousedownSparePiece);
1683 // mouse enter / leave square
1684 boardEl.addEventListener('mouseenter', mouseenterSquare);
1685 boardEl.addEventListener('mouseleave', mouseleaveSquare);
1687 window.addEventListener('mousemove', mousemoveWindow);
1688 window.addEventListener('mouseup', mouseupWindow);
1690 // touch drag pieces
1691 if (isTouchDevice() === true) {
1692 boardEl.addEventListener('touchstart', touchstartSquare);
1693 containerEl.addEventListener('touchstart', touchstartSparePiece);
1694 window.addEventListener('touchmove', touchmoveWindow);
1695 window.addEventListener('touchend', touchendWindow);
1699 function initDom() {
1700 // build board and save it in memory
1701 containerEl.innerHTML = buildBoardContainer();
1702 boardEl = containerEl.querySelector('.' + CSS.board);
1704 if (cfg.sparePieces === true) {
1705 sparePiecesTopEl = containerEl.querySelector('.' + CSS.sparePiecesTop);
1706 sparePiecesBottomEl = containerEl.querySelector('.' + CSS.sparePiecesBottom);
1709 // create the drag piece
1710 var draggedPieceId = createId();
1711 document.body.append(buildPiece('wP', true, draggedPieceId));
1712 draggedPieceEl = document.getElementById(draggedPieceId);
1714 // get the border size
1715 BOARD_BORDER_SIZE = parseInt(boardEl.style.borderLeftWidth, 10);
1717 // set the size and draw the board
1722 if (checkDeps() !== true ||
1723 expandConfig() !== true) return;
1725 // create unique IDs for all the elements we will create
1735 // return the widget object
1738 }; // end window.ChessBoard
1740 // expose util functions
1741 window.ChessBoard.fenToObj = fenToObj;
1742 window.ChessBoard.objToFen = objToFen;
1744 })(); // end anonymous wrapper