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 highlight1: 'highlight1-32417',
211 highlight2: 'highlight2-9c5d2',
212 notation: 'notation-322f9',
213 numeric: 'numeric-fc462',
214 piece: 'piece-417db',
215 square: 'square-55d63'
218 CSSColor['white'] = 'white-1e1d7';
219 CSSColor['black'] = 'black-3c85d';
221 //------------------------------------------------------------------------------
222 // Module Scope Variables
223 //------------------------------------------------------------------------------
230 // constructor return object
233 //------------------------------------------------------------------------------
235 //------------------------------------------------------------------------------
237 var CURRENT_ORIENTATION = 'white',
238 CURRENT_POSITION = {},
240 DRAGGED_PIECE_LOCATION,
241 DRAGGED_PIECE_SOURCE,
242 DRAGGING_A_PIECE = false,
243 PIECE_ON_SQUARE = {};
245 //------------------------------------------------------------------------------
247 //------------------------------------------------------------------------------
250 function createId() {
251 return 'chesspiece-id-' + (id_counter++);
254 function deepCopy(thing) {
255 return JSON.parse(JSON.stringify(thing));
258 //------------------------------------------------------------------------------
259 // Validation / Errors
260 //------------------------------------------------------------------------------
263 * @param {!number} code
264 * @param {!string} msg
265 * @param {Object=} obj
267 function error(code, msg, obj) {
268 // do nothing if showErrors is not set
269 if (cfg.hasOwnProperty('showErrors') !== true ||
270 cfg.showErrors === false) {
274 var errorText = 'ChessBoard Error ' + code + ': ' + msg;
277 if (cfg.showErrors === 'console' &&
278 typeof console === 'object' &&
279 typeof console.log === 'function') {
280 console.log(errorText);
281 if (arguments.length >= 2) {
288 if (cfg.showErrors === 'alert') {
290 errorText += '\n\n' + JSON.stringify(obj);
292 window.alert(errorText);
297 if (typeof cfg.showErrors === 'function') {
298 cfg.showErrors(code, msg, obj);
302 // check dependencies
303 function checkDeps() {
304 // if containerId is a string, it must be the ID of a DOM node
305 if (typeof containerElOrId === 'string') {
307 if (containerElOrId === '') {
308 window.alert('ChessBoard Error 1001: ' +
309 'The first argument to ChessBoard() cannot be an empty string.' +
314 // make sure the container element exists in the DOM
315 var el = document.getElementById(containerElOrId);
317 window.alert('ChessBoard Error 1002: Element with id "' +
318 containerElOrId + '" does not exist in the DOM.' +
323 // set the containerEl
327 // else it must be a DOM node
329 containerEl = containerElOrId;
335 function validAnimationSpeed(speed) {
336 if (speed === 'fast' || speed === 'slow') {
340 if ((parseInt(speed, 10) + '') !== (speed + '')) {
347 // validate config / set default options
348 function expandConfig() {
349 if (typeof cfg === 'string' || validPositionObject(cfg) === true) {
355 // default for orientation is white
356 if (cfg.orientation !== 'black') {
357 cfg.orientation = 'white';
359 CURRENT_ORIENTATION = cfg.orientation;
361 // default for showNotation is true
362 if (cfg.showNotation !== false) {
363 cfg.showNotation = true;
366 // default for draggable is false
367 if (cfg.draggable !== true) {
368 cfg.draggable = false;
371 // default piece theme is wikipedia
372 if (cfg.hasOwnProperty('pieceTheme') !== true ||
373 (typeof cfg.pieceTheme !== 'string' &&
374 typeof cfg.pieceTheme !== 'function')) {
375 cfg.pieceTheme = 'img/chesspieces/wikipedia/{piece}.png';
379 if (cfg.hasOwnProperty('appearSpeed') !== true ||
380 validAnimationSpeed(cfg.appearSpeed) !== true) {
381 cfg.appearSpeed = 200;
383 if (cfg.hasOwnProperty('moveSpeed') !== true ||
384 validAnimationSpeed(cfg.moveSpeed) !== true) {
387 if (cfg.hasOwnProperty('snapbackSpeed') !== true ||
388 validAnimationSpeed(cfg.snapbackSpeed) !== true) {
389 cfg.snapbackSpeed = 50;
391 if (cfg.hasOwnProperty('snapSpeed') !== true ||
392 validAnimationSpeed(cfg.snapSpeed) !== true) {
395 if (cfg.hasOwnProperty('trashSpeed') !== true ||
396 validAnimationSpeed(cfg.trashSpeed) !== true) {
397 cfg.trashSpeed = 100;
400 // make sure position is valid
401 if (cfg.hasOwnProperty('position') === true) {
402 if (cfg.position === 'start') {
403 CURRENT_POSITION = deepCopy(START_POSITION);
406 else if (validFen(cfg.position) === true) {
407 CURRENT_POSITION = fenToObj(cfg.position);
410 else if (validPositionObject(cfg.position) === true) {
411 CURRENT_POSITION = deepCopy(cfg.position);
415 error(7263, 'Invalid value passed to config.position.', cfg.position);
422 //------------------------------------------------------------------------------
424 //------------------------------------------------------------------------------
426 function buildBoardContainer() {
427 var html = '<div class="' + CSS.chessboard + '">';
429 html += '<div class="' + CSS.board + '"></div>';
436 function buildBoard(orientation) {
437 if (orientation !== 'black') {
438 orientation = 'white';
443 // algebraic notation / orientation
444 var alpha = deepCopy(COLUMNS);
446 if (orientation === 'black') {
451 var squareColor = 'white';
452 for (var i = 0; i < 8; i++) {
453 for (var j = 0; j < 8; j++) {
454 var square = alpha[j] + row;
456 html += '<div class="' + CSS.square + ' ' + CSSColor[squareColor] + ' ' +
457 'square-' + square + '" ' +
458 'style="grid-row: ' + (i+1) + '; grid-column: ' + (j+1) + ';" ' +
459 'data-square="' + square + '">';
461 if (cfg.showNotation === true) {
463 if ((orientation === 'white' && row === 1) ||
464 (orientation === 'black' && row === 8)) {
465 let bottom = 'calc(' + (12.5 * (7-i)) + '% + 1px)';
466 let right = 'calc(' + (12.5 * (7-j)) + '% + 3px)';
467 html += '<div class="' + CSS.alpha + '" style="right: ' + right + '; bottom: ' + bottom + ';">' +
473 let top = 'calc(' + (12.5 * i) + '% + 2px)';
474 let left = 'calc(' + (12.5 * j) + '% + 2px)';
475 html += '<div class="' + CSS.numeric + '" style="top: ' + top + '; left: ' + left + ';">' +
480 html += '</div>'; // end .square
482 squareColor = (squareColor === 'white' ? 'black' : 'white');
485 squareColor = (squareColor === 'white' ? 'black' : 'white');
487 if (orientation === 'white') {
498 function buildPieceImgSrc(piece) {
499 if (typeof cfg.pieceTheme === 'function') {
500 return cfg.pieceTheme(piece);
503 if (typeof cfg.pieceTheme === 'string') {
504 return cfg.pieceTheme.replace(/{piece}/g, piece);
507 // NOTE: this should never happen
508 error(8272, 'Unable to build image source for cfg.pieceTheme.');
513 * @param {!string} piece
514 * @param {boolean=} hidden
516 function buildPiece(piece, hidden) {
517 let img = document.createElement('img');
518 img.src = buildPieceImgSrc(piece);
519 img.setAttribute('alt', '');
520 img.classList.add(CSS.piece);
521 if (hidden === true) {
522 img.style.display = 'none';
527 //------------------------------------------------------------------------------
529 //------------------------------------------------------------------------------
531 function offset(el) { // From https://youmightnotneedjquery.com/.
532 let box = el.getBoundingClientRect();
533 let docElem = document.documentElement;
535 top: box.top + window.pageYOffset - docElem.clientTop,
536 left: box.left + window.pageXOffset - docElem.clientLeft
540 function findSquarePosition(square) {
541 let s1 = square.split('');
542 var s1x = COLUMNS.indexOf(s1[0]);
543 var s1y = parseInt(s1[1], 10) - 1;
544 if (CURRENT_ORIENTATION === 'white') {
548 top: (s1y * 12.5) + '%',
549 left: (s1x * 12.5) + '%',
553 function animateSquareToSquare(move_pieces, complete) {
554 for (const [piece, destination] of move_pieces) {
555 // Move it to the end of the stack, which changes the implicit z-index
556 // so that it will go on top of any pieces it's replacing.
558 boardEl.appendChild(piece);
560 // animate the piece to the destination square
561 piece.addEventListener('transitionend', complete, {once: true});
563 requestAnimationFrame(() => {
564 for (const [piece, destination] of move_pieces) {
565 let destSquarePosition = findSquarePosition(destination);
566 piece.style.transitionProperty = 'top, left';
567 piece.style.transitionDuration = cfg.moveSpeed + 'ms';
568 piece.style.top = destSquarePosition.top;
569 piece.style.left = destSquarePosition.left;
574 function fadeIn(pieces, onFinish) {
575 pieces.forEach((piece) => {
576 piece.style.opacity = 0;
577 piece.style.display = null;
578 piece.addEventListener('transitionend', onFinish, {once: true});
580 requestAnimationFrame(() => {
581 pieces.forEach((piece) => {
582 piece.style.transitionProperty = 'opacity';
583 piece.style.transitionDuration = cfg.appearSpeed + 'ms';
584 piece.style.opacity = 1;
589 function fadeOut(pieces, onFinish) {
590 pieces.forEach((piece) => {
591 piece.style.opacity = 1;
592 piece.style.display = null;
593 piece.addEventListener('transitionend', onFinish, {once: true});
595 requestAnimationFrame(() => {
596 pieces.forEach((piece) => {
597 piece.style.transitionProperty = 'opacity';
598 piece.style.transitionDuration = cfg.trashSpeed + 'ms';
599 piece.style.opacity = 0;
604 // execute an array of animations
605 function doAnimations(a, oldPos, newPos) {
606 let fadeout_pieces = [];
607 let fadein_pieces = [];
608 let move_pieces = [];
609 let squares_to_clear = [];
610 let squares_to_fill = {};
611 let removed_pieces = [];
613 for (var i = 0; i < a.length; i++) {
615 if (a[i].type === 'clear') {
616 let square = a[i].square;
617 let piece = PIECE_ON_SQUARE[square];
619 fadeout_pieces.push(piece);
620 squares_to_clear.push(square);
621 removed_pieces.push(piece);
626 if (a[i].type === 'add') {
627 let square = a[i].square;
628 let pos = findSquarePosition(square);
629 let piece = buildPiece(a[i].piece, true);
630 piece.style.left = pos.left;
631 piece.style.top = pos.top;
632 boardEl.append(piece);
633 squares_to_fill[square] = piece;
634 fadein_pieces.push(piece);
638 if (a[i].type === 'move') {
639 let piece = PIECE_ON_SQUARE[a[i].source];
640 move_pieces.push([piece, a[i].destination]);
641 squares_to_clear.push(a[i].source);
642 squares_to_fill[a[i].destination] = piece;
644 // This is O(n²), but OK.
645 let replaced_piece = PIECE_ON_SQUARE[a[i].destination];
646 if (replaced_piece && !a.some(e => e.type === 'move' && e.source === a[i].destination)) {
647 removed_pieces.push(replaced_piece);
652 for (const square of squares_to_clear) {
653 delete PIECE_ON_SQUARE[square];
655 for (const [square, piece] of Object.entries(squares_to_fill)) {
656 PIECE_ON_SQUARE[square] = piece;
657 piece.setAttribute('data-square', square);
661 function onFinish(e) {
663 e.target.transitionProperty = null;
664 e.target.transitionDuration = null;
669 // exit if all the animations aren't finished
670 if (numFinished !== a.length) return;
672 for (let piece of removed_pieces) {
676 // run their onMoveEnd function
677 if (cfg.hasOwnProperty('onMoveEnd') === true &&
678 typeof cfg.onMoveEnd === 'function') {
679 cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
683 requestAnimationFrame(() => { // Firefox workaround.
684 if (fadeout_pieces.length > 0) {
685 fadeOut(fadeout_pieces, onFinish);
687 if (fadein_pieces.length > 0) {
688 fadeIn(fadein_pieces, onFinish);
690 if (move_pieces.length > 0) {
691 animateSquareToSquare(move_pieces, onFinish);
696 // returns the distance between two squares
697 function squareDistance(s1, s2) {
699 var s1x = COLUMNS.indexOf(s1[0]) + 1;
700 var s1y = parseInt(s1[1], 10);
703 var s2x = COLUMNS.indexOf(s2[0]) + 1;
704 var s2y = parseInt(s2[1], 10);
706 var xDelta = Math.abs(s1x - s2x);
707 var yDelta = Math.abs(s1y - s2y);
709 if (xDelta >= yDelta) return xDelta;
713 // returns the square of the closest instance of piece
714 // returns false if no instance of piece is found in position
715 function findClosestPiece(position, piece, square) {
716 let best_square = false;
718 for (var i = 0; i < COLUMNS.length; i++) {
719 for (var j = 1; j <= 8; j++) {
720 let other_square = COLUMNS[i] + j;
722 if (position[other_square] === piece && square != other_square) {
723 let dist = squareDistance(square, other_square);
724 if (dist < best_dist) {
725 best_square = other_square;
735 // calculate an array of animations that need to happen in order to get
737 function calculateAnimations(pos1, pos2) {
738 // make copies of both
739 pos1 = deepCopy(pos1);
740 pos2 = deepCopy(pos2);
743 var squaresMovedTo = {};
745 // remove pieces that are the same in both positions
746 for (var i in pos2) {
747 if (pos2.hasOwnProperty(i) !== true) continue;
749 if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
755 // find all the "move" animations
756 for (var i in pos2) {
757 if (pos2.hasOwnProperty(i) !== true) continue;
759 var closestPiece = findClosestPiece(pos1, pos2[i], i);
760 if (closestPiece !== false) {
763 source: closestPiece,
768 delete pos1[closestPiece];
770 squaresMovedTo[i] = true;
774 // add pieces to pos2
775 for (var i in pos2) {
776 if (pos2.hasOwnProperty(i) !== true) continue;
787 // clear pieces from pos1
788 for (var i in pos1) {
789 if (pos1.hasOwnProperty(i) !== true) continue;
791 // do not clear a piece if it is on a square that is the result
792 // of a "move", ie: a piece capture
793 if (squaresMovedTo.hasOwnProperty(i) === true) continue;
807 //------------------------------------------------------------------------------
809 //------------------------------------------------------------------------------
811 function drawPositionInstant() {
813 boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
816 for (const [square, piece] of Object.entries(CURRENT_POSITION)) {
817 let pos = findSquarePosition(square);
818 let pieceEl = buildPiece(piece);
819 pieceEl.style.left = pos.left;
820 pieceEl.style.top = pos.top;
821 pieceEl.setAttribute('data-square', square);
822 boardEl.append(pieceEl);
823 PIECE_ON_SQUARE[square] = pieceEl;
827 function drawBoard() {
828 boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
829 drawPositionInstant();
832 // given a position and a set of moves, return a new position
833 // with the moves executed
834 function calculatePositionFromMoves(position, moves) {
835 position = deepCopy(position);
837 for (var i in moves) {
838 if (moves.hasOwnProperty(i) !== true) continue;
840 // skip the move if the position doesn't have a piece on the source square
841 if (position.hasOwnProperty(i) !== true) continue;
843 var piece = position[i];
845 position[moves[i]] = piece;
851 function setCurrentPosition(position) {
852 var oldPos = deepCopy(CURRENT_POSITION);
853 var newPos = deepCopy(position);
854 var oldFen = objToFen(oldPos);
855 var newFen = objToFen(newPos);
857 // do nothing if no change in position
858 if (oldFen === newFen) return;
860 // run their onChange function
861 if (cfg.hasOwnProperty('onChange') === true &&
862 typeof cfg.onChange === 'function') {
863 cfg.onChange(oldPos, newPos);
867 CURRENT_POSITION = position;
870 function removeSquareHighlights() {
871 boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
872 piece.classList.remove(CSS.highlight1);
873 piece.classList.remove(CSS.highlight2);
877 function snapbackDraggedPiece() {
878 removeSquareHighlights();
880 // animation complete
881 function complete() {
882 drawPositionInstant();
884 // run their onSnapbackEnd function
885 if (cfg.hasOwnProperty('onSnapbackEnd') === true &&
886 typeof cfg.onSnapbackEnd === 'function') {
887 cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
888 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
892 // get source square position
893 var sourceSquarePosition = findSquarePosition(DRAGGED_PIECE_SOURCE);
895 // animate the piece to the target square
896 DRAGGED_PIECE.addEventListener('transitionend', complete, {once: true});
897 requestAnimationFrame(() => {
898 DRAGGED_PIECE.style.transitionProperty = 'top, left';
899 DRAGGED_PIECE.style.transitionDuration = cfg.snapbackSpeed + 'ms';
900 DRAGGED_PIECE.style.top = sourceSquarePosition.top;
901 DRAGGED_PIECE.style.left = sourceSquarePosition.left;
905 DRAGGING_A_PIECE = false;
908 function dropDraggedPieceOnSquare(square) {
909 removeSquareHighlights();
910 DRAGGING_A_PIECE = false;
912 if (DRAGGED_PIECE_SOURCE === square) {
913 // Nothing to do, but call onSnapEnd anyway
914 if (cfg.hasOwnProperty('onSnapEnd') === true && typeof cfg.onSnapEnd === 'function') {
915 cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
921 var newPosition = deepCopy(CURRENT_POSITION);
922 newPosition[square] = newPosition[DRAGGED_PIECE_SOURCE];
923 delete newPosition[DRAGGED_PIECE_SOURCE];
924 setCurrentPosition(newPosition);
926 delete PIECE_ON_SQUARE[DRAGGED_PIECE_SOURCE];
927 PIECE_ON_SQUARE[square] = DRAGGED_PIECE;
928 DRAGGED_PIECE.setAttribute('data-square', square);
930 // get target square information
931 var targetSquarePosition = findSquarePosition(square);
933 // animation complete
934 var complete = function() {
935 drawPositionInstant();
937 // execute their onSnapEnd function
938 if (cfg.hasOwnProperty('onSnapEnd') === true &&
939 typeof cfg.onSnapEnd === 'function') {
940 requestAnimationFrame(() => { // HACK: so that we don't add event handlers from the callback...
941 cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
946 // snap the piece to the target square
947 DRAGGED_PIECE.addEventListener('transitionend', complete, {once: true});
948 requestAnimationFrame(() => {
949 DRAGGED_PIECE.style.transitionProperty = 'top, left';
950 DRAGGED_PIECE.style.transitionDuration = cfg.snapSpeed + 'ms';
951 DRAGGED_PIECE.style.top = targetSquarePosition.top;
952 DRAGGED_PIECE.style.left = targetSquarePosition.left;
956 function beginDraggingPiece(source, piece, x, y) {
957 // run their custom onDragStart function
958 // their custom onDragStart function can cancel drag start
959 if (typeof cfg.onDragStart === 'function' &&
960 cfg.onDragStart(source, piece,
961 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
966 DRAGGING_A_PIECE = true;
967 DRAGGED_PIECE = PIECE_ON_SQUARE[source];
968 DRAGGED_PIECE_SOURCE = source;
969 DRAGGED_PIECE_LOCATION = source;
970 DRAGGED_PIECE.style.transitionProperty = null;
971 DRAGGED_PIECE.style.transitionDuration = null;
973 // Move it to the end of the stack, which changes the implicit z-index
974 // so that it will go on top of any pieces it's replacing.
975 DRAGGED_PIECE.remove();
976 boardEl.appendChild(DRAGGED_PIECE);
978 // highlight the source square
979 let square = document.querySelector('.' + CSS.square + '[data-square="' + source + '"]');
980 square.classList.add(CSS.highlight1);
983 function findSquareFromEvent(pageX, pageY) {
984 let o = offset(boardEl);
985 let x = pageX - o.left;
986 let y = pageY - o.top;
991 left: Math.floor(x * 8 / boardEl.getBoundingClientRect().width),
992 top: Math.floor(y * 8 / boardEl.getBoundingClientRect().width)
994 if (CURRENT_ORIENTATION === 'white') {
995 position.top = 7 - position.top;
997 if (position.left >= 0 && position.left < 8 && position.top >= 0 && position.top < 8) {
998 position.square = COLUMNS[position.left] + (position.top + 1);
1000 position.square = 'offboard';
1005 function updateDraggedPiece(position) {
1006 // put the dragged piece over the mouse cursor
1007 DRAGGED_PIECE.style.left = 'calc(' + position.x + 'px - 6.25%)';
1008 DRAGGED_PIECE.style.top = 'calc(' + position.y + 'px - 6.25%)';
1010 // do nothing if the location has not changed
1011 if (position === DRAGGED_PIECE_LOCATION) return;
1013 // remove highlight from previous square
1014 if (validSquare(DRAGGED_PIECE_LOCATION)) {
1015 document.querySelector('.' + CSS.square + '[data-square="' + DRAGGED_PIECE_LOCATION + '"]')
1016 .classList.remove(CSS.highlight2);
1019 // add highlight to new square
1020 if (validSquare(position.square)) {
1021 document.querySelector('.' + CSS.square + '[data-square="' + position.square + '"]')
1022 .classList.add(CSS.highlight2);
1026 if (typeof cfg.onDragMove === 'function') {
1027 cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1028 DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1029 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1033 DRAGGED_PIECE_LOCATION = position.square;
1036 function stopDraggedPiece(location) {
1037 // determine what the action should be
1038 var action = 'drop';
1039 if (location.square === 'offboard' && cfg.dropOffBoard === 'snapback') {
1040 action = 'snapback';
1043 // run their onDrop function, which can potentially change the drop action
1044 if (cfg.hasOwnProperty('onDrop') === true &&
1045 typeof cfg.onDrop === 'function') {
1046 var newPosition = deepCopy(CURRENT_POSITION);
1048 // source piece was on the board and position is on the board
1049 if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1050 validSquare(location.square) === true) {
1052 delete newPosition[DRAGGED_PIECE_SOURCE];
1053 newPosition[location.square] = DRAGGED_PIECE;
1054 if (location.square !== DRAGGED_PIECE_SOURCE) {
1055 PIECE_ON_SQUARE[location.square] = PIECE_ON_SQUARE[DRAGGED_PIECE_SOURCE];
1056 DRAGGED_PIECE.setAttribute('data-square', location.square);
1057 delete PIECE_ON_SQUARE[DRAGGED_PIECE_SOURCE];
1061 var oldPosition = deepCopy(CURRENT_POSITION);
1063 var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location.square, DRAGGED_PIECE,
1064 newPosition, oldPosition, CURRENT_ORIENTATION);
1065 if (result === 'snapback') {
1071 if (action === 'snapback') {
1072 snapbackDraggedPiece();
1074 else if (action === 'drop') {
1075 dropDraggedPieceOnSquare(location.square);
1079 //------------------------------------------------------------------------------
1081 //------------------------------------------------------------------------------
1084 widget.clear = function(useAnimation) {
1085 widget.position({}, useAnimation);
1089 // get or set config properties
1090 // TODO: write this, GitHub Issue #1
1091 widget.config = function(arg1, arg2) {
1092 // get the current config
1093 if (arguments.length === 0) {
1094 return deepCopy(cfg);
1099 // remove the widget from the page
1100 widget.destroy = function() {
1102 containerEl.innerHTML = '';
1103 draggedPieceEl.remove();
1106 // shorthand method to get the current FEN
1107 widget.fen = function() {
1108 return widget.position('fen');
1112 widget.flip = function() {
1113 widget.orientation('flip');
1117 // TODO: write this, GitHub Issue #5
1118 widget.highlight = function() {
1124 widget.move = function() {
1125 // no need to throw an error here; just do nothing
1126 if (arguments.length === 0) return;
1128 var useAnimation = true;
1130 // collect the moves into an object
1132 for (var i = 0; i < arguments.length; i++) {
1133 // any "false" to this function means no animations
1134 if (arguments[i] === false) {
1135 useAnimation = false;
1139 // skip invalid arguments
1140 if (validMove(arguments[i]) !== true) {
1141 error(2826, 'Invalid move passed to the move method.', arguments[i]);
1145 var tmp = arguments[i].split('-');
1146 moves[tmp[0]] = tmp[1];
1149 // calculate position from moves
1150 var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1153 widget.position(newPos, useAnimation);
1155 // return the new position object
1159 widget.orientation = function(arg) {
1160 // no arguments, return the current orientation
1161 if (arguments.length === 0) {
1162 return CURRENT_ORIENTATION;
1165 // set to white or black
1166 if (arg === 'white' || arg === 'black') {
1167 CURRENT_ORIENTATION = arg;
1173 if (arg === 'flip') {
1174 CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1179 error(5482, 'Invalid value passed to the orientation method.', arg);
1183 * @param {!string|!Object} position
1184 * @param {boolean=} useAnimation
1186 widget.position = function(position, useAnimation) {
1187 // no arguments, return the current position
1188 if (arguments.length === 0) {
1189 return deepCopy(CURRENT_POSITION);
1192 // get position as FEN
1193 if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1194 return objToFen(CURRENT_POSITION);
1197 // default for useAnimations is true
1198 if (useAnimation !== false) {
1199 useAnimation = true;
1203 if (typeof position === 'string' && position.toLowerCase() === 'start') {
1204 position = deepCopy(START_POSITION);
1207 // convert FEN to position object
1208 if (validFen(position) === true) {
1209 position = fenToObj(position);
1212 // validate position object
1213 if (validPositionObject(position) !== true) {
1214 error(6482, 'Invalid value passed to the position method.', position);
1218 if (useAnimation === true) {
1219 // start the animations
1220 doAnimations(calculateAnimations(CURRENT_POSITION, position),
1221 CURRENT_POSITION, position);
1223 // set the new position
1224 setCurrentPosition(position);
1228 setCurrentPosition(position);
1229 drawPositionInstant();
1233 widget.resize = function() {
1238 // set the starting position
1239 widget.start = function(useAnimation) {
1240 widget.position('start', useAnimation);
1243 //------------------------------------------------------------------------------
1245 //------------------------------------------------------------------------------
1247 function isTouchDevice() {
1248 return ('ontouchstart' in document.documentElement);
1251 function mousedownSquare(e) {
1252 let square = e.target.getAttribute('data-square');
1254 // no piece on this square
1255 if (!validSquare(square) ||
1256 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1260 // do nothing if we're not draggable
1261 if (cfg.draggable !== true) return;
1263 beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1266 function touchstartSquare(e) {
1267 let target = e.target.closest('.' + CSS.square);
1272 // do nothing if we're not draggable
1273 if (cfg.draggable !== true) return;
1275 var square = target.getAttribute('data-square');
1277 // no piece on this square
1278 if (validSquare(square) !== true ||
1279 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1283 beginDraggingPiece(square, CURRENT_POSITION[square],
1284 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1287 function mousemoveWindow(e) {
1288 // do nothing if we are not dragging a piece
1289 if (DRAGGING_A_PIECE !== true) return;
1291 updateDraggedPiece(findSquareFromEvent(e.pageX, e.pageY));
1294 function touchmoveWindow(e) {
1295 // do nothing if we are not dragging a piece
1296 if (DRAGGING_A_PIECE !== true) return;
1298 // prevent screen from scrolling
1301 updateDraggedPiece(findSquareFromEvent(e.changedTouches[0].pageX,
1302 e.changedTouches[0].pageY));
1305 function mouseupWindow(e) {
1306 // do nothing if we are not dragging a piece
1307 if (DRAGGING_A_PIECE !== true) return;
1309 stopDraggedPiece(findSquareFromEvent(e.pageX, e.pageY));
1312 function touchendWindow(e) {
1313 // do nothing if we are not dragging a piece
1314 if (DRAGGING_A_PIECE !== true) return;
1317 var location = isXYOnSquare(e.changedTouches[0].pageX,
1318 e.changedTouches[0].pageY);
1320 stopDraggedPiece(findSquareFromEvent(e.changedTouches[0].pageX,
1321 e.changedTouches[0].pageY));
1324 function mouseenterSquare(e) {
1325 let target = e.target.closest('.' + CSS.square);
1330 // do not fire this event if we are dragging a piece
1331 // NOTE: this should never happen, but it's a safeguard
1332 if (DRAGGING_A_PIECE !== false) return;
1334 if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1335 typeof cfg.onMouseoverSquare !== 'function') return;
1338 var square = target.getAttribute('data-square');
1340 // NOTE: this should never happen; defensive
1341 if (validSquare(square) !== true) return;
1343 // get the piece on this square
1345 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1346 piece = CURRENT_POSITION[square];
1349 // execute their function
1350 cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1351 CURRENT_ORIENTATION);
1354 function mouseleaveSquare(e) {
1355 let target = e.target.closest('.' + CSS.square);
1360 // do not fire this event if we are dragging a piece
1361 // NOTE: this should never happen, but it's a safeguard
1362 if (DRAGGING_A_PIECE !== false) return;
1364 if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1365 typeof cfg.onMouseoutSquare !== 'function') return;
1368 var square = target.getAttribute('data-square');
1370 // NOTE: this should never happen; defensive
1371 if (validSquare(square) !== true) return;
1373 // get the piece on this square
1375 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1376 piece = CURRENT_POSITION[square];
1379 // execute their function
1380 cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1381 CURRENT_ORIENTATION);
1384 //------------------------------------------------------------------------------
1386 //------------------------------------------------------------------------------
1388 function addEvents() {
1389 // prevent browser "image drag"
1390 let stopDefault = (e) => {
1391 if (e.target.matches('.' + CSS.piece)) {
1395 document.body.addEventListener('mousedown', stopDefault);
1396 document.body.addEventListener('mousemove', stopDefault);
1398 // mouse drag pieces
1399 boardEl.addEventListener('mousedown', mousedownSquare);
1401 // mouse enter / leave square
1402 boardEl.addEventListener('mouseenter', mouseenterSquare);
1403 boardEl.addEventListener('mouseleave', mouseleaveSquare);
1405 window.addEventListener('mousemove', mousemoveWindow);
1406 window.addEventListener('mouseup', mouseupWindow);
1408 // touch drag pieces
1409 if (isTouchDevice() === true) {
1410 boardEl.addEventListener('touchstart', touchstartSquare);
1411 window.addEventListener('touchmove', touchmoveWindow);
1412 window.addEventListener('touchend', touchendWindow);
1416 function initDom() {
1417 // build board and save it in memory
1418 containerEl.innerHTML = buildBoardContainer();
1419 boardEl = containerEl.querySelector('.' + CSS.board);
1421 // set the size and draw the board
1426 if (checkDeps() !== true ||
1427 expandConfig() !== true) return;
1436 // return the widget object
1439 }; // end window.ChessBoard
1441 // expose util functions
1442 window.ChessBoard.fenToObj = fenToObj;
1443 window.ChessBoard.objToFen = objToFen;
1445 })(); // end anonymous wrapper