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(src, dest, piece, completeFn) {
607 // get information about the source and destination squares
608 var srcSquareEl = document.getElementById(SQUARE_ELS_IDS[src]);
609 var srcSquarePosition = offset(srcSquareEl);
610 var destSquareEl = document.getElementById(SQUARE_ELS_IDS[dest]);
611 var destSquarePosition = offset(destSquareEl);
613 // create the animated piece and absolutely position it
614 // over the source square
615 var animatedPieceId = createId();
616 document.body.append(buildPiece(piece, true, animatedPieceId));
617 var animatedPieceEl = document.getElementById(animatedPieceId);
618 animatedPieceEl.style.display = null;
619 animatedPieceEl.style.position = 'absolute';
620 animatedPieceEl.style.top = srcSquarePosition.top + 'px';
621 animatedPieceEl.style.left = srcSquarePosition.left + 'px';
623 // remove original piece(s) from source square
624 // TODO: multiple pieces should never really happen, but it will if we are moving
625 // while another animation still isn't done
626 srcSquareEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
629 var complete = function() {
630 // add the "real" piece to the destination square
631 destSquareEl.append(buildPiece(piece));
633 // remove the animated piece
634 animatedPieceEl.remove();
636 // run complete function
637 if (typeof completeFn === 'function') {
642 // animate the piece to the destination square
643 animatedPieceEl.addEventListener('transitionend', complete, {once: true});
644 requestAnimationFrame(() => {
645 animatedPieceEl.style.transitionProperty = 'top, left';
646 animatedPieceEl.style.transitionDuration = cfg.moveSpeed + 'ms';
647 animatedPieceEl.style.top = destSquarePosition.top + 'px';
648 animatedPieceEl.style.left = destSquarePosition.left + 'px';
652 function fadeIn(pieces, onFinish) {
653 pieces.forEach((piece) => {
654 piece.style.opacity = 0;
655 piece.style.display = null;
656 piece.addEventListener('transitionend', onFinish, {once: true});
658 requestAnimationFrame(() => {
659 pieces.forEach((piece) => {
660 piece.style.transitionProperty = 'opacity';
661 piece.style.transitionDuration = cfg.appearSpeed + 'ms';
662 piece.style.opacity = 1;
667 function fadeOut(pieces, onFinish) {
668 pieces.forEach((piece) => {
669 piece.style.opacity = 1;
670 piece.style.display = null;
671 piece.addEventListener('transitionend', onFinish, {once: true});
673 requestAnimationFrame(() => {
674 pieces.forEach((piece) => {
675 piece.style.transitionProperty = 'opacity';
676 piece.style.transitionDuration = cfg.trashSpeed + 'ms';
677 piece.style.opacity = 0;
682 // execute an array of animations
683 function doAnimations(a, oldPos, newPos) {
685 function onFinish(e) {
687 e.target.transitionProperty = null;
692 // exit if all the animations aren't finished
693 if (numFinished !== a.length) return;
695 drawPositionInstant();
697 // run their onMoveEnd function
698 if (cfg.hasOwnProperty('onMoveEnd') === true &&
699 typeof cfg.onMoveEnd === 'function') {
700 cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
704 requestAnimationFrame(() => { // Firefox workaround.
705 let fadeout_pieces = [];
706 let fadein_pieces = [];
708 for (var i = 0; i < a.length; i++) {
710 if (a[i].type === 'clear') {
711 document.getElementById(SQUARE_ELS_IDS[a[i].square]).querySelectorAll('.' + CSS.piece).forEach(
712 (piece) => fadeout_pieces.push(piece)
717 if (a[i].type === 'add') {
718 let square = document.getElementById(SQUARE_ELS_IDS[a[i].square]);
719 square.append(buildPiece(a[i].piece, true));
720 let piece = square.querySelector('.' + CSS.piece);
721 fadein_pieces.push(piece);
725 if (a[i].type === 'move') {
726 animateSquareToSquare(a[i].source, a[i].destination, a[i].piece,
731 // TODO: Batch moves as well, not just fade in/out.
732 // (We batch them because requestAnimationFrame seemingly costs real time.)
733 if (fadeout_pieces.length > 0) {
734 fadeOut(fadeout_pieces, onFinish);
736 if (fadein_pieces.length > 0) {
737 fadeIn(fadein_pieces, onFinish);
742 // returns the distance between two squares
743 function squareDistance(s1, s2) {
745 var s1x = COLUMNS.indexOf(s1[0]) + 1;
746 var s1y = parseInt(s1[1], 10);
749 var s2x = COLUMNS.indexOf(s2[0]) + 1;
750 var s2y = parseInt(s2[1], 10);
752 var xDelta = Math.abs(s1x - s2x);
753 var yDelta = Math.abs(s1y - s2y);
755 if (xDelta >= yDelta) return xDelta;
759 // returns the square of the closest instance of piece
760 // returns false if no instance of piece is found in position
761 function findClosestPiece(position, piece, square) {
762 let best_square = false;
764 for (var i = 0; i < COLUMNS.length; i++) {
765 for (var j = 1; j <= 8; j++) {
766 let other_square = COLUMNS[i] + j;
768 if (position[other_square] === piece && square != other_square) {
769 let dist = squareDistance(square, other_square);
770 if (dist < best_dist) {
771 best_square = other_square;
781 // calculate an array of animations that need to happen in order to get
783 function calculateAnimations(pos1, pos2) {
784 // make copies of both
785 pos1 = deepCopy(pos1);
786 pos2 = deepCopy(pos2);
789 var squaresMovedTo = {};
791 // remove pieces that are the same in both positions
792 for (var i in pos2) {
793 if (pos2.hasOwnProperty(i) !== true) continue;
795 if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
801 // find all the "move" animations
802 for (var i in pos2) {
803 if (pos2.hasOwnProperty(i) !== true) continue;
805 var closestPiece = findClosestPiece(pos1, pos2[i], i);
806 if (closestPiece !== false) {
809 source: closestPiece,
814 delete pos1[closestPiece];
816 squaresMovedTo[i] = true;
820 // add pieces to pos2
821 for (var i in pos2) {
822 if (pos2.hasOwnProperty(i) !== true) continue;
833 // clear pieces from pos1
834 for (var i in pos1) {
835 if (pos1.hasOwnProperty(i) !== true) continue;
837 // do not clear a piece if it is on a square that is the result
838 // of a "move", ie: a piece capture
839 if (squaresMovedTo.hasOwnProperty(i) === true) continue;
853 //------------------------------------------------------------------------------
855 //------------------------------------------------------------------------------
857 function drawPositionInstant() {
859 boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
862 for (var i in CURRENT_POSITION) {
863 if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue;
865 document.getElementById(SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i]));
869 function drawBoard() {
870 boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
871 drawPositionInstant();
874 // given a position and a set of moves, return a new position
875 // with the moves executed
876 function calculatePositionFromMoves(position, moves) {
877 position = deepCopy(position);
879 for (var i in moves) {
880 if (moves.hasOwnProperty(i) !== true) continue;
882 // skip the move if the position doesn't have a piece on the source square
883 if (position.hasOwnProperty(i) !== true) continue;
885 var piece = position[i];
887 position[moves[i]] = piece;
893 function setCurrentPosition(position) {
894 var oldPos = deepCopy(CURRENT_POSITION);
895 var newPos = deepCopy(position);
896 var oldFen = objToFen(oldPos);
897 var newFen = objToFen(newPos);
899 // do nothing if no change in position
900 if (oldFen === newFen) return;
902 // run their onChange function
903 if (cfg.hasOwnProperty('onChange') === true &&
904 typeof cfg.onChange === 'function') {
905 cfg.onChange(oldPos, newPos);
909 CURRENT_POSITION = position;
912 function isXYOnSquare(x, y) {
913 for (var i in SQUARE_ELS_OFFSETS) {
914 if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue;
916 var s = SQUARE_ELS_OFFSETS[i];
917 if (x >= s.left && x < s.left + SQUARE_SIZE &&
918 y >= s.top && y < s.top + SQUARE_SIZE) {
926 // records the XY coords of every square into memory
927 function captureSquareOffsets() {
928 SQUARE_ELS_OFFSETS = {};
930 for (var i in SQUARE_ELS_IDS) {
931 if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue;
933 SQUARE_ELS_OFFSETS[i] = offset(document.getElementById(SQUARE_ELS_IDS[i]));
937 function removeSquareHighlights() {
938 boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
939 piece.classList.remove(CSS.highlight1);
940 piece.classList.remove(CSS.highlight2);
944 function snapbackDraggedPiece() {
945 removeSquareHighlights();
947 // animation complete
948 function complete() {
949 drawPositionInstant();
950 draggedPieceEl.style.display = 'none';
952 // run their onSnapbackEnd function
953 if (cfg.hasOwnProperty('onSnapbackEnd') === true &&
954 typeof cfg.onSnapbackEnd === 'function') {
955 cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
956 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
960 // get source square position
961 var sourceSquarePosition =
962 offset(document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]));
964 // animate the piece to the target square
965 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
966 requestAnimationFrame(() => {
967 draggedPieceEl.style.transitionProperty = 'top, left';
968 draggedPieceEl.style.transitionDuration = cfg.snapbackSpeed + 'ms';
969 draggedPieceEl.style.top = sourceSquarePosition.top + 'px';
970 draggedPieceEl.style.left = sourceSquarePosition.left + 'px';
974 DRAGGING_A_PIECE = false;
977 function dropDraggedPieceOnSquare(square) {
978 removeSquareHighlights();
981 var newPosition = deepCopy(CURRENT_POSITION);
982 delete newPosition[DRAGGED_PIECE_SOURCE];
983 newPosition[square] = DRAGGED_PIECE;
984 setCurrentPosition(newPosition);
986 // get target square information
987 var targetSquarePosition = offset(document.getElementById(SQUARE_ELS_IDS[square]));
989 // animation complete
990 var complete = function() {
991 drawPositionInstant();
992 draggedPieceEl.style.display = 'none';
994 // execute their onSnapEnd function
995 if (cfg.hasOwnProperty('onSnapEnd') === true &&
996 typeof cfg.onSnapEnd === 'function') {
997 requestAnimationFrame(() => { // HACK: so that we don't add event handlers from the callback...
998 cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
1003 // snap the piece to the target square
1004 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1005 requestAnimationFrame(() => {
1006 draggedPieceEl.style.transitionProperty = 'top, left';
1007 draggedPieceEl.style.transitionDuration = cfg.snapSpeed + 'ms';
1008 draggedPieceEl.style.top = targetSquarePosition.top + 'px';
1009 draggedPieceEl.style.left = targetSquarePosition.left + 'px';
1013 DRAGGING_A_PIECE = false;
1016 function beginDraggingPiece(source, piece, x, y) {
1017 // run their custom onDragStart function
1018 // their custom onDragStart function can cancel drag start
1019 if (typeof cfg.onDragStart === 'function' &&
1020 cfg.onDragStart(source, piece,
1021 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
1026 DRAGGING_A_PIECE = true;
1027 DRAGGED_PIECE = piece;
1028 DRAGGED_PIECE_SOURCE = source;
1029 DRAGGED_PIECE_LOCATION = source;
1031 // capture the x, y coords of all squares in memory
1032 captureSquareOffsets();
1034 // create the dragged piece
1035 draggedPieceEl.setAttribute('src', buildPieceImgSrc(piece));
1036 draggedPieceEl.style.display = null;
1037 draggedPieceEl.style.position = 'absolute';
1038 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1039 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1041 // highlight the source square and hide the piece
1042 let square = document.getElementById(SQUARE_ELS_IDS[source]);
1043 square.classList.add(CSS.highlight1);
1044 square.querySelector('.' + CSS.piece).style.display = 'none';
1047 function updateDraggedPiece(x, y) {
1048 // put the dragged piece over the mouse cursor
1049 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1050 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1053 var location = isXYOnSquare(x, y);
1055 // do nothing if the location has not changed
1056 if (location === DRAGGED_PIECE_LOCATION) return;
1058 // remove highlight from previous square
1059 if (validSquare(DRAGGED_PIECE_LOCATION) === true) {
1060 document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION])
1061 .classList.remove(CSS.highlight2);
1064 // add highlight to new square
1065 if (validSquare(location) === true) {
1066 document.getElementById(SQUARE_ELS_IDS[location]).classList.add(CSS.highlight2);
1070 if (typeof cfg.onDragMove === 'function') {
1071 cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1072 DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1073 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1077 DRAGGED_PIECE_LOCATION = location;
1080 function stopDraggedPiece(location) {
1081 // determine what the action should be
1082 var action = 'drop';
1083 if (location === 'offboard' && cfg.dropOffBoard === 'snapback') {
1084 action = 'snapback';
1087 // run their onDrop function, which can potentially change the drop action
1088 if (cfg.hasOwnProperty('onDrop') === true &&
1089 typeof cfg.onDrop === 'function') {
1090 var newPosition = deepCopy(CURRENT_POSITION);
1092 // source piece was on the board and position is on the board
1093 if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1094 validSquare(location) === true) {
1096 delete newPosition[DRAGGED_PIECE_SOURCE];
1097 newPosition[location] = DRAGGED_PIECE;
1100 var oldPosition = deepCopy(CURRENT_POSITION);
1102 var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE,
1103 newPosition, oldPosition, CURRENT_ORIENTATION);
1104 if (result === 'snapback') {
1110 if (action === 'snapback') {
1111 snapbackDraggedPiece();
1113 else if (action === 'drop') {
1114 dropDraggedPieceOnSquare(location);
1118 //------------------------------------------------------------------------------
1120 //------------------------------------------------------------------------------
1123 widget.clear = function(useAnimation) {
1124 widget.position({}, useAnimation);
1128 // get or set config properties
1129 // TODO: write this, GitHub Issue #1
1130 widget.config = function(arg1, arg2) {
1131 // get the current config
1132 if (arguments.length === 0) {
1133 return deepCopy(cfg);
1138 // remove the widget from the page
1139 widget.destroy = function() {
1141 containerEl.innerHTML = '';
1142 draggedPieceEl.remove();
1145 // shorthand method to get the current FEN
1146 widget.fen = function() {
1147 return widget.position('fen');
1151 widget.flip = function() {
1152 widget.orientation('flip');
1156 // TODO: write this, GitHub Issue #5
1157 widget.highlight = function() {
1163 widget.move = function() {
1164 // no need to throw an error here; just do nothing
1165 if (arguments.length === 0) return;
1167 var useAnimation = true;
1169 // collect the moves into an object
1171 for (var i = 0; i < arguments.length; i++) {
1172 // any "false" to this function means no animations
1173 if (arguments[i] === false) {
1174 useAnimation = false;
1178 // skip invalid arguments
1179 if (validMove(arguments[i]) !== true) {
1180 error(2826, 'Invalid move passed to the move method.', arguments[i]);
1184 var tmp = arguments[i].split('-');
1185 moves[tmp[0]] = tmp[1];
1188 // calculate position from moves
1189 var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1192 widget.position(newPos, useAnimation);
1194 // return the new position object
1198 widget.orientation = function(arg) {
1199 // no arguments, return the current orientation
1200 if (arguments.length === 0) {
1201 return CURRENT_ORIENTATION;
1204 // set to white or black
1205 if (arg === 'white' || arg === 'black') {
1206 CURRENT_ORIENTATION = arg;
1212 if (arg === 'flip') {
1213 CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1218 error(5482, 'Invalid value passed to the orientation method.', arg);
1222 * @param {!string|!Object} position
1223 * @param {boolean=} useAnimation
1225 widget.position = function(position, useAnimation) {
1226 // no arguments, return the current position
1227 if (arguments.length === 0) {
1228 return deepCopy(CURRENT_POSITION);
1231 // get position as FEN
1232 if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1233 return objToFen(CURRENT_POSITION);
1236 // default for useAnimations is true
1237 if (useAnimation !== false) {
1238 useAnimation = true;
1242 if (typeof position === 'string' && position.toLowerCase() === 'start') {
1243 position = deepCopy(START_POSITION);
1246 // convert FEN to position object
1247 if (validFen(position) === true) {
1248 position = fenToObj(position);
1251 // validate position object
1252 if (validPositionObject(position) !== true) {
1253 error(6482, 'Invalid value passed to the position method.', position);
1257 if (useAnimation === true) {
1258 // start the animations
1259 doAnimations(calculateAnimations(CURRENT_POSITION, position),
1260 CURRENT_POSITION, position);
1262 // set the new position
1263 setCurrentPosition(position);
1267 setCurrentPosition(position);
1268 drawPositionInstant();
1272 widget.resize = function() {
1273 // calulate the new square size
1274 SQUARE_SIZE = calculateSquareSize();
1277 boardEl.style.width = (SQUARE_SIZE * 8) + 'px';
1279 // set drag piece size
1280 if (draggedPieceEl !== null) {
1281 draggedPieceEl.style.height = SQUARE_SIZE + 'px';
1282 draggedPieceEl.style.width = SQUARE_SIZE + 'px';
1289 // set the starting position
1290 widget.start = function(useAnimation) {
1291 widget.position('start', useAnimation);
1294 //------------------------------------------------------------------------------
1296 //------------------------------------------------------------------------------
1298 function isTouchDevice() {
1299 return ('ontouchstart' in document.documentElement);
1302 function mousedownSquare(e) {
1303 let target = e.target.closest('.' + CSS.square);
1308 // do nothing if we're not draggable
1309 if (cfg.draggable !== true) return;
1311 var square = target.getAttribute('data-square');
1313 // no piece on this square
1314 if (validSquare(square) !== true ||
1315 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1319 beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1322 function touchstartSquare(e) {
1323 let target = e.target.closest('.' + CSS.square);
1328 // do nothing if we're not draggable
1329 if (cfg.draggable !== true) return;
1331 var square = target.getAttribute('data-square');
1333 // no piece on this square
1334 if (validSquare(square) !== true ||
1335 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1339 beginDraggingPiece(square, CURRENT_POSITION[square],
1340 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1343 function mousemoveWindow(e) {
1344 // do nothing if we are not dragging a piece
1345 if (DRAGGING_A_PIECE !== true) return;
1347 updateDraggedPiece(e.pageX, e.pageY);
1350 function touchmoveWindow(e) {
1351 // do nothing if we are not dragging a piece
1352 if (DRAGGING_A_PIECE !== true) return;
1354 // prevent screen from scrolling
1357 updateDraggedPiece(e.changedTouches[0].pageX,
1358 e.changedTouches[0].pageY);
1361 function mouseupWindow(e) {
1362 // do nothing if we are not dragging a piece
1363 if (DRAGGING_A_PIECE !== true) return;
1366 var location = isXYOnSquare(e.pageX, e.pageY);
1368 stopDraggedPiece(location);
1371 function touchendWindow(e) {
1372 // do nothing if we are not dragging a piece
1373 if (DRAGGING_A_PIECE !== true) return;
1376 var location = isXYOnSquare(e.changedTouches[0].pageX,
1377 e.changedTouches[0].pageY);
1379 stopDraggedPiece(location);
1382 function mouseenterSquare(e) {
1383 let target = e.target.closest('.' + CSS.square);
1388 // do not fire this event if we are dragging a piece
1389 // NOTE: this should never happen, but it's a safeguard
1390 if (DRAGGING_A_PIECE !== false) return;
1392 if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1393 typeof cfg.onMouseoverSquare !== 'function') return;
1396 var square = target.getAttribute('data-square');
1398 // NOTE: this should never happen; defensive
1399 if (validSquare(square) !== true) return;
1401 // get the piece on this square
1403 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1404 piece = CURRENT_POSITION[square];
1407 // execute their function
1408 cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1409 CURRENT_ORIENTATION);
1412 function mouseleaveSquare(e) {
1413 let target = e.target.closest('.' + CSS.square);
1418 // do not fire this event if we are dragging a piece
1419 // NOTE: this should never happen, but it's a safeguard
1420 if (DRAGGING_A_PIECE !== false) return;
1422 if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1423 typeof cfg.onMouseoutSquare !== 'function') return;
1426 var square = target.getAttribute('data-square');
1428 // NOTE: this should never happen; defensive
1429 if (validSquare(square) !== true) return;
1431 // get the piece on this square
1433 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1434 piece = CURRENT_POSITION[square];
1437 // execute their function
1438 cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1439 CURRENT_ORIENTATION);
1442 //------------------------------------------------------------------------------
1444 //------------------------------------------------------------------------------
1446 function addEvents() {
1447 // prevent browser "image drag"
1448 let stopDefault = (e) => {
1449 if (e.target.matches('.' + CSS.piece)) {
1453 document.body.addEventListener('mousedown', stopDefault);
1454 document.body.addEventListener('mousemove', stopDefault);
1456 // mouse drag pieces
1457 boardEl.addEventListener('mousedown', mousedownSquare);
1459 // mouse enter / leave square
1460 boardEl.addEventListener('mouseenter', mouseenterSquare);
1461 boardEl.addEventListener('mouseleave', mouseleaveSquare);
1463 window.addEventListener('mousemove', mousemoveWindow);
1464 window.addEventListener('mouseup', mouseupWindow);
1466 // touch drag pieces
1467 if (isTouchDevice() === true) {
1468 boardEl.addEventListener('touchstart', touchstartSquare);
1469 window.addEventListener('touchmove', touchmoveWindow);
1470 window.addEventListener('touchend', touchendWindow);
1474 function initDom() {
1475 // build board and save it in memory
1476 containerEl.innerHTML = buildBoardContainer();
1477 boardEl = containerEl.querySelector('.' + CSS.board);
1479 // create the drag piece
1480 var draggedPieceId = createId();
1481 document.body.append(buildPiece('wP', true, draggedPieceId));
1482 draggedPieceEl = document.getElementById(draggedPieceId);
1484 // get the border size
1485 BOARD_BORDER_SIZE = parseInt(boardEl.style.borderLeftWidth, 10);
1487 // set the size and draw the board
1492 if (checkDeps() !== true ||
1493 expandConfig() !== true) return;
1495 // create unique IDs for all the elements we will create
1505 // return the widget object
1508 }; // end window.ChessBoard
1510 // expose util functions
1511 window.ChessBoard.fenToObj = fenToObj;
1512 window.ChessBoard.objToFen = objToFen;
1514 })(); // end anonymous wrapper