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 for dropOffBoard is 'snapback'
378 if (cfg.dropOffBoard !== 'trash') {
379 cfg.dropOffBoard = 'snapback';
382 // default piece theme is wikipedia
383 if (cfg.hasOwnProperty('pieceTheme') !== true ||
384 (typeof cfg.pieceTheme !== 'string' &&
385 typeof cfg.pieceTheme !== 'function')) {
386 cfg.pieceTheme = 'img/chesspieces/wikipedia/{piece}.png';
390 if (cfg.hasOwnProperty('appearSpeed') !== true ||
391 validAnimationSpeed(cfg.appearSpeed) !== true) {
392 cfg.appearSpeed = 200;
394 if (cfg.hasOwnProperty('moveSpeed') !== true ||
395 validAnimationSpeed(cfg.moveSpeed) !== true) {
398 if (cfg.hasOwnProperty('snapbackSpeed') !== true ||
399 validAnimationSpeed(cfg.snapbackSpeed) !== true) {
400 cfg.snapbackSpeed = 50;
402 if (cfg.hasOwnProperty('snapSpeed') !== true ||
403 validAnimationSpeed(cfg.snapSpeed) !== true) {
406 if (cfg.hasOwnProperty('trashSpeed') !== true ||
407 validAnimationSpeed(cfg.trashSpeed) !== true) {
408 cfg.trashSpeed = 100;
411 // make sure position is valid
412 if (cfg.hasOwnProperty('position') === true) {
413 if (cfg.position === 'start') {
414 CURRENT_POSITION = deepCopy(START_POSITION);
417 else if (validFen(cfg.position) === true) {
418 CURRENT_POSITION = fenToObj(cfg.position);
421 else if (validPositionObject(cfg.position) === true) {
422 CURRENT_POSITION = deepCopy(cfg.position);
426 error(7263, 'Invalid value passed to config.position.', cfg.position);
433 //------------------------------------------------------------------------------
435 //------------------------------------------------------------------------------
437 // calculates square size based on the width of the container
438 // got a little CSS black magic here, so let me explain:
439 // get the width of the container element (could be anything), reduce by 1 for
440 // fudge factor, and then keep reducing until we find an exact mod 8 for
442 function calculateSquareSize() {
443 var containerWidth = parseInt(getComputedStyle(containerEl).width, 10);
445 // defensive, prevent infinite loop
446 if (! containerWidth || containerWidth <= 0) {
451 var boardWidth = containerWidth - 1;
453 while (boardWidth % 8 !== 0 && boardWidth > 0) {
457 return (boardWidth / 8);
460 // create random IDs for elements
461 function createElIds() {
462 // squares on the board
463 for (var i = 0; i < COLUMNS.length; i++) {
464 for (var j = 1; j <= 8; j++) {
465 var square = COLUMNS[i] + j;
466 SQUARE_ELS_IDS[square] = square + '-' + createId();
471 //------------------------------------------------------------------------------
473 //------------------------------------------------------------------------------
475 function buildBoardContainer() {
476 var html = '<div class="' + CSS.chessboard + '">';
478 html += '<div class="' + CSS.board + '"></div>';
486 var buildSquare = function(color, size, id) {
487 var html = '<div class="' + CSS.square + ' ' + CSSColor[color] + '" ' +
488 'style="width: ' + size + 'px; height: ' + size + 'px" ' +
491 if (cfg.showNotation === true) {
501 function buildBoard(orientation) {
502 if (orientation !== 'black') {
503 orientation = 'white';
508 // algebraic notation / orientation
509 var alpha = deepCopy(COLUMNS);
511 if (orientation === 'black') {
516 var squareColor = 'white';
517 for (var i = 0; i < 8; i++) {
518 html += '<div class="' + CSS.row + '">';
519 for (var j = 0; j < 8; j++) {
520 var square = alpha[j] + row;
522 html += '<div class="' + CSS.square + ' ' + CSSColor[squareColor] + ' ' +
523 'square-' + square + '" ' +
524 'style="width: ' + SQUARE_SIZE + 'px; height: ' + SQUARE_SIZE + 'px" ' +
525 'id="' + SQUARE_ELS_IDS[square] + '" ' +
526 'data-square="' + square + '">';
528 if (cfg.showNotation === true) {
530 if ((orientation === 'white' && row === 1) ||
531 (orientation === 'black' && row === 8)) {
532 html += '<div class="' + CSS.notation + ' ' + CSS.alpha + '">' +
538 html += '<div class="' + CSS.notation + ' ' + CSS.numeric + '">' +
543 html += '</div>'; // end .square
545 squareColor = (squareColor === 'white' ? 'black' : 'white');
547 html += '<div class="' + CSS.clearfix + '"></div></div>';
549 squareColor = (squareColor === 'white' ? 'black' : 'white');
551 if (orientation === 'white') {
562 function buildPieceImgSrc(piece) {
563 if (typeof cfg.pieceTheme === 'function') {
564 return cfg.pieceTheme(piece);
567 if (typeof cfg.pieceTheme === 'string') {
568 return cfg.pieceTheme.replace(/{piece}/g, piece);
571 // NOTE: this should never happen
572 error(8272, 'Unable to build image source for cfg.pieceTheme.');
577 * @param {!string} piece
578 * @param {boolean=} hidden
579 * @param {!string=} id
581 function buildPiece(piece, hidden, id) {
582 let img = document.createElement('img');
583 img.src = buildPieceImgSrc(piece);
584 if (id && typeof id === 'string') {
585 img.setAttribute('id', id);
587 img.setAttribute('alt', '');
588 img.classList.add(CSS.piece);
589 img.setAttribute('data-piece', piece);
590 img.style.width = SQUARE_SIZE + 'px';
591 img.style.height = SQUARE_SIZE + 'px';
592 if (hidden === true) {
593 img.style.display = 'none';
598 //------------------------------------------------------------------------------
600 //------------------------------------------------------------------------------
602 function offset(el) { // From https://youmightnotneedjquery.com/.
603 let box = el.getBoundingClientRect();
604 let docElem = document.documentElement;
606 top: box.top + window.pageYOffset - docElem.clientTop,
607 left: box.left + window.pageXOffset - docElem.clientLeft
611 function animateSquareToSquare(src, dest, piece, completeFn) {
612 // get information about the source and destination squares
613 var srcSquareEl = document.getElementById(SQUARE_ELS_IDS[src]);
614 var srcSquarePosition = offset(srcSquareEl);
615 var destSquareEl = document.getElementById(SQUARE_ELS_IDS[dest]);
616 var destSquarePosition = offset(destSquareEl);
618 // create the animated piece and absolutely position it
619 // over the source square
620 var animatedPieceId = createId();
621 document.body.append(buildPiece(piece, true, animatedPieceId));
622 var animatedPieceEl = document.getElementById(animatedPieceId);
623 animatedPieceEl.style.display = null;
624 animatedPieceEl.style.position = 'absolute';
625 animatedPieceEl.style.top = srcSquarePosition.top + 'px';
626 animatedPieceEl.style.left = srcSquarePosition.left + 'px';
628 // remove original piece(s) from source square
629 // TODO: multiple pieces should never really happen, but it will if we are moving
630 // while another animation still isn't done
631 srcSquareEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
634 var complete = function() {
635 // add the "real" piece to the destination square
636 destSquareEl.append(buildPiece(piece));
638 // remove the animated piece
639 animatedPieceEl.remove();
641 // run complete function
642 if (typeof completeFn === 'function') {
647 // animate the piece to the destination square
648 animatedPieceEl.addEventListener('transitionend', complete, {once: true});
649 requestAnimationFrame(() => {
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';
657 function fadeIn(pieces, onFinish) {
658 pieces.forEach((piece) => {
659 piece.style.opacity = 0;
660 piece.style.display = null;
661 piece.addEventListener('transitionend', onFinish, {once: true});
663 requestAnimationFrame(() => {
664 pieces.forEach((piece) => {
665 piece.style.transitionProperty = 'opacity';
666 piece.style.transitionDuration = cfg.appearSpeed + 'ms';
667 piece.style.opacity = 1;
672 function fadeOut(pieces, onFinish) {
673 pieces.forEach((piece) => {
674 piece.style.opacity = 1;
675 piece.style.display = null;
676 piece.addEventListener('transitionend', onFinish, {once: true});
678 requestAnimationFrame(() => {
679 pieces.forEach((piece) => {
680 piece.style.transitionProperty = 'opacity';
681 piece.style.transitionDuration = cfg.trashSpeed + 'ms';
682 piece.style.opacity = 0;
687 // execute an array of animations
688 function doAnimations(a, oldPos, newPos) {
690 function onFinish(e) {
692 e.target.transitionProperty = null;
697 // exit if all the animations aren't finished
698 if (numFinished !== a.length) return;
700 drawPositionInstant();
702 // run their onMoveEnd function
703 if (cfg.hasOwnProperty('onMoveEnd') === true &&
704 typeof cfg.onMoveEnd === 'function') {
705 cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
709 requestAnimationFrame(() => { // Firefox workaround.
710 let fadeout_pieces = [];
711 let fadein_pieces = [];
713 for (var i = 0; i < a.length; i++) {
715 if (a[i].type === 'clear') {
716 document.getElementById(SQUARE_ELS_IDS[a[i].square]).querySelectorAll('.' + CSS.piece).forEach(
717 (piece) => fadeout_pieces.push(piece)
722 if (a[i].type === 'add') {
723 let square = document.getElementById(SQUARE_ELS_IDS[a[i].square]);
724 square.append(buildPiece(a[i].piece, true));
725 let piece = square.querySelector('.' + CSS.piece);
726 fadein_pieces.push(piece);
730 if (a[i].type === 'move') {
731 animateSquareToSquare(a[i].source, a[i].destination, a[i].piece,
736 // TODO: Batch moves as well, not just fade in/out.
737 // (We batch them because requestAnimationFrame seemingly costs real time.)
738 if (fadeout_pieces.length > 0) {
739 fadeOut(fadeout_pieces, onFinish);
741 if (fadein_pieces.length > 0) {
742 fadeIn(fadein_pieces, onFinish);
747 // returns the distance between two squares
748 function squareDistance(s1, s2) {
750 var s1x = COLUMNS.indexOf(s1[0]) + 1;
751 var s1y = parseInt(s1[1], 10);
754 var s2x = COLUMNS.indexOf(s2[0]) + 1;
755 var s2y = parseInt(s2[1], 10);
757 var xDelta = Math.abs(s1x - s2x);
758 var yDelta = Math.abs(s1y - s2y);
760 if (xDelta >= yDelta) return xDelta;
764 // returns the square of the closest instance of piece
765 // returns false if no instance of piece is found in position
766 function findClosestPiece(position, piece, square) {
767 let best_square = false;
769 for (var i = 0; i < COLUMNS.length; i++) {
770 for (var j = 1; j <= 8; j++) {
771 let other_square = COLUMNS[i] + j;
773 if (position[other_square] === piece && square != other_square) {
774 let dist = squareDistance(square, other_square);
775 if (dist < best_dist) {
776 best_square = other_square;
786 // calculate an array of animations that need to happen in order to get
788 function calculateAnimations(pos1, pos2) {
789 // make copies of both
790 pos1 = deepCopy(pos1);
791 pos2 = deepCopy(pos2);
794 var squaresMovedTo = {};
796 // remove pieces that are the same in both positions
797 for (var i in pos2) {
798 if (pos2.hasOwnProperty(i) !== true) continue;
800 if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
806 // find all the "move" animations
807 for (var i in pos2) {
808 if (pos2.hasOwnProperty(i) !== true) continue;
810 var closestPiece = findClosestPiece(pos1, pos2[i], i);
811 if (closestPiece !== false) {
814 source: closestPiece,
819 delete pos1[closestPiece];
821 squaresMovedTo[i] = true;
825 // add pieces to pos2
826 for (var i in pos2) {
827 if (pos2.hasOwnProperty(i) !== true) continue;
838 // clear pieces from pos1
839 for (var i in pos1) {
840 if (pos1.hasOwnProperty(i) !== true) continue;
842 // do not clear a piece if it is on a square that is the result
843 // of a "move", ie: a piece capture
844 if (squaresMovedTo.hasOwnProperty(i) === true) continue;
858 //------------------------------------------------------------------------------
860 //------------------------------------------------------------------------------
862 function drawPositionInstant() {
864 boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
867 for (var i in CURRENT_POSITION) {
868 if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue;
870 document.getElementById(SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i]));
874 function drawBoard() {
875 boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
876 drawPositionInstant();
879 // given a position and a set of moves, return a new position
880 // with the moves executed
881 function calculatePositionFromMoves(position, moves) {
882 position = deepCopy(position);
884 for (var i in moves) {
885 if (moves.hasOwnProperty(i) !== true) continue;
887 // skip the move if the position doesn't have a piece on the source square
888 if (position.hasOwnProperty(i) !== true) continue;
890 var piece = position[i];
892 position[moves[i]] = piece;
898 function setCurrentPosition(position) {
899 var oldPos = deepCopy(CURRENT_POSITION);
900 var newPos = deepCopy(position);
901 var oldFen = objToFen(oldPos);
902 var newFen = objToFen(newPos);
904 // do nothing if no change in position
905 if (oldFen === newFen) return;
907 // run their onChange function
908 if (cfg.hasOwnProperty('onChange') === true &&
909 typeof cfg.onChange === 'function') {
910 cfg.onChange(oldPos, newPos);
914 CURRENT_POSITION = position;
917 function isXYOnSquare(x, y) {
918 for (var i in SQUARE_ELS_OFFSETS) {
919 if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue;
921 var s = SQUARE_ELS_OFFSETS[i];
922 if (x >= s.left && x < s.left + SQUARE_SIZE &&
923 y >= s.top && y < s.top + SQUARE_SIZE) {
931 // records the XY coords of every square into memory
932 function captureSquareOffsets() {
933 SQUARE_ELS_OFFSETS = {};
935 for (var i in SQUARE_ELS_IDS) {
936 if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue;
938 SQUARE_ELS_OFFSETS[i] = offset(document.getElementById(SQUARE_ELS_IDS[i]));
942 function removeSquareHighlights() {
943 boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
944 piece.classList.remove(CSS.highlight1);
945 piece.classList.remove(CSS.highlight2);
949 function snapbackDraggedPiece() {
950 removeSquareHighlights();
952 // animation complete
953 function complete() {
954 drawPositionInstant();
955 draggedPieceEl.style.display = 'none';
957 // run their onSnapbackEnd function
958 if (cfg.hasOwnProperty('onSnapbackEnd') === true &&
959 typeof cfg.onSnapbackEnd === 'function') {
960 cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
961 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
965 // get source square position
966 var sourceSquarePosition =
967 offset(document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]));
969 // animate the piece to the target square
970 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
971 requestAnimationFrame(() => {
972 draggedPieceEl.style.transitionProperty = 'top, left';
973 draggedPieceEl.style.transitionDuration = cfg.snapbackSpeed + 'ms';
974 draggedPieceEl.style.top = sourceSquarePosition.top + 'px';
975 draggedPieceEl.style.left = sourceSquarePosition.left + 'px';
979 DRAGGING_A_PIECE = false;
982 function trashDraggedPiece() {
983 removeSquareHighlights();
985 // remove the source piece
986 var newPosition = deepCopy(CURRENT_POSITION);
987 delete newPosition[DRAGGED_PIECE_SOURCE];
988 setCurrentPosition(newPosition);
990 // redraw the position
991 drawPositionInstant();
993 // hide the dragged piece
994 // FIXME: support this for non-jquery
995 //$(draggedPieceEl).fadeOut(cfg.trashSpeed);
998 DRAGGING_A_PIECE = false;
1001 function dropDraggedPieceOnSquare(square) {
1002 removeSquareHighlights();
1005 var newPosition = deepCopy(CURRENT_POSITION);
1006 delete newPosition[DRAGGED_PIECE_SOURCE];
1007 newPosition[square] = DRAGGED_PIECE;
1008 setCurrentPosition(newPosition);
1010 // get target square information
1011 var targetSquarePosition = offset(document.getElementById(SQUARE_ELS_IDS[square]));
1013 // animation complete
1014 var complete = function() {
1015 drawPositionInstant();
1016 draggedPieceEl.style.display = 'none';
1018 // execute their onSnapEnd function
1019 if (cfg.hasOwnProperty('onSnapEnd') === true &&
1020 typeof cfg.onSnapEnd === 'function') {
1021 requestAnimationFrame(() => { // HACK: so that we don't add event handlers from the callback...
1022 cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
1027 // snap the piece to the target square
1028 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1029 requestAnimationFrame(() => {
1030 draggedPieceEl.style.transitionProperty = 'top, left';
1031 draggedPieceEl.style.transitionDuration = cfg.snapSpeed + 'ms';
1032 draggedPieceEl.style.top = targetSquarePosition.top + 'px';
1033 draggedPieceEl.style.left = targetSquarePosition.left + 'px';
1037 DRAGGING_A_PIECE = false;
1040 function beginDraggingPiece(source, piece, x, y) {
1041 // run their custom onDragStart function
1042 // their custom onDragStart function can cancel drag start
1043 if (typeof cfg.onDragStart === 'function' &&
1044 cfg.onDragStart(source, piece,
1045 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
1050 DRAGGING_A_PIECE = true;
1051 DRAGGED_PIECE = piece;
1052 DRAGGED_PIECE_SOURCE = source;
1053 DRAGGED_PIECE_LOCATION = source;
1055 // capture the x, y coords of all squares in memory
1056 captureSquareOffsets();
1058 // create the dragged piece
1059 draggedPieceEl.setAttribute('src', buildPieceImgSrc(piece));
1060 draggedPieceEl.style.display = null;
1061 draggedPieceEl.style.position = 'absolute';
1062 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1063 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1065 // highlight the source square and hide the piece
1066 let square = document.getElementById(SQUARE_ELS_IDS[source]);
1067 square.classList.add(CSS.highlight1);
1068 square.querySelector('.' + CSS.piece).style.display = 'none';
1071 function updateDraggedPiece(x, y) {
1072 // put the dragged piece over the mouse cursor
1073 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1074 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1077 var location = isXYOnSquare(x, y);
1079 // do nothing if the location has not changed
1080 if (location === DRAGGED_PIECE_LOCATION) return;
1082 // remove highlight from previous square
1083 if (validSquare(DRAGGED_PIECE_LOCATION) === true) {
1084 document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION])
1085 .classList.remove(CSS.highlight2);
1088 // add highlight to new square
1089 if (validSquare(location) === true) {
1090 document.getElementById(SQUARE_ELS_IDS[location]).classList.add(CSS.highlight2);
1094 if (typeof cfg.onDragMove === 'function') {
1095 cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1096 DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1097 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1101 DRAGGED_PIECE_LOCATION = location;
1104 function stopDraggedPiece(location) {
1105 // determine what the action should be
1106 var action = 'drop';
1107 if (location === 'offboard' && cfg.dropOffBoard === 'snapback') {
1108 action = 'snapback';
1110 if (location === 'offboard' && cfg.dropOffBoard === 'trash') {
1114 // run their onDrop function, which can potentially change the drop action
1115 if (cfg.hasOwnProperty('onDrop') === true &&
1116 typeof cfg.onDrop === 'function') {
1117 var newPosition = deepCopy(CURRENT_POSITION);
1119 // source piece was on the board and position is off the board
1120 if (validSquare(DRAGGED_PIECE_SOURCE) === true && location === 'offboard') {
1121 // remove the piece from the board
1122 delete newPosition[DRAGGED_PIECE_SOURCE];
1125 // source piece was on the board and position is on the board
1126 if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1127 validSquare(location) === true) {
1129 delete newPosition[DRAGGED_PIECE_SOURCE];
1130 newPosition[location] = DRAGGED_PIECE;
1133 var oldPosition = deepCopy(CURRENT_POSITION);
1135 var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE,
1136 newPosition, oldPosition, CURRENT_ORIENTATION);
1137 if (result === 'snapback' || result === 'trash') {
1143 if (action === 'snapback') {
1144 snapbackDraggedPiece();
1146 else if (action === 'trash') {
1147 trashDraggedPiece();
1149 else if (action === 'drop') {
1150 dropDraggedPieceOnSquare(location);
1154 //------------------------------------------------------------------------------
1156 //------------------------------------------------------------------------------
1159 widget.clear = function(useAnimation) {
1160 widget.position({}, useAnimation);
1164 // get or set config properties
1165 // TODO: write this, GitHub Issue #1
1166 widget.config = function(arg1, arg2) {
1167 // get the current config
1168 if (arguments.length === 0) {
1169 return deepCopy(cfg);
1174 // remove the widget from the page
1175 widget.destroy = function() {
1177 containerEl.innerHTML = '';
1178 draggedPieceEl.remove();
1181 // shorthand method to get the current FEN
1182 widget.fen = function() {
1183 return widget.position('fen');
1187 widget.flip = function() {
1188 widget.orientation('flip');
1192 // TODO: write this, GitHub Issue #5
1193 widget.highlight = function() {
1199 widget.move = function() {
1200 // no need to throw an error here; just do nothing
1201 if (arguments.length === 0) return;
1203 var useAnimation = true;
1205 // collect the moves into an object
1207 for (var i = 0; i < arguments.length; i++) {
1208 // any "false" to this function means no animations
1209 if (arguments[i] === false) {
1210 useAnimation = false;
1214 // skip invalid arguments
1215 if (validMove(arguments[i]) !== true) {
1216 error(2826, 'Invalid move passed to the move method.', arguments[i]);
1220 var tmp = arguments[i].split('-');
1221 moves[tmp[0]] = tmp[1];
1224 // calculate position from moves
1225 var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1228 widget.position(newPos, useAnimation);
1230 // return the new position object
1234 widget.orientation = function(arg) {
1235 // no arguments, return the current orientation
1236 if (arguments.length === 0) {
1237 return CURRENT_ORIENTATION;
1240 // set to white or black
1241 if (arg === 'white' || arg === 'black') {
1242 CURRENT_ORIENTATION = arg;
1248 if (arg === 'flip') {
1249 CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1254 error(5482, 'Invalid value passed to the orientation method.', arg);
1258 * @param {!string|!Object} position
1259 * @param {boolean=} useAnimation
1261 widget.position = function(position, useAnimation) {
1262 // no arguments, return the current position
1263 if (arguments.length === 0) {
1264 return deepCopy(CURRENT_POSITION);
1267 // get position as FEN
1268 if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1269 return objToFen(CURRENT_POSITION);
1272 // default for useAnimations is true
1273 if (useAnimation !== false) {
1274 useAnimation = true;
1278 if (typeof position === 'string' && position.toLowerCase() === 'start') {
1279 position = deepCopy(START_POSITION);
1282 // convert FEN to position object
1283 if (validFen(position) === true) {
1284 position = fenToObj(position);
1287 // validate position object
1288 if (validPositionObject(position) !== true) {
1289 error(6482, 'Invalid value passed to the position method.', position);
1293 if (useAnimation === true) {
1294 // start the animations
1295 doAnimations(calculateAnimations(CURRENT_POSITION, position),
1296 CURRENT_POSITION, position);
1298 // set the new position
1299 setCurrentPosition(position);
1303 setCurrentPosition(position);
1304 drawPositionInstant();
1308 widget.resize = function() {
1309 // calulate the new square size
1310 SQUARE_SIZE = calculateSquareSize();
1313 boardEl.style.width = (SQUARE_SIZE * 8) + 'px';
1315 // set drag piece size
1316 if (draggedPieceEl !== null) {
1317 draggedPieceEl.style.height = SQUARE_SIZE + 'px';
1318 draggedPieceEl.style.width = SQUARE_SIZE + 'px';
1325 // set the starting position
1326 widget.start = function(useAnimation) {
1327 widget.position('start', useAnimation);
1330 //------------------------------------------------------------------------------
1332 //------------------------------------------------------------------------------
1334 function isTouchDevice() {
1335 return ('ontouchstart' in document.documentElement);
1338 function mousedownSquare(e) {
1339 let target = e.target.closest('.' + CSS.square);
1344 // do nothing if we're not draggable
1345 if (cfg.draggable !== true) return;
1347 var square = target.getAttribute('data-square');
1349 // no piece on this square
1350 if (validSquare(square) !== true ||
1351 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1355 beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1358 function touchstartSquare(e) {
1359 let target = e.target.closest('.' + CSS.square);
1364 // do nothing if we're not draggable
1365 if (cfg.draggable !== true) return;
1367 var square = target.getAttribute('data-square');
1369 // no piece on this square
1370 if (validSquare(square) !== true ||
1371 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1375 beginDraggingPiece(square, CURRENT_POSITION[square],
1376 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1379 function mousemoveWindow(e) {
1380 // do nothing if we are not dragging a piece
1381 if (DRAGGING_A_PIECE !== true) return;
1383 updateDraggedPiece(e.pageX, e.pageY);
1386 function touchmoveWindow(e) {
1387 // do nothing if we are not dragging a piece
1388 if (DRAGGING_A_PIECE !== true) return;
1390 // prevent screen from scrolling
1393 updateDraggedPiece(e.changedTouches[0].pageX,
1394 e.changedTouches[0].pageY);
1397 function mouseupWindow(e) {
1398 // do nothing if we are not dragging a piece
1399 if (DRAGGING_A_PIECE !== true) return;
1402 var location = isXYOnSquare(e.pageX, e.pageY);
1404 stopDraggedPiece(location);
1407 function touchendWindow(e) {
1408 // do nothing if we are not dragging a piece
1409 if (DRAGGING_A_PIECE !== true) return;
1412 var location = isXYOnSquare(e.changedTouches[0].pageX,
1413 e.changedTouches[0].pageY);
1415 stopDraggedPiece(location);
1418 function mouseenterSquare(e) {
1419 let target = e.target.closest('.' + CSS.square);
1424 // do not fire this event if we are dragging a piece
1425 // NOTE: this should never happen, but it's a safeguard
1426 if (DRAGGING_A_PIECE !== false) return;
1428 if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1429 typeof cfg.onMouseoverSquare !== 'function') return;
1432 var square = target.getAttribute('data-square');
1434 // NOTE: this should never happen; defensive
1435 if (validSquare(square) !== true) return;
1437 // get the piece on this square
1439 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1440 piece = CURRENT_POSITION[square];
1443 // execute their function
1444 cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1445 CURRENT_ORIENTATION);
1448 function mouseleaveSquare(e) {
1449 let target = e.target.closest('.' + CSS.square);
1454 // do not fire this event if we are dragging a piece
1455 // NOTE: this should never happen, but it's a safeguard
1456 if (DRAGGING_A_PIECE !== false) return;
1458 if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1459 typeof cfg.onMouseoutSquare !== 'function') return;
1462 var square = target.getAttribute('data-square');
1464 // NOTE: this should never happen; defensive
1465 if (validSquare(square) !== true) return;
1467 // get the piece on this square
1469 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1470 piece = CURRENT_POSITION[square];
1473 // execute their function
1474 cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1475 CURRENT_ORIENTATION);
1478 //------------------------------------------------------------------------------
1480 //------------------------------------------------------------------------------
1482 function addEvents() {
1483 // prevent browser "image drag"
1484 let stopDefault = (e) => {
1485 if (e.target.matches('.' + CSS.piece)) {
1489 document.body.addEventListener('mousedown', stopDefault);
1490 document.body.addEventListener('mousemove', stopDefault);
1492 // mouse drag pieces
1493 boardEl.addEventListener('mousedown', mousedownSquare);
1495 // mouse enter / leave square
1496 boardEl.addEventListener('mouseenter', mouseenterSquare);
1497 boardEl.addEventListener('mouseleave', mouseleaveSquare);
1499 window.addEventListener('mousemove', mousemoveWindow);
1500 window.addEventListener('mouseup', mouseupWindow);
1502 // touch drag pieces
1503 if (isTouchDevice() === true) {
1504 boardEl.addEventListener('touchstart', touchstartSquare);
1505 window.addEventListener('touchmove', touchmoveWindow);
1506 window.addEventListener('touchend', touchendWindow);
1510 function initDom() {
1511 // build board and save it in memory
1512 containerEl.innerHTML = buildBoardContainer();
1513 boardEl = containerEl.querySelector('.' + CSS.board);
1515 // create the drag piece
1516 var draggedPieceId = createId();
1517 document.body.append(buildPiece('wP', true, draggedPieceId));
1518 draggedPieceEl = document.getElementById(draggedPieceId);
1520 // get the border size
1521 BOARD_BORDER_SIZE = parseInt(boardEl.style.borderLeftWidth, 10);
1523 // set the size and draw the board
1528 if (checkDeps() !== true ||
1529 expandConfig() !== true) return;
1531 // create unique IDs for all the elements we will create
1541 // return the widget object
1544 }; // end window.ChessBoard
1546 // expose util functions
1547 window.ChessBoard.fenToObj = fenToObj;
1548 window.ChessBoard.objToFen = objToFen;
1550 })(); // end anonymous wrapper