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]) && validSquare(tmp[1]);
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)) continue;
72 if (!validSquare(i) || !validPieceCode(pos[i])) {
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)) {
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)) {
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)) {
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') ||
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)) {
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') ||
373 (typeof cfg.pieceTheme !== 'string' &&
374 typeof cfg.pieceTheme !== 'function')) {
375 cfg.pieceTheme = 'img/chesspieces/wikipedia/{piece}.png';
379 if (!cfg.hasOwnProperty('appearSpeed') ||
380 !validAnimationSpeed(cfg.appearSpeed)) {
381 cfg.appearSpeed = 200;
383 if (!cfg.hasOwnProperty('moveSpeed') ||
384 !validAnimationSpeed(cfg.moveSpeed)) {
387 if (!cfg.hasOwnProperty('snapbackSpeed') ||
388 !validAnimationSpeed(cfg.snapbackSpeed)) {
389 cfg.snapbackSpeed = 50;
391 if (!cfg.hasOwnProperty('snapSpeed') ||
392 !validAnimationSpeed(cfg.snapSpeed)) {
395 if (!cfg.hasOwnProperty('trashSpeed') ||
396 !validAnimationSpeed(cfg.trashSpeed)) {
397 cfg.trashSpeed = 100;
400 // make sure position is valid
401 if (cfg.hasOwnProperty('position')) {
402 if (cfg.position === 'start') {
403 CURRENT_POSITION = deepCopy(START_POSITION);
406 else if (validFen(cfg.position)) {
407 CURRENT_POSITION = fenToObj(cfg.position);
410 else if (validPositionObject(cfg.position)) {
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) {
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 // execute an array of animations
554 function doAnimations(a, oldPos, newPos) {
555 let fadeout_pieces = [];
556 let fadein_pieces = [];
557 let move_pieces = [];
558 let squares_to_clear = [];
559 let squares_to_fill = {};
560 let removed_pieces = [];
562 for (var i = 0; i < a.length; i++) {
564 if (a[i].type === 'clear') {
565 let square = a[i].square;
566 let piece = PIECE_ON_SQUARE[square];
568 fadeout_pieces.push(piece);
569 squares_to_clear.push(square);
570 removed_pieces.push(piece);
575 if (a[i].type === 'add') {
576 let square = a[i].square;
577 let pos = findSquarePosition(square);
578 let piece = buildPiece(a[i].piece, true);
579 piece.style.left = pos.left;
580 piece.style.top = pos.top;
581 boardEl.append(piece);
582 squares_to_fill[square] = piece;
583 fadein_pieces.push(piece);
587 if (a[i].type === 'move') {
588 let piece = PIECE_ON_SQUARE[a[i].source];
589 move_pieces.push([piece, a[i].destination]);
590 squares_to_clear.push(a[i].source);
591 squares_to_fill[a[i].destination] = piece;
593 // This is O(n²), but OK.
594 let replaced_piece = PIECE_ON_SQUARE[a[i].destination];
595 if (replaced_piece && !a.some(e => e.type === 'move' && e.source === a[i].destination)) {
596 removed_pieces.push(replaced_piece);
601 for (const square of squares_to_clear) {
602 delete PIECE_ON_SQUARE[square];
604 for (const [square, piece] of Object.entries(squares_to_fill)) {
605 PIECE_ON_SQUARE[square] = piece;
606 piece.setAttribute('data-square', square);
610 function onFinish(e, opt_force) {
611 if (++numFinished === a.length) {
612 for (let piece of removed_pieces) {
616 // run their onMoveEnd function
617 if (cfg.hasOwnProperty('onMoveEnd') &&
618 typeof cfg.onMoveEnd === 'function') {
619 cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
624 fadein_pieces.forEach((piece) => {
625 piece.style.display = null;
626 piece.style.opacity = 1;
628 [ { opacity: 0 }, { opacity: 1 } ],
629 { duration: cfg.appearSpeed }
630 ).addEventListener('finish', onFinish);
632 fadeout_pieces.forEach((piece) => {
633 piece.style.display = null;
634 piece.style.opacity = 0;
636 [ { opacity: 1 }, { opacity: 0 } ],
637 { duration: cfg.trashSpeed }
638 ).addEventListener('finish', onFinish);
640 for (const [piece, destination] of move_pieces) {
641 // Move it to the end of the stack, which changes the implicit z-index
642 // so that it will go on top of any pieces it's replacing.
644 boardEl.appendChild(piece);
646 let destSquarePosition = findSquarePosition(destination);
649 { top: piece.style.top, left: piece.style.left },
650 { top: destSquarePosition.top, left: destSquarePosition.left }
652 { duration: cfg.moveSpeed }
653 ).addEventListener('finish', onFinish);
654 piece.style.top = destSquarePosition.top;
655 piece.style.left = destSquarePosition.left;
659 // returns the distance between two squares
660 function squareDistance(s1, s2) {
662 var s1x = COLUMNS.indexOf(s1[0]) + 1;
663 var s1y = parseInt(s1[1], 10);
666 var s2x = COLUMNS.indexOf(s2[0]) + 1;
667 var s2y = parseInt(s2[1], 10);
669 var xDelta = Math.abs(s1x - s2x);
670 var yDelta = Math.abs(s1y - s2y);
672 if (xDelta >= yDelta) return xDelta;
676 // returns the square of the closest instance of piece
677 // returns false if no instance of piece is found in position
678 function findClosestPiece(position, piece, square) {
679 let best_square = false;
681 for (var i = 0; i < COLUMNS.length; i++) {
682 for (var j = 1; j <= 8; j++) {
683 let other_square = COLUMNS[i] + j;
685 if (position[other_square] === piece && square != other_square) {
686 let dist = squareDistance(square, other_square);
687 if (dist < best_dist) {
688 best_square = other_square;
698 // calculate an array of animations that need to happen in order to get
700 function calculateAnimations(pos1, pos2) {
701 // make copies of both
702 pos1 = deepCopy(pos1);
703 pos2 = deepCopy(pos2);
706 var squaresMovedTo = {};
708 // remove pieces that are the same in both positions
709 for (var i in pos2) {
710 if (!pos2.hasOwnProperty(i)) continue;
712 if (pos1.hasOwnProperty(i) && pos1[i] === pos2[i]) {
718 // find all the "move" animations
719 for (var i in pos2) {
720 if (!pos2.hasOwnProperty(i)) continue;
722 var closestPiece = findClosestPiece(pos1, pos2[i], i);
723 if (closestPiece !== false) {
726 source: closestPiece,
731 delete pos1[closestPiece];
733 squaresMovedTo[i] = true;
737 // add pieces to pos2
738 for (var i in pos2) {
739 if (!pos2.hasOwnProperty(i)) continue;
750 // clear pieces from pos1
751 for (var i in pos1) {
752 if (!pos1.hasOwnProperty(i)) continue;
754 // do not clear a piece if it is on a square that is the result
755 // of a "move", ie: a piece capture
756 if (squaresMovedTo.hasOwnProperty(i)) continue;
770 //------------------------------------------------------------------------------
772 //------------------------------------------------------------------------------
774 function drawPositionInstant() {
776 boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
779 for (const [square, piece] of Object.entries(CURRENT_POSITION)) {
780 let pos = findSquarePosition(square);
781 let pieceEl = buildPiece(piece);
782 pieceEl.style.left = pos.left;
783 pieceEl.style.top = pos.top;
784 pieceEl.setAttribute('data-square', square);
785 boardEl.append(pieceEl);
786 PIECE_ON_SQUARE[square] = pieceEl;
790 function drawBoard() {
791 boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
792 drawPositionInstant();
795 // given a position and a set of moves, return a new position
796 // with the moves executed
797 function calculatePositionFromMoves(position, moves) {
798 position = deepCopy(position);
800 for (var i in moves) {
801 if (!moves.hasOwnProperty(i)) continue;
803 // skip the move if the position doesn't have a piece on the source square
804 if (!position.hasOwnProperty(i)) continue;
806 var piece = position[i];
808 position[moves[i]] = piece;
814 function setCurrentPosition(position) {
815 var oldPos = deepCopy(CURRENT_POSITION);
816 var newPos = deepCopy(position);
817 var oldFen = objToFen(oldPos);
818 var newFen = objToFen(newPos);
820 // do nothing if no change in position
821 if (oldFen === newFen) return;
823 // run their onChange function
824 if (cfg.hasOwnProperty('onChange') &&
825 typeof cfg.onChange === 'function') {
826 cfg.onChange(oldPos, newPos);
830 CURRENT_POSITION = position;
833 function removeSquareHighlights() {
834 boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
835 piece.classList.remove(CSS.highlight1);
836 piece.classList.remove(CSS.highlight2);
840 function snapbackDraggedPiece() {
841 removeSquareHighlights();
843 // animation complete
844 function complete() {
845 drawPositionInstant();
847 // run their onSnapbackEnd function
848 if (cfg.hasOwnProperty('onSnapbackEnd') &&
849 typeof cfg.onSnapbackEnd === 'function') {
850 cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
851 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
855 // get source square position
856 var sourceSquarePosition = findSquarePosition(DRAGGED_PIECE_SOURCE);
858 // animate the piece to the target square
859 DRAGGED_PIECE.animate(
861 { top: DRAGGED_PIECE.style.top, left: DRAGGED_PIECE.style.left },
862 { top: sourceSquarePosition.top, left: sourceSquarePosition.left }
864 { duration: cfg.snapbackSpeed }
865 ).addEventListener('finish', complete);
866 DRAGGED_PIECE.style.top = sourceSquarePosition.top;
867 DRAGGED_PIECE.style.left = sourceSquarePosition.left;
870 DRAGGING_A_PIECE = false;
873 function dropDraggedPieceOnSquare(square) {
874 removeSquareHighlights();
875 DRAGGING_A_PIECE = false;
877 if (DRAGGED_PIECE_SOURCE === square) {
878 // Nothing to do, but call onSnapEnd anyway
879 if (cfg.hasOwnProperty('onSnapEnd') && typeof cfg.onSnapEnd === 'function') {
880 cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
886 var newPosition = deepCopy(CURRENT_POSITION);
887 newPosition[square] = newPosition[DRAGGED_PIECE_SOURCE];
888 delete newPosition[DRAGGED_PIECE_SOURCE];
889 setCurrentPosition(newPosition);
891 delete PIECE_ON_SQUARE[DRAGGED_PIECE_SOURCE];
892 PIECE_ON_SQUARE[square] = DRAGGED_PIECE;
893 DRAGGED_PIECE.setAttribute('data-square', square);
895 // get target square information
896 var targetSquarePosition = findSquarePosition(square);
898 // animation complete
899 var complete = function() {
900 drawPositionInstant();
902 // execute their onSnapEnd function
903 if (cfg.hasOwnProperty('onSnapEnd') &&
904 typeof cfg.onSnapEnd === 'function') {
905 requestAnimationFrame(() => { // HACK: so that we don't add event handlers from the callback...
906 cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
911 // snap the piece to the target square
912 DRAGGED_PIECE.animate(
914 { top: DRAGGED_PIECE.style.top, left: DRAGGED_PIECE.style.left },
915 { top: targetSquarePosition.top, left: targetSquarePosition.left }
917 { duration: cfg.snapSpeed }
918 ).addEventListener('finish', complete);
919 DRAGGED_PIECE.style.top = targetSquarePosition.top;
920 DRAGGED_PIECE.style.left = targetSquarePosition.left;
923 function beginDraggingPiece(source, piece, x, y) {
924 // run their custom onDragStart function
925 // their custom onDragStart function can cancel drag start
926 if (typeof cfg.onDragStart === 'function' &&
927 cfg.onDragStart(source, piece,
928 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
933 DRAGGING_A_PIECE = true;
934 DRAGGED_PIECE = PIECE_ON_SQUARE[source];
935 DRAGGED_PIECE_SOURCE = source;
936 DRAGGED_PIECE_LOCATION = source;
938 // Move it to the end of the stack, which changes the implicit z-index
939 // so that it will go on top of any pieces it's replacing.
940 DRAGGED_PIECE.remove();
941 boardEl.appendChild(DRAGGED_PIECE);
943 // highlight the source square
944 let square = document.querySelector('.' + CSS.square + '[data-square="' + source + '"]');
945 square.classList.add(CSS.highlight1);
948 function findSquareFromEvent(pageX, pageY) {
949 let o = offset(boardEl);
950 let x = pageX - o.left;
951 let y = pageY - o.top;
956 left: Math.floor(x * 8 / boardEl.getBoundingClientRect().width),
957 top: Math.floor(y * 8 / boardEl.getBoundingClientRect().width)
959 if (CURRENT_ORIENTATION === 'white') {
960 position.top = 7 - position.top;
962 if (position.left >= 0 && position.left < 8 && position.top >= 0 && position.top < 8) {
963 position.square = COLUMNS[position.left] + (position.top + 1);
965 position.square = 'offboard';
970 function updateDraggedPiece(position) {
971 // put the dragged piece over the mouse cursor
972 DRAGGED_PIECE.style.left = 'calc(' + position.x + 'px - 6.25%)';
973 DRAGGED_PIECE.style.top = 'calc(' + position.y + 'px - 6.25%)';
975 // do nothing if the location has not changed
976 if (position === DRAGGED_PIECE_LOCATION) return;
978 // remove highlight from previous square
979 if (validSquare(DRAGGED_PIECE_LOCATION)) {
980 document.querySelector('.' + CSS.square + '[data-square="' + DRAGGED_PIECE_LOCATION + '"]')
981 .classList.remove(CSS.highlight2);
984 // add highlight to new square
985 if (validSquare(position.square)) {
986 document.querySelector('.' + CSS.square + '[data-square="' + position.square + '"]')
987 .classList.add(CSS.highlight2);
991 if (typeof cfg.onDragMove === 'function') {
992 cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
993 DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
994 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
998 DRAGGED_PIECE_LOCATION = position.square;
1001 function stopDraggedPiece(location) {
1002 // determine what the action should be
1003 var action = 'drop';
1004 if (location.square === 'offboard' && cfg.dropOffBoard === 'snapback') {
1005 action = 'snapback';
1008 // run their onDrop function, which can potentially change the drop action
1009 if (cfg.hasOwnProperty('onDrop') &&
1010 typeof cfg.onDrop === 'function') {
1011 var newPosition = deepCopy(CURRENT_POSITION);
1013 // source piece was on the board and position is on the board
1014 if (validSquare(DRAGGED_PIECE_SOURCE) &&
1015 validSquare(location.square)) {
1017 delete newPosition[DRAGGED_PIECE_SOURCE];
1018 newPosition[location.square] = DRAGGED_PIECE;
1019 if (location.square !== DRAGGED_PIECE_SOURCE) {
1020 PIECE_ON_SQUARE[location.square] = PIECE_ON_SQUARE[DRAGGED_PIECE_SOURCE];
1021 DRAGGED_PIECE.setAttribute('data-square', location.square);
1022 delete PIECE_ON_SQUARE[DRAGGED_PIECE_SOURCE];
1026 var oldPosition = deepCopy(CURRENT_POSITION);
1028 var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location.square, DRAGGED_PIECE,
1029 newPosition, oldPosition, CURRENT_ORIENTATION);
1030 if (result === 'snapback') {
1036 if (action === 'snapback') {
1037 snapbackDraggedPiece();
1039 else if (action === 'drop') {
1040 dropDraggedPieceOnSquare(location.square);
1044 //------------------------------------------------------------------------------
1046 //------------------------------------------------------------------------------
1049 widget.clear = function(useAnimation) {
1050 widget.position({}, useAnimation);
1054 // get or set config properties
1055 // TODO: write this, GitHub Issue #1
1056 widget.config = function(arg1, arg2) {
1057 // get the current config
1058 if (arguments.length === 0) {
1059 return deepCopy(cfg);
1064 // remove the widget from the page
1065 widget.destroy = function() {
1067 containerEl.innerHTML = '';
1068 draggedPieceEl.remove();
1071 // shorthand method to get the current FEN
1072 widget.fen = function() {
1073 return widget.position('fen');
1077 widget.flip = function() {
1078 widget.orientation('flip');
1082 // TODO: write this, GitHub Issue #5
1083 widget.highlight = function() {
1089 widget.move = function() {
1090 // no need to throw an error here; just do nothing
1091 if (arguments.length === 0) return;
1093 var useAnimation = true;
1095 // collect the moves into an object
1097 for (var i = 0; i < arguments.length; i++) {
1098 // any "false" to this function means no animations
1099 if (arguments[i] === false) {
1100 useAnimation = false;
1104 // skip invalid arguments
1105 if (!validMove(arguments[i])) {
1106 error(2826, 'Invalid move passed to the move method.', arguments[i]);
1110 var tmp = arguments[i].split('-');
1111 moves[tmp[0]] = tmp[1];
1114 // calculate position from moves
1115 var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1118 widget.position(newPos, useAnimation);
1120 // return the new position object
1124 widget.orientation = function(arg) {
1125 // no arguments, return the current orientation
1126 if (arguments.length === 0) {
1127 return CURRENT_ORIENTATION;
1130 // set to white or black
1131 if (arg === 'white' || arg === 'black') {
1132 CURRENT_ORIENTATION = arg;
1138 if (arg === 'flip') {
1139 CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1144 error(5482, 'Invalid value passed to the orientation method.', arg);
1148 * @param {!string|!Object} position
1149 * @param {boolean=} useAnimation
1151 widget.position = function(position, useAnimation) {
1152 // no arguments, return the current position
1153 if (arguments.length === 0) {
1154 return deepCopy(CURRENT_POSITION);
1157 // get position as FEN
1158 if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1159 return objToFen(CURRENT_POSITION);
1162 // default for useAnimations is true
1163 if (useAnimation !== false) {
1164 useAnimation = true;
1168 if (typeof position === 'string' && position.toLowerCase() === 'start') {
1169 position = deepCopy(START_POSITION);
1172 // convert FEN to position object
1173 if (validFen(position)) {
1174 position = fenToObj(position);
1177 // validate position object
1178 if (!validPositionObject(position)) {
1179 error(6482, 'Invalid value passed to the position method.', position);
1184 // start the animations
1185 doAnimations(calculateAnimations(CURRENT_POSITION, position),
1186 CURRENT_POSITION, position);
1188 // set the new position
1189 setCurrentPosition(position);
1193 setCurrentPosition(position);
1194 drawPositionInstant();
1198 widget.resize = function() {
1203 // set the starting position
1204 widget.start = function(useAnimation) {
1205 widget.position('start', useAnimation);
1208 //------------------------------------------------------------------------------
1210 //------------------------------------------------------------------------------
1212 function isTouchDevice() {
1213 return ('ontouchstart' in document.documentElement);
1216 function mousedownSquare(e) {
1217 let square = e.target.getAttribute('data-square');
1219 // no piece on this square
1220 if (!validSquare(square) ||
1221 !CURRENT_POSITION.hasOwnProperty(square)) {
1225 // do nothing if we're not draggable
1226 if (!cfg.draggable) return;
1228 beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1231 function touchstartSquare(e) {
1232 let target = e.target.closest('.' + CSS.square);
1237 // do nothing if we're not draggable
1238 if (!cfg.draggable) return;
1240 var square = target.getAttribute('data-square');
1242 // no piece on this square
1243 if (!validSquare(square) ||
1244 !CURRENT_POSITION.hasOwnProperty(square)) {
1248 beginDraggingPiece(square, CURRENT_POSITION[square],
1249 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1252 function mousemoveWindow(e) {
1253 // do nothing if we are not dragging a piece
1254 if (!DRAGGING_A_PIECE) return;
1256 updateDraggedPiece(findSquareFromEvent(e.pageX, e.pageY));
1259 function touchmoveWindow(e) {
1260 // do nothing if we are not dragging a piece
1261 if (!DRAGGING_A_PIECE) return;
1263 // prevent screen from scrolling
1266 updateDraggedPiece(findSquareFromEvent(e.changedTouches[0].pageX,
1267 e.changedTouches[0].pageY));
1270 function mouseupWindow(e) {
1271 // do nothing if we are not dragging a piece
1272 if (!DRAGGING_A_PIECE) return;
1274 stopDraggedPiece(findSquareFromEvent(e.pageX, e.pageY));
1277 function touchendWindow(e) {
1278 // do nothing if we are not dragging a piece
1279 if (!DRAGGING_A_PIECE) return;
1281 stopDraggedPiece(findSquareFromEvent(e.changedTouches[0].pageX,
1282 e.changedTouches[0].pageY));
1285 function mouseenterSquare(e) {
1286 let target = e.target.closest('.' + CSS.square);
1291 // do not fire this event if we are dragging a piece
1292 // NOTE: this should never happen, but it's a safeguard
1293 if (DRAGGING_A_PIECE !== false) return;
1295 if (!cfg.hasOwnProperty('onMouseoverSquare') ||
1296 typeof cfg.onMouseoverSquare !== 'function') return;
1299 var square = target.getAttribute('data-square');
1301 // NOTE: this should never happen; defensive
1302 if (!validSquare(square)) return;
1304 // get the piece on this square
1306 if (CURRENT_POSITION.hasOwnProperty(square)) {
1307 piece = CURRENT_POSITION[square];
1310 // execute their function
1311 cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1312 CURRENT_ORIENTATION);
1315 function mouseleaveSquare(e) {
1316 let target = e.target.closest('.' + CSS.square);
1321 // do not fire this event if we are dragging a piece
1322 // NOTE: this should never happen, but it's a safeguard
1323 if (DRAGGING_A_PIECE !== false) return;
1325 if (!cfg.hasOwnProperty('onMouseoutSquare') ||
1326 typeof cfg.onMouseoutSquare !== 'function') return;
1329 var square = target.getAttribute('data-square');
1331 // NOTE: this should never happen; defensive
1332 if (!validSquare(square)) return;
1334 // get the piece on this square
1336 if (CURRENT_POSITION.hasOwnProperty(square)) {
1337 piece = CURRENT_POSITION[square];
1340 // execute their function
1341 cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1342 CURRENT_ORIENTATION);
1345 //------------------------------------------------------------------------------
1347 //------------------------------------------------------------------------------
1349 function addEvents() {
1350 // prevent browser "image drag"
1351 let stopDefault = (e) => {
1352 if (e.target.matches('.' + CSS.piece)) {
1356 document.body.addEventListener('mousedown', stopDefault);
1357 document.body.addEventListener('mousemove', stopDefault);
1359 // mouse drag pieces
1360 boardEl.addEventListener('mousedown', mousedownSquare);
1362 // mouse enter / leave square
1363 boardEl.addEventListener('mouseenter', mouseenterSquare);
1364 boardEl.addEventListener('mouseleave', mouseleaveSquare);
1366 window.addEventListener('mousemove', mousemoveWindow);
1367 window.addEventListener('mouseup', mouseupWindow);
1369 // touch drag pieces
1370 if (isTouchDevice()) {
1371 boardEl.addEventListener('touchstart', touchstartSquare);
1372 window.addEventListener('touchmove', touchmoveWindow);
1373 window.addEventListener('touchend', touchendWindow);
1377 function initDom() {
1378 // build board and save it in memory
1379 containerEl.innerHTML = buildBoardContainer();
1380 boardEl = containerEl.querySelector('.' + CSS.board);
1382 // set the size and draw the board
1387 if (!checkDeps() || !expandConfig()) return;
1396 // return the widget object
1399 }; // end window.ChessBoard
1401 // expose util functions
1402 window.ChessBoard.fenToObj = fenToObj;
1403 window.ChessBoard.objToFen = objToFen;
1405 })(); // end anonymous wrapper