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 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 square: 'square-55d63'
221 CSSColor['white'] = 'white-1e1d7';
222 CSSColor['black'] = 'black-3c85d';
224 //------------------------------------------------------------------------------
225 // Module Scope Variables
226 //------------------------------------------------------------------------------
233 // constructor return object
236 //------------------------------------------------------------------------------
238 //------------------------------------------------------------------------------
240 var BOARD_BORDER_SIZE = 2,
241 CURRENT_ORIENTATION = 'white',
242 CURRENT_POSITION = {},
245 DRAGGED_PIECE_LOCATION,
246 DRAGGED_PIECE_SOURCE,
247 DRAGGING_A_PIECE = false,
251 //------------------------------------------------------------------------------
253 //------------------------------------------------------------------------------
256 function createId() {
257 return 'chesspiece-id-' + (id_counter++);
260 function deepCopy(thing) {
261 return JSON.parse(JSON.stringify(thing));
264 //------------------------------------------------------------------------------
265 // Validation / Errors
266 //------------------------------------------------------------------------------
269 * @param {!number} code
270 * @param {!string} msg
271 * @param {Object=} obj
273 function error(code, msg, obj) {
274 // do nothing if showErrors is not set
275 if (cfg.hasOwnProperty('showErrors') !== true ||
276 cfg.showErrors === false) {
280 var errorText = 'ChessBoard Error ' + code + ': ' + msg;
283 if (cfg.showErrors === 'console' &&
284 typeof console === 'object' &&
285 typeof console.log === 'function') {
286 console.log(errorText);
287 if (arguments.length >= 2) {
294 if (cfg.showErrors === 'alert') {
296 errorText += '\n\n' + JSON.stringify(obj);
298 window.alert(errorText);
303 if (typeof cfg.showErrors === 'function') {
304 cfg.showErrors(code, msg, obj);
308 // check dependencies
309 function checkDeps() {
310 // if containerId is a string, it must be the ID of a DOM node
311 if (typeof containerElOrId === 'string') {
313 if (containerElOrId === '') {
314 window.alert('ChessBoard Error 1001: ' +
315 'The first argument to ChessBoard() cannot be an empty string.' +
320 // make sure the container element exists in the DOM
321 var el = document.getElementById(containerElOrId);
323 window.alert('ChessBoard Error 1002: Element with id "' +
324 containerElOrId + '" does not exist in the DOM.' +
329 // set the containerEl
333 // else it must be a DOM node
335 containerEl = containerElOrId;
341 function validAnimationSpeed(speed) {
342 if (speed === 'fast' || speed === 'slow') {
346 if ((parseInt(speed, 10) + '') !== (speed + '')) {
353 // validate config / set default options
354 function expandConfig() {
355 if (typeof cfg === 'string' || validPositionObject(cfg) === true) {
361 // default for orientation is white
362 if (cfg.orientation !== 'black') {
363 cfg.orientation = 'white';
365 CURRENT_ORIENTATION = cfg.orientation;
367 // default for showNotation is true
368 if (cfg.showNotation !== false) {
369 cfg.showNotation = true;
372 // default for draggable is false
373 if (cfg.draggable !== true) {
374 cfg.draggable = false;
377 // default piece theme is wikipedia
378 if (cfg.hasOwnProperty('pieceTheme') !== true ||
379 (typeof cfg.pieceTheme !== 'string' &&
380 typeof cfg.pieceTheme !== 'function')) {
381 cfg.pieceTheme = 'img/chesspieces/wikipedia/{piece}.png';
385 if (cfg.hasOwnProperty('appearSpeed') !== true ||
386 validAnimationSpeed(cfg.appearSpeed) !== true) {
387 cfg.appearSpeed = 200;
389 if (cfg.hasOwnProperty('moveSpeed') !== true ||
390 validAnimationSpeed(cfg.moveSpeed) !== true) {
393 if (cfg.hasOwnProperty('snapbackSpeed') !== true ||
394 validAnimationSpeed(cfg.snapbackSpeed) !== true) {
395 cfg.snapbackSpeed = 50;
397 if (cfg.hasOwnProperty('snapSpeed') !== true ||
398 validAnimationSpeed(cfg.snapSpeed) !== true) {
401 if (cfg.hasOwnProperty('trashSpeed') !== true ||
402 validAnimationSpeed(cfg.trashSpeed) !== true) {
403 cfg.trashSpeed = 100;
406 // make sure position is valid
407 if (cfg.hasOwnProperty('position') === true) {
408 if (cfg.position === 'start') {
409 CURRENT_POSITION = deepCopy(START_POSITION);
412 else if (validFen(cfg.position) === true) {
413 CURRENT_POSITION = fenToObj(cfg.position);
416 else if (validPositionObject(cfg.position) === true) {
417 CURRENT_POSITION = deepCopy(cfg.position);
421 error(7263, 'Invalid value passed to config.position.', cfg.position);
428 //------------------------------------------------------------------------------
430 //------------------------------------------------------------------------------
432 // calculates square size based on the width of the container
433 // got a little CSS black magic here, so let me explain:
434 // get the width of the container element (could be anything), reduce by 1 for
435 // fudge factor, and then keep reducing until we find an exact mod 8 for
437 function calculateSquareSize() {
438 var containerWidth = parseInt(getComputedStyle(containerEl).width, 10);
440 // defensive, prevent infinite loop
441 if (! containerWidth || containerWidth <= 0) {
446 var boardWidth = containerWidth - 1;
448 while (boardWidth % 8 !== 0 && boardWidth > 0) {
452 return (boardWidth / 8);
455 // create random IDs for elements
456 function createElIds() {
457 // squares on the board
458 for (var i = 0; i < COLUMNS.length; i++) {
459 for (var j = 1; j <= 8; j++) {
460 var square = COLUMNS[i] + j;
461 SQUARE_ELS_IDS[square] = square + '-' + createId();
466 //------------------------------------------------------------------------------
468 //------------------------------------------------------------------------------
470 function buildBoardContainer() {
471 var html = '<div class="' + CSS.chessboard + '">';
473 html += '<div class="' + CSS.board + '"></div>';
481 var buildSquare = function(color, size, id) {
482 var html = '<div class="' + CSS.square + ' ' + CSSColor[color] + '" ' +
483 'style="width: ' + size + 'px; height: ' + size + 'px" ' +
486 if (cfg.showNotation === true) {
496 function buildBoard(orientation) {
497 if (orientation !== 'black') {
498 orientation = 'white';
503 // algebraic notation / orientation
504 var alpha = deepCopy(COLUMNS);
506 if (orientation === 'black') {
511 var squareColor = 'white';
512 for (var i = 0; i < 8; i++) {
513 html += '<div class="' + CSS.row + '">';
514 for (var j = 0; j < 8; j++) {
515 var square = alpha[j] + row;
517 html += '<div class="' + CSS.square + ' ' + CSSColor[squareColor] + ' ' +
518 'square-' + square + '" ' +
519 'style="width: ' + SQUARE_SIZE + 'px; height: ' + SQUARE_SIZE + 'px" ' +
520 'id="' + SQUARE_ELS_IDS[square] + '" ' +
521 'data-square="' + square + '">';
523 if (cfg.showNotation === true) {
525 if ((orientation === 'white' && row === 1) ||
526 (orientation === 'black' && row === 8)) {
527 html += '<div class="' + CSS.notation + ' ' + CSS.alpha + '">' +
533 html += '<div class="' + CSS.notation + ' ' + CSS.numeric + '">' +
538 html += '</div>'; // end .square
540 squareColor = (squareColor === 'white' ? 'black' : 'white');
542 html += '<div class="' + CSS.clearfix + '"></div></div>';
544 squareColor = (squareColor === 'white' ? 'black' : 'white');
546 if (orientation === 'white') {
557 function buildPieceImgSrc(piece) {
558 if (typeof cfg.pieceTheme === 'function') {
559 return cfg.pieceTheme(piece);
562 if (typeof cfg.pieceTheme === 'string') {
563 return cfg.pieceTheme.replace(/{piece}/g, piece);
566 // NOTE: this should never happen
567 error(8272, 'Unable to build image source for cfg.pieceTheme.');
572 * @param {!string} piece
573 * @param {boolean=} hidden
574 * @param {!string=} id
576 function buildPiece(piece, hidden, id) {
577 let img = document.createElement('img');
578 img.src = buildPieceImgSrc(piece);
579 if (id && typeof id === 'string') {
580 img.setAttribute('id', id);
582 img.setAttribute('alt', '');
583 img.classList.add(CSS.piece);
584 img.setAttribute('data-piece', piece);
585 img.style.width = SQUARE_SIZE + 'px';
586 img.style.height = SQUARE_SIZE + 'px';
587 if (hidden === true) {
588 img.style.display = 'none';
593 //------------------------------------------------------------------------------
595 //------------------------------------------------------------------------------
597 function offset(el) { // From https://youmightnotneedjquery.com/.
598 let box = el.getBoundingClientRect();
599 let docElem = document.documentElement;
601 top: box.top + window.pageYOffset - docElem.clientTop,
602 left: box.left + window.pageXOffset - docElem.clientLeft
606 function animateSquareToSquare(moved_pieces, completeFn) {
608 for (const {source, destination, piece} of moved_pieces) {
609 // get information about the source and destination squares
610 let srcSquareEl = document.getElementById(SQUARE_ELS_IDS[source]);
611 let srcSquarePosition = offset(srcSquareEl);
612 let destSquareEl = document.getElementById(SQUARE_ELS_IDS[destination]);
613 let destSquarePosition = offset(destSquareEl);
615 // create the animated piece and absolutely position it
616 // over the source square
617 let animatedPieceId = createId();
618 document.body.append(buildPiece(piece, true, animatedPieceId));
619 let animatedPieceEl = document.getElementById(animatedPieceId);
620 animatedPieceEl.style.display = null;
621 animatedPieceEl.style.position = 'absolute';
622 animatedPieceEl.style.top = srcSquarePosition.top + 'px';
623 animatedPieceEl.style.left = srcSquarePosition.left + 'px';
625 // remove original piece(s) from source square
626 // TODO: multiple pieces should never really happen, but it will if we are moving
627 // while another animation still isn't done
628 srcSquareEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
631 let complete = function() {
632 // add the "real" piece to the destination square
633 destSquareEl.append(buildPiece(piece));
635 // remove the animated piece
636 animatedPieceEl.remove();
638 // run complete function
639 if (typeof completeFn === 'function') {
644 // animate the piece to the destination square
645 animatedPieceEl.addEventListener('transitionend', complete, {once: true});
646 pieces.push([animatedPieceEl, destSquarePosition]);
648 requestAnimationFrame(() => {
649 for (let [animatedPieceEl, destSquarePosition] of pieces) {
650 animatedPieceEl.style.transitionProperty = 'top, left';
651 animatedPieceEl.style.transitionDuration = cfg.moveSpeed + 'ms';
652 animatedPieceEl.style.top = destSquarePosition.top + 'px';
653 animatedPieceEl.style.left = destSquarePosition.left + 'px';
658 function fadeIn(pieces, onFinish) {
659 pieces.forEach((piece) => {
660 piece.style.opacity = 0;
661 piece.style.display = null;
662 piece.addEventListener('transitionend', onFinish, {once: true});
664 requestAnimationFrame(() => {
665 pieces.forEach((piece) => {
666 piece.style.transitionProperty = 'opacity';
667 piece.style.transitionDuration = cfg.appearSpeed + 'ms';
668 piece.style.opacity = 1;
673 function fadeOut(pieces, onFinish) {
674 pieces.forEach((piece) => {
675 piece.style.opacity = 1;
676 piece.style.display = null;
677 piece.addEventListener('transitionend', onFinish, {once: true});
679 requestAnimationFrame(() => {
680 pieces.forEach((piece) => {
681 piece.style.transitionProperty = 'opacity';
682 piece.style.transitionDuration = cfg.trashSpeed + 'ms';
683 piece.style.opacity = 0;
688 // execute an array of animations
689 function doAnimations(a, oldPos, newPos) {
691 function onFinish(e) {
693 e.target.transitionProperty = null;
698 // exit if all the animations aren't finished
699 if (numFinished !== a.length) return;
701 drawPositionInstant();
703 // run their onMoveEnd function
704 if (cfg.hasOwnProperty('onMoveEnd') === true &&
705 typeof cfg.onMoveEnd === 'function') {
706 cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
710 requestAnimationFrame(() => { // Firefox workaround.
711 let fadeout_pieces = [];
712 let fadein_pieces = [];
713 let moved_pieces = [];
715 for (var i = 0; i < a.length; i++) {
717 if (a[i].type === 'clear') {
718 document.getElementById(SQUARE_ELS_IDS[a[i].square]).querySelectorAll('.' + CSS.piece).forEach(
719 (piece) => fadeout_pieces.push(piece)
724 if (a[i].type === 'add') {
725 let square = document.getElementById(SQUARE_ELS_IDS[a[i].square]);
726 square.append(buildPiece(a[i].piece, true));
727 let piece = square.querySelector('.' + CSS.piece);
728 fadein_pieces.push(piece);
732 if (a[i].type === 'move') {
733 moved_pieces.push(a[i]);
737 // TODO: Batch moves as well, not just fade in/out.
738 // (We batch them because requestAnimationFrame seemingly costs real time.)
739 if (fadeout_pieces.length > 0) {
740 fadeOut(fadeout_pieces, onFinish);
742 if (fadein_pieces.length > 0) {
743 fadeIn(fadein_pieces, onFinish);
745 if (moved_pieces.length > 0) {
746 animateSquareToSquare(moved_pieces, onFinish);
751 // returns the distance between two squares
752 function squareDistance(s1, s2) {
754 var s1x = COLUMNS.indexOf(s1[0]) + 1;
755 var s1y = parseInt(s1[1], 10);
758 var s2x = COLUMNS.indexOf(s2[0]) + 1;
759 var s2y = parseInt(s2[1], 10);
761 var xDelta = Math.abs(s1x - s2x);
762 var yDelta = Math.abs(s1y - s2y);
764 if (xDelta >= yDelta) return xDelta;
768 // returns the square of the closest instance of piece
769 // returns false if no instance of piece is found in position
770 function findClosestPiece(position, piece, square) {
771 let best_square = false;
773 for (var i = 0; i < COLUMNS.length; i++) {
774 for (var j = 1; j <= 8; j++) {
775 let other_square = COLUMNS[i] + j;
777 if (position[other_square] === piece && square != other_square) {
778 let dist = squareDistance(square, other_square);
779 if (dist < best_dist) {
780 best_square = other_square;
790 // calculate an array of animations that need to happen in order to get
792 function calculateAnimations(pos1, pos2) {
793 // make copies of both
794 pos1 = deepCopy(pos1);
795 pos2 = deepCopy(pos2);
798 var squaresMovedTo = {};
800 // remove pieces that are the same in both positions
801 for (var i in pos2) {
802 if (pos2.hasOwnProperty(i) !== true) continue;
804 if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
810 // find all the "move" animations
811 for (var i in pos2) {
812 if (pos2.hasOwnProperty(i) !== true) continue;
814 var closestPiece = findClosestPiece(pos1, pos2[i], i);
815 if (closestPiece !== false) {
818 source: closestPiece,
823 delete pos1[closestPiece];
825 squaresMovedTo[i] = true;
829 // add pieces to pos2
830 for (var i in pos2) {
831 if (pos2.hasOwnProperty(i) !== true) continue;
842 // clear pieces from pos1
843 for (var i in pos1) {
844 if (pos1.hasOwnProperty(i) !== true) continue;
846 // do not clear a piece if it is on a square that is the result
847 // of a "move", ie: a piece capture
848 if (squaresMovedTo.hasOwnProperty(i) === true) continue;
862 //------------------------------------------------------------------------------
864 //------------------------------------------------------------------------------
866 function drawPositionInstant() {
868 boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
871 for (var i in CURRENT_POSITION) {
872 if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue;
874 document.getElementById(SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i]));
878 function drawBoard() {
879 boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
880 drawPositionInstant();
883 // given a position and a set of moves, return a new position
884 // with the moves executed
885 function calculatePositionFromMoves(position, moves) {
886 position = deepCopy(position);
888 for (var i in moves) {
889 if (moves.hasOwnProperty(i) !== true) continue;
891 // skip the move if the position doesn't have a piece on the source square
892 if (position.hasOwnProperty(i) !== true) continue;
894 var piece = position[i];
896 position[moves[i]] = piece;
902 function setCurrentPosition(position) {
903 var oldPos = deepCopy(CURRENT_POSITION);
904 var newPos = deepCopy(position);
905 var oldFen = objToFen(oldPos);
906 var newFen = objToFen(newPos);
908 // do nothing if no change in position
909 if (oldFen === newFen) return;
911 // run their onChange function
912 if (cfg.hasOwnProperty('onChange') === true &&
913 typeof cfg.onChange === 'function') {
914 cfg.onChange(oldPos, newPos);
918 CURRENT_POSITION = position;
921 function isXYOnSquare(x, y) {
922 for (var i in SQUARE_ELS_OFFSETS) {
923 if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue;
925 var s = SQUARE_ELS_OFFSETS[i];
926 if (x >= s.left && x < s.left + SQUARE_SIZE &&
927 y >= s.top && y < s.top + SQUARE_SIZE) {
935 // records the XY coords of every square into memory
936 function captureSquareOffsets() {
937 SQUARE_ELS_OFFSETS = {};
939 for (var i in SQUARE_ELS_IDS) {
940 if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue;
942 SQUARE_ELS_OFFSETS[i] = offset(document.getElementById(SQUARE_ELS_IDS[i]));
946 function removeSquareHighlights() {
947 boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
948 piece.classList.remove(CSS.highlight1);
949 piece.classList.remove(CSS.highlight2);
953 function snapbackDraggedPiece() {
954 removeSquareHighlights();
956 // animation complete
957 function complete() {
958 drawPositionInstant();
959 draggedPieceEl.style.display = 'none';
961 // run their onSnapbackEnd function
962 if (cfg.hasOwnProperty('onSnapbackEnd') === true &&
963 typeof cfg.onSnapbackEnd === 'function') {
964 cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
965 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
969 // get source square position
970 var sourceSquarePosition =
971 offset(document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]));
973 // animate the piece to the target square
974 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
975 requestAnimationFrame(() => {
976 draggedPieceEl.style.transitionProperty = 'top, left';
977 draggedPieceEl.style.transitionDuration = cfg.snapbackSpeed + 'ms';
978 draggedPieceEl.style.top = sourceSquarePosition.top + 'px';
979 draggedPieceEl.style.left = sourceSquarePosition.left + 'px';
983 DRAGGING_A_PIECE = false;
986 function dropDraggedPieceOnSquare(square) {
987 removeSquareHighlights();
990 var newPosition = deepCopy(CURRENT_POSITION);
991 delete newPosition[DRAGGED_PIECE_SOURCE];
992 newPosition[square] = DRAGGED_PIECE;
993 setCurrentPosition(newPosition);
995 // get target square information
996 var targetSquarePosition = offset(document.getElementById(SQUARE_ELS_IDS[square]));
998 // animation complete
999 var complete = function() {
1000 drawPositionInstant();
1001 draggedPieceEl.style.display = 'none';
1003 // execute their onSnapEnd function
1004 if (cfg.hasOwnProperty('onSnapEnd') === true &&
1005 typeof cfg.onSnapEnd === 'function') {
1006 requestAnimationFrame(() => { // HACK: so that we don't add event handlers from the callback...
1007 cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
1012 // snap the piece to the target square
1013 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1014 requestAnimationFrame(() => {
1015 draggedPieceEl.style.transitionProperty = 'top, left';
1016 draggedPieceEl.style.transitionDuration = cfg.snapSpeed + 'ms';
1017 draggedPieceEl.style.top = targetSquarePosition.top + 'px';
1018 draggedPieceEl.style.left = targetSquarePosition.left + 'px';
1022 DRAGGING_A_PIECE = false;
1025 function beginDraggingPiece(source, piece, x, y) {
1026 // run their custom onDragStart function
1027 // their custom onDragStart function can cancel drag start
1028 if (typeof cfg.onDragStart === 'function' &&
1029 cfg.onDragStart(source, piece,
1030 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
1035 DRAGGING_A_PIECE = true;
1036 DRAGGED_PIECE = piece;
1037 DRAGGED_PIECE_SOURCE = source;
1038 DRAGGED_PIECE_LOCATION = source;
1040 // capture the x, y coords of all squares in memory
1041 captureSquareOffsets();
1043 // create the dragged piece
1044 draggedPieceEl.setAttribute('src', buildPieceImgSrc(piece));
1045 draggedPieceEl.style.display = null;
1046 draggedPieceEl.style.position = 'absolute';
1047 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1048 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1050 // highlight the source square and hide the piece
1051 let square = document.getElementById(SQUARE_ELS_IDS[source]);
1052 square.classList.add(CSS.highlight1);
1053 square.querySelector('.' + CSS.piece).style.display = 'none';
1056 function updateDraggedPiece(x, y) {
1057 // put the dragged piece over the mouse cursor
1058 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1059 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1062 var location = isXYOnSquare(x, y);
1064 // do nothing if the location has not changed
1065 if (location === DRAGGED_PIECE_LOCATION) return;
1067 // remove highlight from previous square
1068 if (validSquare(DRAGGED_PIECE_LOCATION) === true) {
1069 document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION])
1070 .classList.remove(CSS.highlight2);
1073 // add highlight to new square
1074 if (validSquare(location) === true) {
1075 document.getElementById(SQUARE_ELS_IDS[location]).classList.add(CSS.highlight2);
1079 if (typeof cfg.onDragMove === 'function') {
1080 cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1081 DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1082 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1086 DRAGGED_PIECE_LOCATION = location;
1089 function stopDraggedPiece(location) {
1090 // determine what the action should be
1091 var action = 'drop';
1092 if (location === 'offboard' && cfg.dropOffBoard === 'snapback') {
1093 action = 'snapback';
1096 // run their onDrop function, which can potentially change the drop action
1097 if (cfg.hasOwnProperty('onDrop') === true &&
1098 typeof cfg.onDrop === 'function') {
1099 var newPosition = deepCopy(CURRENT_POSITION);
1101 // source piece was on the board and position is on the board
1102 if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1103 validSquare(location) === true) {
1105 delete newPosition[DRAGGED_PIECE_SOURCE];
1106 newPosition[location] = DRAGGED_PIECE;
1109 var oldPosition = deepCopy(CURRENT_POSITION);
1111 var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE,
1112 newPosition, oldPosition, CURRENT_ORIENTATION);
1113 if (result === 'snapback') {
1119 if (action === 'snapback') {
1120 snapbackDraggedPiece();
1122 else if (action === 'drop') {
1123 dropDraggedPieceOnSquare(location);
1127 //------------------------------------------------------------------------------
1129 //------------------------------------------------------------------------------
1132 widget.clear = function(useAnimation) {
1133 widget.position({}, useAnimation);
1137 // get or set config properties
1138 // TODO: write this, GitHub Issue #1
1139 widget.config = function(arg1, arg2) {
1140 // get the current config
1141 if (arguments.length === 0) {
1142 return deepCopy(cfg);
1147 // remove the widget from the page
1148 widget.destroy = function() {
1150 containerEl.innerHTML = '';
1151 draggedPieceEl.remove();
1154 // shorthand method to get the current FEN
1155 widget.fen = function() {
1156 return widget.position('fen');
1160 widget.flip = function() {
1161 widget.orientation('flip');
1165 // TODO: write this, GitHub Issue #5
1166 widget.highlight = function() {
1172 widget.move = function() {
1173 // no need to throw an error here; just do nothing
1174 if (arguments.length === 0) return;
1176 var useAnimation = true;
1178 // collect the moves into an object
1180 for (var i = 0; i < arguments.length; i++) {
1181 // any "false" to this function means no animations
1182 if (arguments[i] === false) {
1183 useAnimation = false;
1187 // skip invalid arguments
1188 if (validMove(arguments[i]) !== true) {
1189 error(2826, 'Invalid move passed to the move method.', arguments[i]);
1193 var tmp = arguments[i].split('-');
1194 moves[tmp[0]] = tmp[1];
1197 // calculate position from moves
1198 var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1201 widget.position(newPos, useAnimation);
1203 // return the new position object
1207 widget.orientation = function(arg) {
1208 // no arguments, return the current orientation
1209 if (arguments.length === 0) {
1210 return CURRENT_ORIENTATION;
1213 // set to white or black
1214 if (arg === 'white' || arg === 'black') {
1215 CURRENT_ORIENTATION = arg;
1221 if (arg === 'flip') {
1222 CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1227 error(5482, 'Invalid value passed to the orientation method.', arg);
1231 * @param {!string|!Object} position
1232 * @param {boolean=} useAnimation
1234 widget.position = function(position, useAnimation) {
1235 // no arguments, return the current position
1236 if (arguments.length === 0) {
1237 return deepCopy(CURRENT_POSITION);
1240 // get position as FEN
1241 if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1242 return objToFen(CURRENT_POSITION);
1245 // default for useAnimations is true
1246 if (useAnimation !== false) {
1247 useAnimation = true;
1251 if (typeof position === 'string' && position.toLowerCase() === 'start') {
1252 position = deepCopy(START_POSITION);
1255 // convert FEN to position object
1256 if (validFen(position) === true) {
1257 position = fenToObj(position);
1260 // validate position object
1261 if (validPositionObject(position) !== true) {
1262 error(6482, 'Invalid value passed to the position method.', position);
1266 if (useAnimation === true) {
1267 // start the animations
1268 doAnimations(calculateAnimations(CURRENT_POSITION, position),
1269 CURRENT_POSITION, position);
1271 // set the new position
1272 setCurrentPosition(position);
1276 setCurrentPosition(position);
1277 drawPositionInstant();
1281 widget.resize = function() {
1282 // calulate the new square size
1283 SQUARE_SIZE = calculateSquareSize();
1286 boardEl.style.width = (SQUARE_SIZE * 8) + 'px';
1288 // set drag piece size
1289 if (draggedPieceEl !== null) {
1290 draggedPieceEl.style.height = SQUARE_SIZE + 'px';
1291 draggedPieceEl.style.width = SQUARE_SIZE + 'px';
1298 // set the starting position
1299 widget.start = function(useAnimation) {
1300 widget.position('start', useAnimation);
1303 //------------------------------------------------------------------------------
1305 //------------------------------------------------------------------------------
1307 function isTouchDevice() {
1308 return ('ontouchstart' in document.documentElement);
1311 function mousedownSquare(e) {
1312 let target = e.target.closest('.' + CSS.square);
1317 // do nothing if we're not draggable
1318 if (cfg.draggable !== true) return;
1320 var square = target.getAttribute('data-square');
1322 // no piece on this square
1323 if (validSquare(square) !== true ||
1324 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1328 beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1331 function touchstartSquare(e) {
1332 let target = e.target.closest('.' + CSS.square);
1337 // do nothing if we're not draggable
1338 if (cfg.draggable !== true) return;
1340 var square = target.getAttribute('data-square');
1342 // no piece on this square
1343 if (validSquare(square) !== true ||
1344 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1348 beginDraggingPiece(square, CURRENT_POSITION[square],
1349 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1352 function mousemoveWindow(e) {
1353 // do nothing if we are not dragging a piece
1354 if (DRAGGING_A_PIECE !== true) return;
1356 updateDraggedPiece(e.pageX, e.pageY);
1359 function touchmoveWindow(e) {
1360 // do nothing if we are not dragging a piece
1361 if (DRAGGING_A_PIECE !== true) return;
1363 // prevent screen from scrolling
1366 updateDraggedPiece(e.changedTouches[0].pageX,
1367 e.changedTouches[0].pageY);
1370 function mouseupWindow(e) {
1371 // do nothing if we are not dragging a piece
1372 if (DRAGGING_A_PIECE !== true) return;
1375 var location = isXYOnSquare(e.pageX, e.pageY);
1377 stopDraggedPiece(location);
1380 function touchendWindow(e) {
1381 // do nothing if we are not dragging a piece
1382 if (DRAGGING_A_PIECE !== true) return;
1385 var location = isXYOnSquare(e.changedTouches[0].pageX,
1386 e.changedTouches[0].pageY);
1388 stopDraggedPiece(location);
1391 function mouseenterSquare(e) {
1392 let target = e.target.closest('.' + CSS.square);
1397 // do not fire this event if we are dragging a piece
1398 // NOTE: this should never happen, but it's a safeguard
1399 if (DRAGGING_A_PIECE !== false) return;
1401 if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1402 typeof cfg.onMouseoverSquare !== 'function') return;
1405 var square = target.getAttribute('data-square');
1407 // NOTE: this should never happen; defensive
1408 if (validSquare(square) !== true) return;
1410 // get the piece on this square
1412 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1413 piece = CURRENT_POSITION[square];
1416 // execute their function
1417 cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1418 CURRENT_ORIENTATION);
1421 function mouseleaveSquare(e) {
1422 let target = e.target.closest('.' + CSS.square);
1427 // do not fire this event if we are dragging a piece
1428 // NOTE: this should never happen, but it's a safeguard
1429 if (DRAGGING_A_PIECE !== false) return;
1431 if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1432 typeof cfg.onMouseoutSquare !== 'function') return;
1435 var square = target.getAttribute('data-square');
1437 // NOTE: this should never happen; defensive
1438 if (validSquare(square) !== true) return;
1440 // get the piece on this square
1442 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1443 piece = CURRENT_POSITION[square];
1446 // execute their function
1447 cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1448 CURRENT_ORIENTATION);
1451 //------------------------------------------------------------------------------
1453 //------------------------------------------------------------------------------
1455 function addEvents() {
1456 // prevent browser "image drag"
1457 let stopDefault = (e) => {
1458 if (e.target.matches('.' + CSS.piece)) {
1462 document.body.addEventListener('mousedown', stopDefault);
1463 document.body.addEventListener('mousemove', stopDefault);
1465 // mouse drag pieces
1466 boardEl.addEventListener('mousedown', mousedownSquare);
1468 // mouse enter / leave square
1469 boardEl.addEventListener('mouseenter', mouseenterSquare);
1470 boardEl.addEventListener('mouseleave', mouseleaveSquare);
1472 window.addEventListener('mousemove', mousemoveWindow);
1473 window.addEventListener('mouseup', mouseupWindow);
1475 // touch drag pieces
1476 if (isTouchDevice() === true) {
1477 boardEl.addEventListener('touchstart', touchstartSquare);
1478 window.addEventListener('touchmove', touchmoveWindow);
1479 window.addEventListener('touchend', touchendWindow);
1483 function initDom() {
1484 // build board and save it in memory
1485 containerEl.innerHTML = buildBoardContainer();
1486 boardEl = containerEl.querySelector('.' + CSS.board);
1488 // create the drag piece
1489 var draggedPieceId = createId();
1490 document.body.append(buildPiece('wP', true, draggedPieceId));
1491 draggedPieceEl = document.getElementById(draggedPieceId);
1493 // get the border size
1494 BOARD_BORDER_SIZE = parseInt(boardEl.style.borderLeftWidth, 10);
1496 // set the size and draw the board
1501 if (checkDeps() !== true ||
1502 expandConfig() !== true) return;
1504 // create unique IDs for all the elements we will create
1514 // return the widget object
1517 }; // end window.ChessBoard
1519 // expose util functions
1520 window.ChessBoard.fenToObj = fenToObj;
1521 window.ChessBoard.objToFen = objToFen;
1523 })(); // end anonymous wrapper