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) {
155 for (var i = 0; i < 8; i++) {
156 for (var j = 0; j < 8; j++) {
157 var square = COLUMNS[j] + currentRow;
160 if (obj.hasOwnProperty(square) === true) {
165 fen += pieceCodeToFen(obj[square]);
192 window.ChessBoard = function(containerElOrId, cfg) {
197 //------------------------------------------------------------------------------
199 //------------------------------------------------------------------------------
201 var START_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR',
202 START_POSITION = fenToObj(START_FEN);
204 // use unique class names to prevent clashing with anything else on the page
205 // and simplify selectors
207 alpha: 'alpha-d2270',
208 board: 'board-b72b1',
209 chessboard: 'chessboard-63f37',
210 clearfix: 'clearfix-7da63',
211 highlight1: 'highlight1-32417',
212 highlight2: 'highlight2-9c5d2',
213 notation: 'notation-322f9',
214 numeric: 'numeric-fc462',
215 piece: 'piece-417db',
217 square: 'square-55d63'
220 CSSColor['white'] = 'white-1e1d7';
221 CSSColor['black'] = 'black-3c85d';
223 //------------------------------------------------------------------------------
224 // Module Scope Variables
225 //------------------------------------------------------------------------------
232 // constructor return object
235 //------------------------------------------------------------------------------
237 //------------------------------------------------------------------------------
239 var BOARD_BORDER_SIZE = 2,
240 CURRENT_ORIENTATION = 'white',
241 CURRENT_POSITION = {},
244 DRAGGED_PIECE_LOCATION,
245 DRAGGED_PIECE_SOURCE,
246 DRAGGING_A_PIECE = false,
250 //------------------------------------------------------------------------------
252 //------------------------------------------------------------------------------
255 function createId() {
256 return 'chesspiece-id-' + (id_counter++);
259 function deepCopy(thing) {
260 return JSON.parse(JSON.stringify(thing));
263 //------------------------------------------------------------------------------
264 // Validation / Errors
265 //------------------------------------------------------------------------------
268 * @param {!number} code
269 * @param {!string} msg
270 * @param {Object=} obj
272 function error(code, msg, obj) {
273 // do nothing if showErrors is not set
274 if (cfg.hasOwnProperty('showErrors') !== true ||
275 cfg.showErrors === false) {
279 var errorText = 'ChessBoard Error ' + code + ': ' + msg;
282 if (cfg.showErrors === 'console' &&
283 typeof console === 'object' &&
284 typeof console.log === 'function') {
285 console.log(errorText);
286 if (arguments.length >= 2) {
293 if (cfg.showErrors === 'alert') {
295 errorText += '\n\n' + JSON.stringify(obj);
297 window.alert(errorText);
302 if (typeof cfg.showErrors === 'function') {
303 cfg.showErrors(code, msg, obj);
307 // check dependencies
308 function checkDeps() {
309 // if containerId is a string, it must be the ID of a DOM node
310 if (typeof containerElOrId === 'string') {
312 if (containerElOrId === '') {
313 window.alert('ChessBoard Error 1001: ' +
314 'The first argument to ChessBoard() cannot be an empty string.' +
319 // make sure the container element exists in the DOM
320 var el = document.getElementById(containerElOrId);
322 window.alert('ChessBoard Error 1002: Element with id "' +
323 containerElOrId + '" does not exist in the DOM.' +
328 // set the containerEl
332 // else it must be a DOM node
334 containerEl = containerElOrId;
340 function validAnimationSpeed(speed) {
341 if (speed === 'fast' || speed === 'slow') {
345 if ((parseInt(speed, 10) + '') !== (speed + '')) {
352 // validate config / set default options
353 function expandConfig() {
354 if (typeof cfg === 'string' || validPositionObject(cfg) === true) {
360 // default for orientation is white
361 if (cfg.orientation !== 'black') {
362 cfg.orientation = 'white';
364 CURRENT_ORIENTATION = cfg.orientation;
366 // default for showNotation is true
367 if (cfg.showNotation !== false) {
368 cfg.showNotation = true;
371 // default for draggable is false
372 if (cfg.draggable !== true) {
373 cfg.draggable = false;
376 // default piece theme is wikipedia
377 if (cfg.hasOwnProperty('pieceTheme') !== true ||
378 (typeof cfg.pieceTheme !== 'string' &&
379 typeof cfg.pieceTheme !== 'function')) {
380 cfg.pieceTheme = 'img/chesspieces/wikipedia/{piece}.png';
384 if (cfg.hasOwnProperty('appearSpeed') !== true ||
385 validAnimationSpeed(cfg.appearSpeed) !== true) {
386 cfg.appearSpeed = 200;
388 if (cfg.hasOwnProperty('moveSpeed') !== true ||
389 validAnimationSpeed(cfg.moveSpeed) !== true) {
392 if (cfg.hasOwnProperty('snapbackSpeed') !== true ||
393 validAnimationSpeed(cfg.snapbackSpeed) !== true) {
394 cfg.snapbackSpeed = 50;
396 if (cfg.hasOwnProperty('snapSpeed') !== true ||
397 validAnimationSpeed(cfg.snapSpeed) !== true) {
400 if (cfg.hasOwnProperty('trashSpeed') !== true ||
401 validAnimationSpeed(cfg.trashSpeed) !== true) {
402 cfg.trashSpeed = 100;
405 // make sure position is valid
406 if (cfg.hasOwnProperty('position') === true) {
407 if (cfg.position === 'start') {
408 CURRENT_POSITION = deepCopy(START_POSITION);
411 else if (validFen(cfg.position) === true) {
412 CURRENT_POSITION = fenToObj(cfg.position);
415 else if (validPositionObject(cfg.position) === true) {
416 CURRENT_POSITION = deepCopy(cfg.position);
420 error(7263, 'Invalid value passed to config.position.', cfg.position);
427 //------------------------------------------------------------------------------
429 //------------------------------------------------------------------------------
431 // calculates square size based on the width of the container
432 // got a little CSS black magic here, so let me explain:
433 // get the width of the container element (could be anything), reduce by 1 for
434 // fudge factor, and then keep reducing until we find an exact mod 8 for
436 function calculateSquareSize() {
437 var containerWidth = parseInt(getComputedStyle(containerEl).width, 10);
439 // defensive, prevent infinite loop
440 if (! containerWidth || containerWidth <= 0) {
445 var boardWidth = containerWidth - 1;
447 while (boardWidth % 8 !== 0 && boardWidth > 0) {
451 return (boardWidth / 8);
454 // create random IDs for elements
455 function createElIds() {
456 // squares on the board
457 for (var i = 0; i < COLUMNS.length; i++) {
458 for (var j = 1; j <= 8; j++) {
459 var square = COLUMNS[i] + j;
460 SQUARE_ELS_IDS[square] = square + '-' + createId();
465 //------------------------------------------------------------------------------
467 //------------------------------------------------------------------------------
469 function buildBoardContainer() {
470 var html = '<div class="' + CSS.chessboard + '">';
472 html += '<div class="' + CSS.board + '"></div>';
480 var buildSquare = function(color, size, id) {
481 var html = '<div class="' + CSS.square + ' ' + CSSColor[color] + '" ' +
482 'style="width: ' + size + 'px; height: ' + size + 'px" ' +
485 if (cfg.showNotation === true) {
495 function buildBoard(orientation) {
496 if (orientation !== 'black') {
497 orientation = 'white';
502 // algebraic notation / orientation
503 var alpha = deepCopy(COLUMNS);
505 if (orientation === 'black') {
510 var squareColor = 'white';
511 for (var i = 0; i < 8; i++) {
512 html += '<div class="' + CSS.row + '">';
513 for (var j = 0; j < 8; j++) {
514 var square = alpha[j] + row;
516 html += '<div class="' + CSS.square + ' ' + CSSColor[squareColor] + ' ' +
517 'square-' + square + '" ' +
518 'style="width: ' + SQUARE_SIZE + 'px; height: ' + SQUARE_SIZE + 'px" ' +
519 'id="' + SQUARE_ELS_IDS[square] + '" ' +
520 'data-square="' + square + '">';
522 if (cfg.showNotation === true) {
524 if ((orientation === 'white' && row === 1) ||
525 (orientation === 'black' && row === 8)) {
526 html += '<div class="' + CSS.notation + ' ' + CSS.alpha + '">' +
532 html += '<div class="' + CSS.notation + ' ' + CSS.numeric + '">' +
537 html += '</div>'; // end .square
539 squareColor = (squareColor === 'white' ? 'black' : 'white');
541 html += '<div class="' + CSS.clearfix + '"></div></div>';
543 squareColor = (squareColor === 'white' ? 'black' : 'white');
545 if (orientation === 'white') {
556 function buildPieceImgSrc(piece) {
557 if (typeof cfg.pieceTheme === 'function') {
558 return cfg.pieceTheme(piece);
561 if (typeof cfg.pieceTheme === 'string') {
562 return cfg.pieceTheme.replace(/{piece}/g, piece);
565 // NOTE: this should never happen
566 error(8272, 'Unable to build image source for cfg.pieceTheme.');
571 * @param {!string} piece
572 * @param {boolean=} hidden
573 * @param {!string=} id
575 function buildPiece(piece, hidden, id) {
576 let img = document.createElement('img');
577 img.src = buildPieceImgSrc(piece);
578 if (id && typeof id === 'string') {
579 img.setAttribute('id', id);
581 img.setAttribute('alt', '');
582 img.classList.add(CSS.piece);
583 img.setAttribute('data-piece', piece);
584 img.style.width = SQUARE_SIZE + 'px';
585 img.style.height = SQUARE_SIZE + 'px';
586 if (hidden === true) {
587 img.style.display = 'none';
592 //------------------------------------------------------------------------------
594 //------------------------------------------------------------------------------
596 function offset(el) { // From https://youmightnotneedjquery.com/.
597 let box = el.getBoundingClientRect();
598 let docElem = document.documentElement;
600 top: box.top + window.pageYOffset - docElem.clientTop,
601 left: box.left + window.pageXOffset - docElem.clientLeft
605 function animateSquareToSquare(moved_pieces, completeFn) {
607 for (const {source, destination, piece} of moved_pieces) {
608 // get information about the source and destination squares
609 let srcSquareEl = document.getElementById(SQUARE_ELS_IDS[source]);
610 let srcSquarePosition = offset(srcSquareEl);
611 let destSquareEl = document.getElementById(SQUARE_ELS_IDS[destination]);
612 let destSquarePosition = offset(destSquareEl);
614 // create the animated piece and absolutely position it
615 // over the source square
616 let animatedPieceId = createId();
617 document.body.append(buildPiece(piece, true, animatedPieceId));
618 let animatedPieceEl = document.getElementById(animatedPieceId);
619 animatedPieceEl.style.display = null;
620 animatedPieceEl.style.position = 'absolute';
621 animatedPieceEl.style.top = srcSquarePosition.top + 'px';
622 animatedPieceEl.style.left = srcSquarePosition.left + 'px';
624 // remove original piece(s) from source square
625 // TODO: multiple pieces should never really happen, but it will if we are moving
626 // while another animation still isn't done
627 srcSquareEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
630 let complete = function() {
631 // add the "real" piece to the destination square
632 destSquareEl.append(buildPiece(piece));
634 // remove the animated piece
635 animatedPieceEl.remove();
637 // run complete function
638 if (typeof completeFn === 'function') {
643 // animate the piece to the destination square
644 animatedPieceEl.addEventListener('transitionend', complete, {once: true});
645 pieces.push([animatedPieceEl, destSquarePosition]);
647 requestAnimationFrame(() => {
648 for (let [animatedPieceEl, destSquarePosition] of pieces) {
649 animatedPieceEl.style.transitionProperty = 'top, left';
650 animatedPieceEl.style.transitionDuration = cfg.moveSpeed + 'ms';
651 animatedPieceEl.style.top = destSquarePosition.top + 'px';
652 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 = [];
712 let moved_pieces = [];
714 for (var i = 0; i < a.length; i++) {
716 if (a[i].type === 'clear') {
717 document.getElementById(SQUARE_ELS_IDS[a[i].square]).querySelectorAll('.' + CSS.piece).forEach(
718 (piece) => fadeout_pieces.push(piece)
723 if (a[i].type === 'add') {
724 let square = document.getElementById(SQUARE_ELS_IDS[a[i].square]);
725 square.append(buildPiece(a[i].piece, true));
726 let piece = square.querySelector('.' + CSS.piece);
727 fadein_pieces.push(piece);
731 if (a[i].type === 'move') {
732 moved_pieces.push(a[i]);
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);
744 if (moved_pieces.length > 0) {
745 animateSquareToSquare(moved_pieces, onFinish);
750 // returns the distance between two squares
751 function squareDistance(s1, s2) {
753 var s1x = COLUMNS.indexOf(s1[0]) + 1;
754 var s1y = parseInt(s1[1], 10);
757 var s2x = COLUMNS.indexOf(s2[0]) + 1;
758 var s2y = parseInt(s2[1], 10);
760 var xDelta = Math.abs(s1x - s2x);
761 var yDelta = Math.abs(s1y - s2y);
763 if (xDelta >= yDelta) return xDelta;
767 // returns the square of the closest instance of piece
768 // returns false if no instance of piece is found in position
769 function findClosestPiece(position, piece, square) {
770 let best_square = false;
772 for (var i = 0; i < COLUMNS.length; i++) {
773 for (var j = 1; j <= 8; j++) {
774 let other_square = COLUMNS[i] + j;
776 if (position[other_square] === piece && square != other_square) {
777 let dist = squareDistance(square, other_square);
778 if (dist < best_dist) {
779 best_square = other_square;
789 // calculate an array of animations that need to happen in order to get
791 function calculateAnimations(pos1, pos2) {
792 // make copies of both
793 pos1 = deepCopy(pos1);
794 pos2 = deepCopy(pos2);
797 var squaresMovedTo = {};
799 // remove pieces that are the same in both positions
800 for (var i in pos2) {
801 if (pos2.hasOwnProperty(i) !== true) continue;
803 if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
809 // find all the "move" animations
810 for (var i in pos2) {
811 if (pos2.hasOwnProperty(i) !== true) continue;
813 var closestPiece = findClosestPiece(pos1, pos2[i], i);
814 if (closestPiece !== false) {
817 source: closestPiece,
822 delete pos1[closestPiece];
824 squaresMovedTo[i] = true;
828 // add pieces to pos2
829 for (var i in pos2) {
830 if (pos2.hasOwnProperty(i) !== true) continue;
841 // clear pieces from pos1
842 for (var i in pos1) {
843 if (pos1.hasOwnProperty(i) !== true) continue;
845 // do not clear a piece if it is on a square that is the result
846 // of a "move", ie: a piece capture
847 if (squaresMovedTo.hasOwnProperty(i) === true) continue;
861 //------------------------------------------------------------------------------
863 //------------------------------------------------------------------------------
865 function drawPositionInstant() {
867 boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
870 for (var i in CURRENT_POSITION) {
871 if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue;
873 document.getElementById(SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i]));
877 function drawBoard() {
878 boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
879 drawPositionInstant();
882 // given a position and a set of moves, return a new position
883 // with the moves executed
884 function calculatePositionFromMoves(position, moves) {
885 position = deepCopy(position);
887 for (var i in moves) {
888 if (moves.hasOwnProperty(i) !== true) continue;
890 // skip the move if the position doesn't have a piece on the source square
891 if (position.hasOwnProperty(i) !== true) continue;
893 var piece = position[i];
895 position[moves[i]] = piece;
901 function setCurrentPosition(position) {
902 var oldPos = deepCopy(CURRENT_POSITION);
903 var newPos = deepCopy(position);
904 var oldFen = objToFen(oldPos);
905 var newFen = objToFen(newPos);
907 // do nothing if no change in position
908 if (oldFen === newFen) return;
910 // run their onChange function
911 if (cfg.hasOwnProperty('onChange') === true &&
912 typeof cfg.onChange === 'function') {
913 cfg.onChange(oldPos, newPos);
917 CURRENT_POSITION = position;
920 function isXYOnSquare(x, y) {
921 for (var i in SQUARE_ELS_OFFSETS) {
922 if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue;
924 var s = SQUARE_ELS_OFFSETS[i];
925 if (x >= s.left && x < s.left + SQUARE_SIZE &&
926 y >= s.top && y < s.top + SQUARE_SIZE) {
934 // records the XY coords of every square into memory
935 function captureSquareOffsets() {
936 SQUARE_ELS_OFFSETS = {};
938 for (var i in SQUARE_ELS_IDS) {
939 if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue;
941 SQUARE_ELS_OFFSETS[i] = offset(document.getElementById(SQUARE_ELS_IDS[i]));
945 function removeSquareHighlights() {
946 boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
947 piece.classList.remove(CSS.highlight1);
948 piece.classList.remove(CSS.highlight2);
952 function snapbackDraggedPiece() {
953 removeSquareHighlights();
955 // animation complete
956 function complete() {
957 drawPositionInstant();
958 draggedPieceEl.style.display = 'none';
960 // run their onSnapbackEnd function
961 if (cfg.hasOwnProperty('onSnapbackEnd') === true &&
962 typeof cfg.onSnapbackEnd === 'function') {
963 cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
964 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
968 // get source square position
969 var sourceSquarePosition =
970 offset(document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]));
972 // animate the piece to the target square
973 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
974 requestAnimationFrame(() => {
975 draggedPieceEl.style.transitionProperty = 'top, left';
976 draggedPieceEl.style.transitionDuration = cfg.snapbackSpeed + 'ms';
977 draggedPieceEl.style.top = sourceSquarePosition.top + 'px';
978 draggedPieceEl.style.left = sourceSquarePosition.left + 'px';
982 DRAGGING_A_PIECE = false;
985 function dropDraggedPieceOnSquare(square) {
986 removeSquareHighlights();
989 var newPosition = deepCopy(CURRENT_POSITION);
990 delete newPosition[DRAGGED_PIECE_SOURCE];
991 newPosition[square] = DRAGGED_PIECE;
992 setCurrentPosition(newPosition);
994 // get target square information
995 var targetSquarePosition = offset(document.getElementById(SQUARE_ELS_IDS[square]));
997 // animation complete
998 var complete = function() {
999 drawPositionInstant();
1000 draggedPieceEl.style.display = 'none';
1002 // execute their onSnapEnd function
1003 if (cfg.hasOwnProperty('onSnapEnd') === true &&
1004 typeof cfg.onSnapEnd === 'function') {
1005 requestAnimationFrame(() => { // HACK: so that we don't add event handlers from the callback...
1006 cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
1011 // snap the piece to the target square
1012 draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1013 requestAnimationFrame(() => {
1014 draggedPieceEl.style.transitionProperty = 'top, left';
1015 draggedPieceEl.style.transitionDuration = cfg.snapSpeed + 'ms';
1016 draggedPieceEl.style.top = targetSquarePosition.top + 'px';
1017 draggedPieceEl.style.left = targetSquarePosition.left + 'px';
1021 DRAGGING_A_PIECE = false;
1024 function beginDraggingPiece(source, piece, x, y) {
1025 // run their custom onDragStart function
1026 // their custom onDragStart function can cancel drag start
1027 if (typeof cfg.onDragStart === 'function' &&
1028 cfg.onDragStart(source, piece,
1029 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
1034 DRAGGING_A_PIECE = true;
1035 DRAGGED_PIECE = piece;
1036 DRAGGED_PIECE_SOURCE = source;
1037 DRAGGED_PIECE_LOCATION = source;
1039 // capture the x, y coords of all squares in memory
1040 captureSquareOffsets();
1042 // create the dragged piece
1043 draggedPieceEl.setAttribute('src', buildPieceImgSrc(piece));
1044 draggedPieceEl.style.display = null;
1045 draggedPieceEl.style.position = 'absolute';
1046 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1047 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1049 // highlight the source square and hide the piece
1050 let square = document.getElementById(SQUARE_ELS_IDS[source]);
1051 square.classList.add(CSS.highlight1);
1052 square.querySelector('.' + CSS.piece).style.display = 'none';
1055 function updateDraggedPiece(x, y) {
1056 // put the dragged piece over the mouse cursor
1057 draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1058 draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1061 var location = isXYOnSquare(x, y);
1063 // do nothing if the location has not changed
1064 if (location === DRAGGED_PIECE_LOCATION) return;
1066 // remove highlight from previous square
1067 if (validSquare(DRAGGED_PIECE_LOCATION) === true) {
1068 document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION])
1069 .classList.remove(CSS.highlight2);
1072 // add highlight to new square
1073 if (validSquare(location) === true) {
1074 document.getElementById(SQUARE_ELS_IDS[location]).classList.add(CSS.highlight2);
1078 if (typeof cfg.onDragMove === 'function') {
1079 cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1080 DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1081 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1085 DRAGGED_PIECE_LOCATION = location;
1088 function stopDraggedPiece(location) {
1089 // determine what the action should be
1090 var action = 'drop';
1091 if (location === 'offboard' && cfg.dropOffBoard === 'snapback') {
1092 action = 'snapback';
1095 // run their onDrop function, which can potentially change the drop action
1096 if (cfg.hasOwnProperty('onDrop') === true &&
1097 typeof cfg.onDrop === 'function') {
1098 var newPosition = deepCopy(CURRENT_POSITION);
1100 // source piece was on the board and position is on the board
1101 if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1102 validSquare(location) === true) {
1104 delete newPosition[DRAGGED_PIECE_SOURCE];
1105 newPosition[location] = DRAGGED_PIECE;
1108 var oldPosition = deepCopy(CURRENT_POSITION);
1110 var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE,
1111 newPosition, oldPosition, CURRENT_ORIENTATION);
1112 if (result === 'snapback') {
1118 if (action === 'snapback') {
1119 snapbackDraggedPiece();
1121 else if (action === 'drop') {
1122 dropDraggedPieceOnSquare(location);
1126 //------------------------------------------------------------------------------
1128 //------------------------------------------------------------------------------
1131 widget.clear = function(useAnimation) {
1132 widget.position({}, useAnimation);
1136 // get or set config properties
1137 // TODO: write this, GitHub Issue #1
1138 widget.config = function(arg1, arg2) {
1139 // get the current config
1140 if (arguments.length === 0) {
1141 return deepCopy(cfg);
1146 // remove the widget from the page
1147 widget.destroy = function() {
1149 containerEl.innerHTML = '';
1150 draggedPieceEl.remove();
1153 // shorthand method to get the current FEN
1154 widget.fen = function() {
1155 return widget.position('fen');
1159 widget.flip = function() {
1160 widget.orientation('flip');
1164 // TODO: write this, GitHub Issue #5
1165 widget.highlight = function() {
1171 widget.move = function() {
1172 // no need to throw an error here; just do nothing
1173 if (arguments.length === 0) return;
1175 var useAnimation = true;
1177 // collect the moves into an object
1179 for (var i = 0; i < arguments.length; i++) {
1180 // any "false" to this function means no animations
1181 if (arguments[i] === false) {
1182 useAnimation = false;
1186 // skip invalid arguments
1187 if (validMove(arguments[i]) !== true) {
1188 error(2826, 'Invalid move passed to the move method.', arguments[i]);
1192 var tmp = arguments[i].split('-');
1193 moves[tmp[0]] = tmp[1];
1196 // calculate position from moves
1197 var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1200 widget.position(newPos, useAnimation);
1202 // return the new position object
1206 widget.orientation = function(arg) {
1207 // no arguments, return the current orientation
1208 if (arguments.length === 0) {
1209 return CURRENT_ORIENTATION;
1212 // set to white or black
1213 if (arg === 'white' || arg === 'black') {
1214 CURRENT_ORIENTATION = arg;
1220 if (arg === 'flip') {
1221 CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1226 error(5482, 'Invalid value passed to the orientation method.', arg);
1230 * @param {!string|!Object} position
1231 * @param {boolean=} useAnimation
1233 widget.position = function(position, useAnimation) {
1234 // no arguments, return the current position
1235 if (arguments.length === 0) {
1236 return deepCopy(CURRENT_POSITION);
1239 // get position as FEN
1240 if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1241 return objToFen(CURRENT_POSITION);
1244 // default for useAnimations is true
1245 if (useAnimation !== false) {
1246 useAnimation = true;
1250 if (typeof position === 'string' && position.toLowerCase() === 'start') {
1251 position = deepCopy(START_POSITION);
1254 // convert FEN to position object
1255 if (validFen(position) === true) {
1256 position = fenToObj(position);
1259 // validate position object
1260 if (validPositionObject(position) !== true) {
1261 error(6482, 'Invalid value passed to the position method.', position);
1265 if (useAnimation === true) {
1266 // start the animations
1267 doAnimations(calculateAnimations(CURRENT_POSITION, position),
1268 CURRENT_POSITION, position);
1270 // set the new position
1271 setCurrentPosition(position);
1275 setCurrentPosition(position);
1276 drawPositionInstant();
1280 widget.resize = function() {
1281 // calulate the new square size
1282 SQUARE_SIZE = calculateSquareSize();
1285 boardEl.style.width = (SQUARE_SIZE * 8) + 'px';
1287 // set drag piece size
1288 if (draggedPieceEl !== null) {
1289 draggedPieceEl.style.height = SQUARE_SIZE + 'px';
1290 draggedPieceEl.style.width = SQUARE_SIZE + 'px';
1297 // set the starting position
1298 widget.start = function(useAnimation) {
1299 widget.position('start', useAnimation);
1302 //------------------------------------------------------------------------------
1304 //------------------------------------------------------------------------------
1306 function isTouchDevice() {
1307 return ('ontouchstart' in document.documentElement);
1310 function mousedownSquare(e) {
1311 let target = e.target.closest('.' + CSS.square);
1316 // do nothing if we're not draggable
1317 if (cfg.draggable !== true) return;
1319 var square = target.getAttribute('data-square');
1321 // no piece on this square
1322 if (validSquare(square) !== true ||
1323 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1327 beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1330 function touchstartSquare(e) {
1331 let target = e.target.closest('.' + CSS.square);
1336 // do nothing if we're not draggable
1337 if (cfg.draggable !== true) return;
1339 var square = target.getAttribute('data-square');
1341 // no piece on this square
1342 if (validSquare(square) !== true ||
1343 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1347 beginDraggingPiece(square, CURRENT_POSITION[square],
1348 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1351 function mousemoveWindow(e) {
1352 // do nothing if we are not dragging a piece
1353 if (DRAGGING_A_PIECE !== true) return;
1355 updateDraggedPiece(e.pageX, e.pageY);
1358 function touchmoveWindow(e) {
1359 // do nothing if we are not dragging a piece
1360 if (DRAGGING_A_PIECE !== true) return;
1362 // prevent screen from scrolling
1365 updateDraggedPiece(e.changedTouches[0].pageX,
1366 e.changedTouches[0].pageY);
1369 function mouseupWindow(e) {
1370 // do nothing if we are not dragging a piece
1371 if (DRAGGING_A_PIECE !== true) return;
1374 var location = isXYOnSquare(e.pageX, e.pageY);
1376 stopDraggedPiece(location);
1379 function touchendWindow(e) {
1380 // do nothing if we are not dragging a piece
1381 if (DRAGGING_A_PIECE !== true) return;
1384 var location = isXYOnSquare(e.changedTouches[0].pageX,
1385 e.changedTouches[0].pageY);
1387 stopDraggedPiece(location);
1390 function mouseenterSquare(e) {
1391 let target = e.target.closest('.' + CSS.square);
1396 // do not fire this event if we are dragging a piece
1397 // NOTE: this should never happen, but it's a safeguard
1398 if (DRAGGING_A_PIECE !== false) return;
1400 if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1401 typeof cfg.onMouseoverSquare !== 'function') return;
1404 var square = target.getAttribute('data-square');
1406 // NOTE: this should never happen; defensive
1407 if (validSquare(square) !== true) return;
1409 // get the piece on this square
1411 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1412 piece = CURRENT_POSITION[square];
1415 // execute their function
1416 cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1417 CURRENT_ORIENTATION);
1420 function mouseleaveSquare(e) {
1421 let target = e.target.closest('.' + CSS.square);
1426 // do not fire this event if we are dragging a piece
1427 // NOTE: this should never happen, but it's a safeguard
1428 if (DRAGGING_A_PIECE !== false) return;
1430 if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1431 typeof cfg.onMouseoutSquare !== 'function') return;
1434 var square = target.getAttribute('data-square');
1436 // NOTE: this should never happen; defensive
1437 if (validSquare(square) !== true) return;
1439 // get the piece on this square
1441 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1442 piece = CURRENT_POSITION[square];
1445 // execute their function
1446 cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1447 CURRENT_ORIENTATION);
1450 //------------------------------------------------------------------------------
1452 //------------------------------------------------------------------------------
1454 function addEvents() {
1455 // prevent browser "image drag"
1456 let stopDefault = (e) => {
1457 if (e.target.matches('.' + CSS.piece)) {
1461 document.body.addEventListener('mousedown', stopDefault);
1462 document.body.addEventListener('mousemove', stopDefault);
1464 // mouse drag pieces
1465 boardEl.addEventListener('mousedown', mousedownSquare);
1467 // mouse enter / leave square
1468 boardEl.addEventListener('mouseenter', mouseenterSquare);
1469 boardEl.addEventListener('mouseleave', mouseleaveSquare);
1471 window.addEventListener('mousemove', mousemoveWindow);
1472 window.addEventListener('mouseup', mouseupWindow);
1474 // touch drag pieces
1475 if (isTouchDevice() === true) {
1476 boardEl.addEventListener('touchstart', touchstartSquare);
1477 window.addEventListener('touchmove', touchmoveWindow);
1478 window.addEventListener('touchend', touchendWindow);
1482 function initDom() {
1483 // build board and save it in memory
1484 containerEl.innerHTML = buildBoardContainer();
1485 boardEl = containerEl.querySelector('.' + CSS.board);
1487 // create the drag piece
1488 var draggedPieceId = createId();
1489 document.body.append(buildPiece('wP', true, draggedPieceId));
1490 draggedPieceEl = document.getElementById(draggedPieceId);
1492 // get the border size
1493 BOARD_BORDER_SIZE = parseInt(boardEl.style.borderLeftWidth, 10);
1495 // set the size and draw the board
1500 if (checkDeps() !== true ||
1501 expandConfig() !== true) return;
1503 // create unique IDs for all the elements we will create
1513 // return the widget object
1516 }; // end window.ChessBoard
1518 // expose util functions
1519 window.ChessBoard.fenToObj = fenToObj;
1520 window.ChessBoard.objToFen = objToFen;
1522 })(); // end anonymous wrapper