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) {
612 e.target.transitionProperty = null;
613 e.target.transitionDuration = null;
617 // For whatever reason, the transition didn't seem to actually run
618 // (and thus, we didn't get an end event). Finish off now.
619 // (In particular, this seems to happen in Chrome if the tab is
620 // hidden and left alone for a while.)
621 if (numFinished == a.length) return;
622 numFinished = a.length; // Make sure a very delayed later event will be ignored.
625 if (numFinished !== a.length) return;
628 for (let piece of removed_pieces) {
632 // run their onMoveEnd function
633 if (cfg.hasOwnProperty('onMoveEnd') &&
634 typeof cfg.onMoveEnd === 'function') {
635 cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
639 if (fadeout_pieces.length == 0 || fadein_pieces.length > 0 || move_pieces.length > 0) {
640 requestAnimationFrame(() => { // Firefox workaround.
641 // Backup in case the transition never runs.
642 setTimeout(() => onFinish(null, true),
643 cfg.appearSpeed + cfg.trashSpeed + cfg.moveSpeed + 100);
645 fadein_pieces.forEach((piece) => {
646 piece.style.opacity = 0;
647 piece.style.display = null;
648 piece.addEventListener('transitionend', onFinish, {once: true});
650 fadeout_pieces.forEach((piece) => {
651 piece.style.opacity = 1;
652 piece.style.display = null;
653 piece.addEventListener('transitionend', onFinish, {once: true});
655 for (const [piece, destination] of move_pieces) {
656 // Move it to the end of the stack, which changes the implicit z-index
657 // so that it will go on top of any pieces it's replacing.
659 boardEl.appendChild(piece);
660 piece.addEventListener('transitionend', onFinish, {once: true});
662 requestAnimationFrame(() => {
663 fadein_pieces.forEach((piece) => {
664 piece.style.transitionProperty = 'opacity';
665 piece.style.transitionDuration = cfg.appearSpeed + 'ms';
666 piece.style.opacity = 1;
668 fadeout_pieces.forEach((piece) => {
669 piece.style.transitionProperty = 'opacity';
670 piece.style.transitionDuration = cfg.trashSpeed + 'ms';
671 piece.style.opacity = 0;
673 for (const [piece, destination] of move_pieces) {
674 let destSquarePosition = findSquarePosition(destination);
675 piece.style.transitionProperty = 'top, left';
676 piece.style.transitionDuration = cfg.moveSpeed + 'ms';
677 piece.style.top = destSquarePosition.top;
678 piece.style.left = destSquarePosition.left;
685 // returns the distance between two squares
686 function squareDistance(s1, s2) {
688 var s1x = COLUMNS.indexOf(s1[0]) + 1;
689 var s1y = parseInt(s1[1], 10);
692 var s2x = COLUMNS.indexOf(s2[0]) + 1;
693 var s2y = parseInt(s2[1], 10);
695 var xDelta = Math.abs(s1x - s2x);
696 var yDelta = Math.abs(s1y - s2y);
698 if (xDelta >= yDelta) return xDelta;
702 // returns the square of the closest instance of piece
703 // returns false if no instance of piece is found in position
704 function findClosestPiece(position, piece, square) {
705 let best_square = false;
707 for (var i = 0; i < COLUMNS.length; i++) {
708 for (var j = 1; j <= 8; j++) {
709 let other_square = COLUMNS[i] + j;
711 if (position[other_square] === piece && square != other_square) {
712 let dist = squareDistance(square, other_square);
713 if (dist < best_dist) {
714 best_square = other_square;
724 // calculate an array of animations that need to happen in order to get
726 function calculateAnimations(pos1, pos2) {
727 // make copies of both
728 pos1 = deepCopy(pos1);
729 pos2 = deepCopy(pos2);
732 var squaresMovedTo = {};
734 // remove pieces that are the same in both positions
735 for (var i in pos2) {
736 if (!pos2.hasOwnProperty(i)) continue;
738 if (pos1.hasOwnProperty(i) && pos1[i] === pos2[i]) {
744 // find all the "move" animations
745 for (var i in pos2) {
746 if (!pos2.hasOwnProperty(i)) continue;
748 var closestPiece = findClosestPiece(pos1, pos2[i], i);
749 if (closestPiece !== false) {
752 source: closestPiece,
757 delete pos1[closestPiece];
759 squaresMovedTo[i] = true;
763 // add pieces to pos2
764 for (var i in pos2) {
765 if (!pos2.hasOwnProperty(i)) continue;
776 // clear pieces from pos1
777 for (var i in pos1) {
778 if (!pos1.hasOwnProperty(i)) continue;
780 // do not clear a piece if it is on a square that is the result
781 // of a "move", ie: a piece capture
782 if (squaresMovedTo.hasOwnProperty(i)) continue;
796 //------------------------------------------------------------------------------
798 //------------------------------------------------------------------------------
800 function drawPositionInstant() {
802 boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
805 for (const [square, piece] of Object.entries(CURRENT_POSITION)) {
806 let pos = findSquarePosition(square);
807 let pieceEl = buildPiece(piece);
808 pieceEl.style.left = pos.left;
809 pieceEl.style.top = pos.top;
810 pieceEl.setAttribute('data-square', square);
811 boardEl.append(pieceEl);
812 PIECE_ON_SQUARE[square] = pieceEl;
816 function drawBoard() {
817 boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
818 drawPositionInstant();
821 // given a position and a set of moves, return a new position
822 // with the moves executed
823 function calculatePositionFromMoves(position, moves) {
824 position = deepCopy(position);
826 for (var i in moves) {
827 if (!moves.hasOwnProperty(i)) continue;
829 // skip the move if the position doesn't have a piece on the source square
830 if (!position.hasOwnProperty(i)) continue;
832 var piece = position[i];
834 position[moves[i]] = piece;
840 function setCurrentPosition(position) {
841 var oldPos = deepCopy(CURRENT_POSITION);
842 var newPos = deepCopy(position);
843 var oldFen = objToFen(oldPos);
844 var newFen = objToFen(newPos);
846 // do nothing if no change in position
847 if (oldFen === newFen) return;
849 // run their onChange function
850 if (cfg.hasOwnProperty('onChange') &&
851 typeof cfg.onChange === 'function') {
852 cfg.onChange(oldPos, newPos);
856 CURRENT_POSITION = position;
859 function removeSquareHighlights() {
860 boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
861 piece.classList.remove(CSS.highlight1);
862 piece.classList.remove(CSS.highlight2);
866 function snapbackDraggedPiece() {
867 removeSquareHighlights();
869 // animation complete
870 function complete() {
871 drawPositionInstant();
873 // run their onSnapbackEnd function
874 if (cfg.hasOwnProperty('onSnapbackEnd') &&
875 typeof cfg.onSnapbackEnd === 'function') {
876 cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
877 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
881 // get source square position
882 var sourceSquarePosition = findSquarePosition(DRAGGED_PIECE_SOURCE);
884 // animate the piece to the target square
885 DRAGGED_PIECE.addEventListener('transitionend', complete, {once: true});
886 requestAnimationFrame(() => {
887 DRAGGED_PIECE.style.transitionProperty = 'top, left';
888 DRAGGED_PIECE.style.transitionDuration = cfg.snapbackSpeed + 'ms';
889 DRAGGED_PIECE.style.top = sourceSquarePosition.top;
890 DRAGGED_PIECE.style.left = sourceSquarePosition.left;
894 DRAGGING_A_PIECE = false;
897 function dropDraggedPieceOnSquare(square) {
898 removeSquareHighlights();
899 DRAGGING_A_PIECE = false;
901 if (DRAGGED_PIECE_SOURCE === square) {
902 // Nothing to do, but call onSnapEnd anyway
903 if (cfg.hasOwnProperty('onSnapEnd') && typeof cfg.onSnapEnd === 'function') {
904 cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
910 var newPosition = deepCopy(CURRENT_POSITION);
911 newPosition[square] = newPosition[DRAGGED_PIECE_SOURCE];
912 delete newPosition[DRAGGED_PIECE_SOURCE];
913 setCurrentPosition(newPosition);
915 delete PIECE_ON_SQUARE[DRAGGED_PIECE_SOURCE];
916 PIECE_ON_SQUARE[square] = DRAGGED_PIECE;
917 DRAGGED_PIECE.setAttribute('data-square', square);
919 // get target square information
920 var targetSquarePosition = findSquarePosition(square);
922 // animation complete
923 var complete = function() {
924 drawPositionInstant();
926 // execute their onSnapEnd function
927 if (cfg.hasOwnProperty('onSnapEnd') &&
928 typeof cfg.onSnapEnd === 'function') {
929 requestAnimationFrame(() => { // HACK: so that we don't add event handlers from the callback...
930 cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
935 // snap the piece to the target square
936 DRAGGED_PIECE.addEventListener('transitionend', complete, {once: true});
937 requestAnimationFrame(() => {
938 DRAGGED_PIECE.style.transitionProperty = 'top, left';
939 DRAGGED_PIECE.style.transitionDuration = cfg.snapSpeed + 'ms';
940 DRAGGED_PIECE.style.top = targetSquarePosition.top;
941 DRAGGED_PIECE.style.left = targetSquarePosition.left;
945 function beginDraggingPiece(source, piece, x, y) {
946 // run their custom onDragStart function
947 // their custom onDragStart function can cancel drag start
948 if (typeof cfg.onDragStart === 'function' &&
949 cfg.onDragStart(source, piece,
950 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
955 DRAGGING_A_PIECE = true;
956 DRAGGED_PIECE = PIECE_ON_SQUARE[source];
957 DRAGGED_PIECE_SOURCE = source;
958 DRAGGED_PIECE_LOCATION = source;
959 DRAGGED_PIECE.style.transitionProperty = null;
960 DRAGGED_PIECE.style.transitionDuration = null;
962 // Move it to the end of the stack, which changes the implicit z-index
963 // so that it will go on top of any pieces it's replacing.
964 DRAGGED_PIECE.remove();
965 boardEl.appendChild(DRAGGED_PIECE);
967 // highlight the source square
968 let square = document.querySelector('.' + CSS.square + '[data-square="' + source + '"]');
969 square.classList.add(CSS.highlight1);
972 function findSquareFromEvent(pageX, pageY) {
973 let o = offset(boardEl);
974 let x = pageX - o.left;
975 let y = pageY - o.top;
980 left: Math.floor(x * 8 / boardEl.getBoundingClientRect().width),
981 top: Math.floor(y * 8 / boardEl.getBoundingClientRect().width)
983 if (CURRENT_ORIENTATION === 'white') {
984 position.top = 7 - position.top;
986 if (position.left >= 0 && position.left < 8 && position.top >= 0 && position.top < 8) {
987 position.square = COLUMNS[position.left] + (position.top + 1);
989 position.square = 'offboard';
994 function updateDraggedPiece(position) {
995 // put the dragged piece over the mouse cursor
996 DRAGGED_PIECE.style.left = 'calc(' + position.x + 'px - 6.25%)';
997 DRAGGED_PIECE.style.top = 'calc(' + position.y + 'px - 6.25%)';
999 // do nothing if the location has not changed
1000 if (position === DRAGGED_PIECE_LOCATION) return;
1002 // remove highlight from previous square
1003 if (validSquare(DRAGGED_PIECE_LOCATION)) {
1004 document.querySelector('.' + CSS.square + '[data-square="' + DRAGGED_PIECE_LOCATION + '"]')
1005 .classList.remove(CSS.highlight2);
1008 // add highlight to new square
1009 if (validSquare(position.square)) {
1010 document.querySelector('.' + CSS.square + '[data-square="' + position.square + '"]')
1011 .classList.add(CSS.highlight2);
1015 if (typeof cfg.onDragMove === 'function') {
1016 cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1017 DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1018 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1022 DRAGGED_PIECE_LOCATION = position.square;
1025 function stopDraggedPiece(location) {
1026 // determine what the action should be
1027 var action = 'drop';
1028 if (location.square === 'offboard' && cfg.dropOffBoard === 'snapback') {
1029 action = 'snapback';
1032 // run their onDrop function, which can potentially change the drop action
1033 if (cfg.hasOwnProperty('onDrop') &&
1034 typeof cfg.onDrop === 'function') {
1035 var newPosition = deepCopy(CURRENT_POSITION);
1037 // source piece was on the board and position is on the board
1038 if (validSquare(DRAGGED_PIECE_SOURCE) &&
1039 validSquare(location.square)) {
1041 delete newPosition[DRAGGED_PIECE_SOURCE];
1042 newPosition[location.square] = DRAGGED_PIECE;
1043 if (location.square !== DRAGGED_PIECE_SOURCE) {
1044 PIECE_ON_SQUARE[location.square] = PIECE_ON_SQUARE[DRAGGED_PIECE_SOURCE];
1045 DRAGGED_PIECE.setAttribute('data-square', location.square);
1046 delete PIECE_ON_SQUARE[DRAGGED_PIECE_SOURCE];
1050 var oldPosition = deepCopy(CURRENT_POSITION);
1052 var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location.square, DRAGGED_PIECE,
1053 newPosition, oldPosition, CURRENT_ORIENTATION);
1054 if (result === 'snapback') {
1060 if (action === 'snapback') {
1061 snapbackDraggedPiece();
1063 else if (action === 'drop') {
1064 dropDraggedPieceOnSquare(location.square);
1068 //------------------------------------------------------------------------------
1070 //------------------------------------------------------------------------------
1073 widget.clear = function(useAnimation) {
1074 widget.position({}, useAnimation);
1078 // get or set config properties
1079 // TODO: write this, GitHub Issue #1
1080 widget.config = function(arg1, arg2) {
1081 // get the current config
1082 if (arguments.length === 0) {
1083 return deepCopy(cfg);
1088 // remove the widget from the page
1089 widget.destroy = function() {
1091 containerEl.innerHTML = '';
1092 draggedPieceEl.remove();
1095 // shorthand method to get the current FEN
1096 widget.fen = function() {
1097 return widget.position('fen');
1101 widget.flip = function() {
1102 widget.orientation('flip');
1106 // TODO: write this, GitHub Issue #5
1107 widget.highlight = function() {
1113 widget.move = function() {
1114 // no need to throw an error here; just do nothing
1115 if (arguments.length === 0) return;
1117 var useAnimation = true;
1119 // collect the moves into an object
1121 for (var i = 0; i < arguments.length; i++) {
1122 // any "false" to this function means no animations
1123 if (arguments[i] === false) {
1124 useAnimation = false;
1128 // skip invalid arguments
1129 if (!validMove(arguments[i])) {
1130 error(2826, 'Invalid move passed to the move method.', arguments[i]);
1134 var tmp = arguments[i].split('-');
1135 moves[tmp[0]] = tmp[1];
1138 // calculate position from moves
1139 var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1142 widget.position(newPos, useAnimation);
1144 // return the new position object
1148 widget.orientation = function(arg) {
1149 // no arguments, return the current orientation
1150 if (arguments.length === 0) {
1151 return CURRENT_ORIENTATION;
1154 // set to white or black
1155 if (arg === 'white' || arg === 'black') {
1156 CURRENT_ORIENTATION = arg;
1162 if (arg === 'flip') {
1163 CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1168 error(5482, 'Invalid value passed to the orientation method.', arg);
1172 * @param {!string|!Object} position
1173 * @param {boolean=} useAnimation
1175 widget.position = function(position, useAnimation) {
1176 // no arguments, return the current position
1177 if (arguments.length === 0) {
1178 return deepCopy(CURRENT_POSITION);
1181 // get position as FEN
1182 if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1183 return objToFen(CURRENT_POSITION);
1186 // default for useAnimations is true
1187 if (useAnimation !== false) {
1188 useAnimation = true;
1192 if (typeof position === 'string' && position.toLowerCase() === 'start') {
1193 position = deepCopy(START_POSITION);
1196 // convert FEN to position object
1197 if (validFen(position)) {
1198 position = fenToObj(position);
1201 // validate position object
1202 if (!validPositionObject(position)) {
1203 error(6482, 'Invalid value passed to the position method.', position);
1208 // start the animations
1209 doAnimations(calculateAnimations(CURRENT_POSITION, position),
1210 CURRENT_POSITION, position);
1212 // set the new position
1213 setCurrentPosition(position);
1217 setCurrentPosition(position);
1218 drawPositionInstant();
1222 widget.resize = function() {
1227 // set the starting position
1228 widget.start = function(useAnimation) {
1229 widget.position('start', useAnimation);
1232 //------------------------------------------------------------------------------
1234 //------------------------------------------------------------------------------
1236 function isTouchDevice() {
1237 return ('ontouchstart' in document.documentElement);
1240 function mousedownSquare(e) {
1241 let square = e.target.getAttribute('data-square');
1243 // no piece on this square
1244 if (!validSquare(square) ||
1245 !CURRENT_POSITION.hasOwnProperty(square)) {
1249 // do nothing if we're not draggable
1250 if (cfg.draggable) return;
1252 beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1255 function touchstartSquare(e) {
1256 let target = e.target.closest('.' + CSS.square);
1261 // do nothing if we're not draggable
1262 if (cfg.draggable) return;
1264 var square = target.getAttribute('data-square');
1266 // no piece on this square
1267 if (!validSquare(square) ||
1268 !CURRENT_POSITION.hasOwnProperty(square)) {
1272 beginDraggingPiece(square, CURRENT_POSITION[square],
1273 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1276 function mousemoveWindow(e) {
1277 // do nothing if we are not dragging a piece
1278 if (!DRAGGING_A_PIECE) return;
1280 updateDraggedPiece(findSquareFromEvent(e.pageX, e.pageY));
1283 function touchmoveWindow(e) {
1284 // do nothing if we are not dragging a piece
1285 if (!DRAGGING_A_PIECE) return;
1287 // prevent screen from scrolling
1290 updateDraggedPiece(findSquareFromEvent(e.changedTouches[0].pageX,
1291 e.changedTouches[0].pageY));
1294 function mouseupWindow(e) {
1295 // do nothing if we are not dragging a piece
1296 if (!DRAGGING_A_PIECE) return;
1298 stopDraggedPiece(findSquareFromEvent(e.pageX, e.pageY));
1301 function touchendWindow(e) {
1302 // do nothing if we are not dragging a piece
1303 if (!DRAGGING_A_PIECE) return;
1306 var location = isXYOnSquare(e.changedTouches[0].pageX,
1307 e.changedTouches[0].pageY);
1309 stopDraggedPiece(findSquareFromEvent(e.changedTouches[0].pageX,
1310 e.changedTouches[0].pageY));
1313 function mouseenterSquare(e) {
1314 let target = e.target.closest('.' + CSS.square);
1319 // do not fire this event if we are dragging a piece
1320 // NOTE: this should never happen, but it's a safeguard
1321 if (DRAGGING_A_PIECE !== false) return;
1323 if (!cfg.hasOwnProperty('onMouseoverSquare') ||
1324 typeof cfg.onMouseoverSquare !== 'function') return;
1327 var square = target.getAttribute('data-square');
1329 // NOTE: this should never happen; defensive
1330 if (!validSquare(square)) return;
1332 // get the piece on this square
1334 if (CURRENT_POSITION.hasOwnProperty(square)) {
1335 piece = CURRENT_POSITION[square];
1338 // execute their function
1339 cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1340 CURRENT_ORIENTATION);
1343 function mouseleaveSquare(e) {
1344 let target = e.target.closest('.' + CSS.square);
1349 // do not fire this event if we are dragging a piece
1350 // NOTE: this should never happen, but it's a safeguard
1351 if (DRAGGING_A_PIECE !== false) return;
1353 if (!cfg.hasOwnProperty('onMouseoutSquare') ||
1354 typeof cfg.onMouseoutSquare !== 'function') return;
1357 var square = target.getAttribute('data-square');
1359 // NOTE: this should never happen; defensive
1360 if (!validSquare(square)) return;
1362 // get the piece on this square
1364 if (CURRENT_POSITION.hasOwnProperty(square)) {
1365 piece = CURRENT_POSITION[square];
1368 // execute their function
1369 cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1370 CURRENT_ORIENTATION);
1373 //------------------------------------------------------------------------------
1375 //------------------------------------------------------------------------------
1377 function addEvents() {
1378 // prevent browser "image drag"
1379 let stopDefault = (e) => {
1380 if (e.target.matches('.' + CSS.piece)) {
1384 document.body.addEventListener('mousedown', stopDefault);
1385 document.body.addEventListener('mousemove', stopDefault);
1387 // mouse drag pieces
1388 boardEl.addEventListener('mousedown', mousedownSquare);
1390 // mouse enter / leave square
1391 boardEl.addEventListener('mouseenter', mouseenterSquare);
1392 boardEl.addEventListener('mouseleave', mouseleaveSquare);
1394 window.addEventListener('mousemove', mousemoveWindow);
1395 window.addEventListener('mouseup', mouseupWindow);
1397 // touch drag pieces
1398 if (isTouchDevice()) {
1399 boardEl.addEventListener('touchstart', touchstartSquare);
1400 window.addEventListener('touchmove', touchmoveWindow);
1401 window.addEventListener('touchend', touchendWindow);
1405 function initDom() {
1406 // build board and save it in memory
1407 containerEl.innerHTML = buildBoardContainer();
1408 boardEl = containerEl.querySelector('.' + CSS.board);
1410 // set the size and draw the board
1415 if (!checkDeps() || !expandConfig()) return;
1424 // return the widget object
1427 }; // end window.ChessBoard
1429 // expose util functions
1430 window.ChessBoard.fenToObj = fenToObj;
1431 window.ChessBoard.objToFen = objToFen;
1433 })(); // end anonymous wrapper