]> git.sesse.net Git - remoteglot/blob - www/js/chessboard-0.3.0.js
dc0e427b7fae69679c032147280fcdff7876fa17
[remoteglot] / www / js / chessboard-0.3.0.js
1 /*!
2  * chessboard.js v0.3.0+asn
3  *
4  * Copyright 2013 Chris Oakman
5  * Portions copyright 2022 Steinar H. Gunderson
6  * Released under the MIT license
7  * http://chessboardjs.com/license
8  *
9  * Date: 10 Aug 2013
10  */
11
12 // start anonymous scope
13 ;(function() {
14 'use strict';
15
16 //------------------------------------------------------------------------------
17 // Chess Util Functions
18 //------------------------------------------------------------------------------
19 var COLUMNS = 'abcdefgh'.split('');
20
21 function validMove(move) {
22   // move should be a string
23   if (typeof move !== 'string') return false;
24
25   // move should be in the form of "e2-e4", "f6-d5"
26   var tmp = move.split('-');
27   if (tmp.length !== 2) return false;
28
29   return (validSquare(tmp[0]) === true && validSquare(tmp[1]) === true);
30 }
31
32 function validSquare(square) {
33   if (typeof square !== 'string') return false;
34   return (square.search(/^[a-h][1-8]$/) !== -1);
35 }
36
37 function validPieceCode(code) {
38   if (typeof code !== 'string') return false;
39   return (code.search(/^[bw][KQRNBP]$/) !== -1);
40 }
41
42 // TODO: this whole function could probably be replaced with a single regex
43 function validFen(fen) {
44   if (typeof fen !== 'string') return false;
45
46   // cut off any move, castling, etc info from the end
47   // we're only interested in position information
48   fen = fen.replace(/ .+$/, '');
49
50   // FEN should be 8 sections separated by slashes
51   var chunks = fen.split('/');
52   if (chunks.length !== 8) return false;
53
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) {
59       return false;
60     }
61   }
62
63   return true;
64 }
65
66 function validPositionObject(pos) {
67   if (typeof pos !== 'object') return false;
68
69   for (var i in pos) {
70     if (pos.hasOwnProperty(i) !== true) continue;
71
72     if (validSquare(i) !== true || validPieceCode(pos[i]) !== true) {
73       return false;
74     }
75   }
76
77   return true;
78 }
79
80 // convert FEN piece code to bP, wK, etc
81 function fenToPieceCode(piece) {
82   // black piece
83   if (piece.toLowerCase() === piece) {
84     return 'b' + piece.toUpperCase();
85   }
86
87   // white piece
88   return 'w' + piece.toUpperCase();
89 }
90
91 // convert bP, wK, etc code to FEN structure
92 function pieceCodeToFen(piece) {
93   var tmp = piece.split('');
94
95   // white piece
96   if (tmp[0] === 'w') {
97     return tmp[1].toUpperCase();
98   }
99
100   // black piece
101   return tmp[1].toLowerCase();
102 }
103
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) {
108     return false;
109   }
110
111   // cut off any move, castling, etc info from the end
112   // we're only interested in position information
113   fen = fen.replace(/ .+$/, '');
114
115   var rows = fen.split('/');
116   var position = {};
117
118   var currentRow = 8;
119   for (var i = 0; i < 8; i++) {
120     var row = rows[i].split('');
121     var colIndex = 0;
122
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;
129       }
130       // piece
131       else {
132         var square = COLUMNS[colIndex] + currentRow;
133         position[square] = fenToPieceCode(row[j]);
134         colIndex++;
135       }
136     }
137
138     currentRow--;
139   }
140
141   return position;
142 }
143
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) {
148     return false;
149   }
150
151   var fen = '';
152
153   var currentRow = 8;
154   for (var i = 0; i < 8; i++) {
155     for (var j = 0; j < 8; j++) {
156       var square = COLUMNS[j] + currentRow;
157
158       // piece exists
159       if (obj.hasOwnProperty(square) === true) {
160         fen += pieceCodeToFen(obj[square]);
161       }
162
163       // empty space
164       else {
165         fen += '1';
166       }
167     }
168
169     if (i !== 7) {
170       fen += '/';
171     }
172
173     currentRow--;
174   }
175
176   // squeeze the numbers together
177   // haha, I love this solution...
178   fen = fen.replace(/11111111/g, '8');
179   fen = fen.replace(/1111111/g, '7');
180   fen = fen.replace(/111111/g, '6');
181   fen = fen.replace(/11111/g, '5');
182   fen = fen.replace(/1111/g, '4');
183   fen = fen.replace(/111/g, '3');
184   fen = fen.replace(/11/g, '2');
185
186   return fen;
187 }
188
189 /** @struct */
190 var cfg;
191
192 /** @constructor */
193 window.ChessBoard = function(containerElOrId, cfg) {
194 'use strict';
195
196 cfg = cfg || {};
197
198 //------------------------------------------------------------------------------
199 // Constants
200 //------------------------------------------------------------------------------
201
202 var START_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR',
203   START_POSITION = fenToObj(START_FEN);
204
205 // use unique class names to prevent clashing with anything else on the page
206 // and simplify selectors
207 var CSS = {
208   alpha: 'alpha-d2270',
209   board: 'board-b72b1',
210   chessboard: 'chessboard-63f37',
211   clearfix: 'clearfix-7da63',
212   highlight1: 'highlight1-32417',
213   highlight2: 'highlight2-9c5d2',
214   notation: 'notation-322f9',
215   numeric: 'numeric-fc462',
216   piece: 'piece-417db',
217   row: 'row-5277c',
218   square: 'square-55d63'
219 };
220 var CSSColor = {};
221 CSSColor['white'] = 'white-1e1d7';
222 CSSColor['black'] = 'black-3c85d';
223
224 //------------------------------------------------------------------------------
225 // Module Scope Variables
226 //------------------------------------------------------------------------------
227
228 // DOM elements
229 var containerEl,
230   boardEl,
231   draggedPieceEl;
232
233 // constructor return object
234 var widget = {};
235
236 //------------------------------------------------------------------------------
237 // Stateful
238 //------------------------------------------------------------------------------
239
240 var BOARD_BORDER_SIZE = 2,
241   CURRENT_ORIENTATION = 'white',
242   CURRENT_POSITION = {},
243   SQUARE_SIZE,
244   DRAGGED_PIECE,
245   DRAGGED_PIECE_LOCATION,
246   DRAGGED_PIECE_SOURCE,
247   DRAGGING_A_PIECE = false,
248   SQUARE_ELS_IDS = {},
249   SQUARE_ELS_OFFSETS;
250
251 //------------------------------------------------------------------------------
252 // JS Util Functions
253 //------------------------------------------------------------------------------
254
255 let id_counter = 0;
256 function createId() {
257   return 'chesspiece-id-' + (id_counter++);
258 }
259
260 function deepCopy(thing) {
261   return JSON.parse(JSON.stringify(thing));
262 }
263
264 //------------------------------------------------------------------------------
265 // Validation / Errors
266 //------------------------------------------------------------------------------
267
268 /**
269  * @param {!number} code
270  * @param {!string} msg
271  * @param {Object=} obj
272  */
273 function error(code, msg, obj) {
274   // do nothing if showErrors is not set
275   if (cfg.hasOwnProperty('showErrors') !== true ||
276       cfg.showErrors === false) {
277     return;
278   }
279
280   var errorText = 'ChessBoard Error ' + code + ': ' + msg;
281
282   // print to console
283   if (cfg.showErrors === 'console' &&
284       typeof console === 'object' &&
285       typeof console.log === 'function') {
286     console.log(errorText);
287     if (arguments.length >= 2) {
288       console.log(obj);
289     }
290     return;
291   }
292
293   // alert errors
294   if (cfg.showErrors === 'alert') {
295     if (obj) {
296       errorText += '\n\n' + JSON.stringify(obj);
297     }
298     window.alert(errorText);
299     return;
300   }
301
302   // custom function
303   if (typeof cfg.showErrors === 'function') {
304     cfg.showErrors(code, msg, obj);
305   }
306 }
307
308 // check dependencies
309 function checkDeps() {
310   // if containerId is a string, it must be the ID of a DOM node
311   if (typeof containerElOrId === 'string') {
312     // cannot be empty
313     if (containerElOrId === '') {
314       window.alert('ChessBoard Error 1001: ' +
315         'The first argument to ChessBoard() cannot be an empty string.' +
316         '\n\nExiting...');
317       return false;
318     }
319
320     // make sure the container element exists in the DOM
321     var el = document.getElementById(containerElOrId);
322     if (! el) {
323       window.alert('ChessBoard Error 1002: Element with id "' +
324         containerElOrId + '" does not exist in the DOM.' +
325         '\n\nExiting...');
326       return false;
327     }
328
329     // set the containerEl
330     containerEl = el;
331   }
332
333   // else it must be a DOM node
334   else {
335     containerEl = containerElOrId;
336   }
337
338   return true;
339 }
340
341 function validAnimationSpeed(speed) {
342   if (speed === 'fast' || speed === 'slow') {
343     return true;
344   }
345
346   if ((parseInt(speed, 10) + '') !== (speed + '')) {
347     return false;
348   }
349
350   return (speed >= 0);
351 }
352
353 // validate config / set default options
354 function expandConfig() {
355   if (typeof cfg === 'string' || validPositionObject(cfg) === true) {
356     cfg = {
357       position: cfg
358     };
359   }
360
361   // default for orientation is white
362   if (cfg.orientation !== 'black') {
363     cfg.orientation = 'white';
364   }
365   CURRENT_ORIENTATION = cfg.orientation;
366
367   // default for showNotation is true
368   if (cfg.showNotation !== false) {
369     cfg.showNotation = true;
370   }
371
372   // default for draggable is false
373   if (cfg.draggable !== true) {
374     cfg.draggable = false;
375   }
376
377   // default piece theme is wikipedia
378   if (cfg.hasOwnProperty('pieceTheme') !== true ||
379       (typeof cfg.pieceTheme !== 'string' &&
380        typeof cfg.pieceTheme !== 'function')) {
381     cfg.pieceTheme = 'img/chesspieces/wikipedia/{piece}.png';
382   }
383
384   // animation speeds
385   if (cfg.hasOwnProperty('appearSpeed') !== true ||
386       validAnimationSpeed(cfg.appearSpeed) !== true) {
387     cfg.appearSpeed = 200;
388   }
389   if (cfg.hasOwnProperty('moveSpeed') !== true ||
390       validAnimationSpeed(cfg.moveSpeed) !== true) {
391     cfg.moveSpeed = 200;
392   }
393   if (cfg.hasOwnProperty('snapbackSpeed') !== true ||
394       validAnimationSpeed(cfg.snapbackSpeed) !== true) {
395     cfg.snapbackSpeed = 50;
396   }
397   if (cfg.hasOwnProperty('snapSpeed') !== true ||
398       validAnimationSpeed(cfg.snapSpeed) !== true) {
399     cfg.snapSpeed = 25;
400   }
401   if (cfg.hasOwnProperty('trashSpeed') !== true ||
402       validAnimationSpeed(cfg.trashSpeed) !== true) {
403     cfg.trashSpeed = 100;
404   }
405
406   // make sure position is valid
407   if (cfg.hasOwnProperty('position') === true) {
408     if (cfg.position === 'start') {
409       CURRENT_POSITION = deepCopy(START_POSITION);
410     }
411
412     else if (validFen(cfg.position) === true) {
413       CURRENT_POSITION = fenToObj(cfg.position);
414     }
415
416     else if (validPositionObject(cfg.position) === true) {
417       CURRENT_POSITION = deepCopy(cfg.position);
418     }
419
420     else {
421       error(7263, 'Invalid value passed to config.position.', cfg.position);
422     }
423   }
424
425   return true;
426 }
427
428 //------------------------------------------------------------------------------
429 // DOM Misc
430 //------------------------------------------------------------------------------
431
432 // calculates square size based on the width of the container
433 // got a little CSS black magic here, so let me explain:
434 // get the width of the container element (could be anything), reduce by 1 for
435 // fudge factor, and then keep reducing until we find an exact mod 8 for
436 // our square size
437 function calculateSquareSize() {
438   var containerWidth = parseInt(getComputedStyle(containerEl).width, 10);
439
440   // defensive, prevent infinite loop
441   if (! containerWidth || containerWidth <= 0) {
442     return 0;
443   }
444
445   // pad one pixel
446   var boardWidth = containerWidth - 1;
447
448   while (boardWidth % 8 !== 0 && boardWidth > 0) {
449     boardWidth--;
450   }
451
452   return (boardWidth / 8);
453 }
454
455 // create random IDs for elements
456 function createElIds() {
457   // squares on the board
458   for (var i = 0; i < COLUMNS.length; i++) {
459     for (var j = 1; j <= 8; j++) {
460       var square = COLUMNS[i] + j;
461       SQUARE_ELS_IDS[square] = square + '-' + createId();
462     }
463   }
464 }
465
466 //------------------------------------------------------------------------------
467 // Markup Building
468 //------------------------------------------------------------------------------
469
470 function buildBoardContainer() {
471   var html = '<div class="' + CSS.chessboard + '">';
472
473   html += '<div class="' + CSS.board + '"></div>';
474
475   html += '</div>';
476
477   return html;
478 }
479
480 /*
481 var buildSquare = function(color, size, id) {
482   var html = '<div class="' + CSS.square + ' ' + CSSColor[color] + '" ' +
483   'style="width: ' + size + 'px; height: ' + size + 'px" ' +
484   'id="' + id + '">';
485
486   if (cfg.showNotation === true) {
487
488   }
489
490   html += '</div>';
491
492   return html;
493 };
494 */
495
496 function buildBoard(orientation) {
497   if (orientation !== 'black') {
498     orientation = 'white';
499   }
500
501   var html = '';
502
503   // algebraic notation / orientation
504   var alpha = deepCopy(COLUMNS);
505   var row = 8;
506   if (orientation === 'black') {
507     alpha.reverse();
508     row = 1;
509   }
510
511   var squareColor = 'white';
512   for (var i = 0; i < 8; i++) {
513     html += '<div class="' + CSS.row + '">';
514     for (var j = 0; j < 8; j++) {
515       var square = alpha[j] + row;
516
517       html += '<div class="' + CSS.square + ' ' + CSSColor[squareColor] + ' ' +
518         'square-' + square + '" ' +
519         'style="width: ' + SQUARE_SIZE + 'px; height: ' + SQUARE_SIZE + 'px" ' +
520         'id="' + SQUARE_ELS_IDS[square] + '" ' +
521         'data-square="' + square + '">';
522
523       if (cfg.showNotation === true) {
524         // alpha notation
525         if ((orientation === 'white' && row === 1) ||
526             (orientation === 'black' && row === 8)) {
527           html += '<div class="' + CSS.notation + ' ' + CSS.alpha + '">' +
528             alpha[j] + '</div>';
529         }
530
531         // numeric notation
532         if (j === 0) {
533           html += '<div class="' + CSS.notation + ' ' + CSS.numeric + '">' +
534             row + '</div>';
535         }
536       }
537
538       html += '</div>'; // end .square
539
540       squareColor = (squareColor === 'white' ? 'black' : 'white');
541     }
542     html += '<div class="' + CSS.clearfix + '"></div></div>';
543
544     squareColor = (squareColor === 'white' ? 'black' : 'white');
545
546     if (orientation === 'white') {
547       row--;
548     }
549     else {
550       row++;
551     }
552   }
553
554   return html;
555 }
556
557 function buildPieceImgSrc(piece) {
558   if (typeof cfg.pieceTheme === 'function') {
559     return cfg.pieceTheme(piece);
560   }
561
562   if (typeof cfg.pieceTheme === 'string') {
563     return cfg.pieceTheme.replace(/{piece}/g, piece);
564   }
565
566   // NOTE: this should never happen
567   error(8272, 'Unable to build image source for cfg.pieceTheme.');
568   return '';
569 }
570
571 /**
572  * @param {!string} piece
573  * @param {boolean=} hidden
574  * @param {!string=} id
575  */
576 function buildPiece(piece, hidden, id) {
577   let img = document.createElement('img');
578   img.src = buildPieceImgSrc(piece);
579   if (id && typeof id === 'string') {
580     img.setAttribute('id', id);
581   }
582   img.setAttribute('alt', '');
583   img.classList.add(CSS.piece);
584   img.setAttribute('data-piece', piece);
585   img.style.width = SQUARE_SIZE + 'px';
586   img.style.height = SQUARE_SIZE + 'px';
587   if (hidden === true) {
588     img.style.display = 'none';
589   }
590   return img;
591 }
592
593 //------------------------------------------------------------------------------
594 // Animations
595 //------------------------------------------------------------------------------
596
597 function offset(el) {  // From https://youmightnotneedjquery.com/.
598   let box = el.getBoundingClientRect();
599   let docElem = document.documentElement;
600   return {
601     top: box.top + window.pageYOffset - docElem.clientTop,
602     left: box.left + window.pageXOffset - docElem.clientLeft
603   };
604 }
605
606 function animateSquareToSquare(moved_pieces, completeFn) {
607   let pieces = [];
608   for (const {source, destination, piece} of moved_pieces) {
609     // get information about the source and destination squares
610     let srcSquareEl = document.getElementById(SQUARE_ELS_IDS[source]);
611     let srcSquarePosition = offset(srcSquareEl);
612     let destSquareEl = document.getElementById(SQUARE_ELS_IDS[destination]);
613     let destSquarePosition = offset(destSquareEl);
614
615     // create the animated piece and absolutely position it
616     // over the source square
617     let animatedPieceId = createId();
618     document.body.append(buildPiece(piece, true, animatedPieceId));
619     let animatedPieceEl = document.getElementById(animatedPieceId);
620     animatedPieceEl.style.display = null;
621     animatedPieceEl.style.position = 'absolute';
622     animatedPieceEl.style.top = srcSquarePosition.top + 'px';
623     animatedPieceEl.style.left = srcSquarePosition.left + 'px';
624
625     // remove original piece(s) from source square
626     // TODO: multiple pieces should never really happen, but it will if we are moving
627     // while another animation still isn't done
628     srcSquareEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
629
630     // on complete
631     let complete = function() {
632       // add the "real" piece to the destination square
633       destSquareEl.append(buildPiece(piece));
634
635       // remove the animated piece
636       animatedPieceEl.remove();
637
638       // run complete function
639       if (typeof completeFn === 'function') {
640         completeFn();
641       }
642     };
643
644     // animate the piece to the destination square
645     animatedPieceEl.addEventListener('transitionend', complete, {once: true});
646     pieces.push([animatedPieceEl, destSquarePosition]);
647   }
648   requestAnimationFrame(() => {
649     for (let [animatedPieceEl, destSquarePosition] of pieces) {
650       animatedPieceEl.style.transitionProperty = 'top, left';
651       animatedPieceEl.style.transitionDuration = cfg.moveSpeed + 'ms';
652       animatedPieceEl.style.top = destSquarePosition.top + 'px';
653       animatedPieceEl.style.left = destSquarePosition.left + 'px';
654     }
655   });
656 }
657
658 function fadeIn(pieces, onFinish) {
659   pieces.forEach((piece) => {
660     piece.style.opacity = 0;
661     piece.style.display = null;
662     piece.addEventListener('transitionend', onFinish, {once: true});
663   });
664   requestAnimationFrame(() => {
665     pieces.forEach((piece) => {
666       piece.style.transitionProperty = 'opacity';
667       piece.style.transitionDuration = cfg.appearSpeed + 'ms';
668       piece.style.opacity = 1;
669     });
670   });
671 }
672
673 function fadeOut(pieces, onFinish) {
674   pieces.forEach((piece) => {
675     piece.style.opacity = 1;
676     piece.style.display = null;
677     piece.addEventListener('transitionend', onFinish, {once: true});
678   });
679   requestAnimationFrame(() => {
680     pieces.forEach((piece) => {
681       piece.style.transitionProperty = 'opacity';
682       piece.style.transitionDuration = cfg.trashSpeed + 'ms';
683       piece.style.opacity = 0;
684     });
685   });
686 }
687
688 // execute an array of animations
689 function doAnimations(a, oldPos, newPos) {
690   var numFinished = 0;
691   function onFinish(e) {
692     if (e && e.target) {
693       e.target.transitionProperty = null;
694     }
695
696     numFinished++;
697
698     // exit if all the animations aren't finished
699     if (numFinished !== a.length) return;
700
701     drawPositionInstant();
702
703     // run their onMoveEnd function
704     if (cfg.hasOwnProperty('onMoveEnd') === true &&
705       typeof cfg.onMoveEnd === 'function') {
706       cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
707     }
708   }
709
710   requestAnimationFrame(() => {  // Firefox workaround.
711     let fadeout_pieces = [];
712     let fadein_pieces = [];
713     let moved_pieces = [];
714
715     for (var i = 0; i < a.length; i++) {
716       // clear a piece
717       if (a[i].type === 'clear') {
718         document.getElementById(SQUARE_ELS_IDS[a[i].square]).querySelectorAll('.' + CSS.piece).forEach(
719           (piece) => fadeout_pieces.push(piece)
720         );
721       }
722
723       // add a piece
724       if (a[i].type === 'add') {
725         let square = document.getElementById(SQUARE_ELS_IDS[a[i].square]);
726         square.append(buildPiece(a[i].piece, true));
727         let piece = square.querySelector('.' + CSS.piece);
728         fadein_pieces.push(piece);
729       }
730
731       // move a piece
732       if (a[i].type === 'move') {
733         moved_pieces.push(a[i]);
734       }
735     }
736
737     // TODO: Batch moves as well, not just fade in/out.
738     // (We batch them because requestAnimationFrame seemingly costs real time.)
739     if (fadeout_pieces.length > 0) {
740       fadeOut(fadeout_pieces, onFinish);
741     }
742     if (fadein_pieces.length > 0) {
743       fadeIn(fadein_pieces, onFinish);
744     }
745     if (moved_pieces.length > 0) {
746       animateSquareToSquare(moved_pieces, onFinish);
747     }
748   });
749 }
750
751 // returns the distance between two squares
752 function squareDistance(s1, s2) {
753   s1 = s1.split('');
754   var s1x = COLUMNS.indexOf(s1[0]) + 1;
755   var s1y = parseInt(s1[1], 10);
756
757   s2 = s2.split('');
758   var s2x = COLUMNS.indexOf(s2[0]) + 1;
759   var s2y = parseInt(s2[1], 10);
760
761   var xDelta = Math.abs(s1x - s2x);
762   var yDelta = Math.abs(s1y - s2y);
763
764   if (xDelta >= yDelta) return xDelta;
765   return yDelta;
766 }
767
768 // returns the square of the closest instance of piece
769 // returns false if no instance of piece is found in position
770 function findClosestPiece(position, piece, square) {
771   let best_square = false;
772   let best_dist = 1e9;
773   for (var i = 0; i < COLUMNS.length; i++) {
774     for (var j = 1; j <= 8; j++) {
775       let other_square = COLUMNS[i] + j;
776
777       if (position[other_square] === piece && square != other_square) {
778         let dist = squareDistance(square, other_square);
779         if (dist < best_dist) {
780           best_square = other_square;
781           best_dist = dist;
782         }
783       }
784     }
785   }
786
787   return best_square;
788 }
789
790 // calculate an array of animations that need to happen in order to get
791 // from pos1 to pos2
792 function calculateAnimations(pos1, pos2) {
793   // make copies of both
794   pos1 = deepCopy(pos1);
795   pos2 = deepCopy(pos2);
796
797   var animations = [];
798   var squaresMovedTo = {};
799
800   // remove pieces that are the same in both positions
801   for (var i in pos2) {
802     if (pos2.hasOwnProperty(i) !== true) continue;
803
804     if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
805       delete pos1[i];
806       delete pos2[i];
807     }
808   }
809
810   // find all the "move" animations
811   for (var i in pos2) {
812     if (pos2.hasOwnProperty(i) !== true) continue;
813
814     var closestPiece = findClosestPiece(pos1, pos2[i], i);
815     if (closestPiece !== false) {
816       animations.push({
817         type: 'move',
818         source: closestPiece,
819         destination: i,
820         piece: pos2[i]
821       });
822
823       delete pos1[closestPiece];
824       delete pos2[i];
825       squaresMovedTo[i] = true;
826     }
827   }
828
829   // add pieces to pos2
830   for (var i in pos2) {
831     if (pos2.hasOwnProperty(i) !== true) continue;
832
833     animations.push({
834       type: 'add',
835       square: i,
836       piece: pos2[i]
837     })
838
839     delete pos2[i];
840   }
841
842   // clear pieces from pos1
843   for (var i in pos1) {
844     if (pos1.hasOwnProperty(i) !== true) continue;
845
846     // do not clear a piece if it is on a square that is the result
847     // of a "move", ie: a piece capture
848     if (squaresMovedTo.hasOwnProperty(i) === true) continue;
849
850     animations.push({
851       type: 'clear',
852       square: i,
853       piece: pos1[i]
854     });
855
856     delete pos1[i];
857   }
858
859   return animations;
860 }
861
862 //------------------------------------------------------------------------------
863 // Control Flow
864 //------------------------------------------------------------------------------
865
866 function drawPositionInstant() {
867   // clear the board
868   boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
869
870   // add the pieces
871   for (var i in CURRENT_POSITION) {
872     if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue;
873
874     document.getElementById(SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i]));
875   }
876 }
877
878 function drawBoard() {
879   boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
880   drawPositionInstant();
881 }
882
883 // given a position and a set of moves, return a new position
884 // with the moves executed
885 function calculatePositionFromMoves(position, moves) {
886   position = deepCopy(position);
887
888   for (var i in moves) {
889     if (moves.hasOwnProperty(i) !== true) continue;
890
891     // skip the move if the position doesn't have a piece on the source square
892     if (position.hasOwnProperty(i) !== true) continue;
893
894     var piece = position[i];
895     delete position[i];
896     position[moves[i]] = piece;
897   }
898
899   return position;
900 }
901
902 function setCurrentPosition(position) {
903   var oldPos = deepCopy(CURRENT_POSITION);
904   var newPos = deepCopy(position);
905   var oldFen = objToFen(oldPos);
906   var newFen = objToFen(newPos);
907
908   // do nothing if no change in position
909   if (oldFen === newFen) return;
910
911   // run their onChange function
912   if (cfg.hasOwnProperty('onChange') === true &&
913     typeof cfg.onChange === 'function') {
914     cfg.onChange(oldPos, newPos);
915   }
916
917   // update state
918   CURRENT_POSITION = position;
919 }
920
921 function isXYOnSquare(x, y) {
922   for (var i in SQUARE_ELS_OFFSETS) {
923     if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue;
924
925     var s = SQUARE_ELS_OFFSETS[i];
926     if (x >= s.left && x < s.left + SQUARE_SIZE &&
927         y >= s.top && y < s.top + SQUARE_SIZE) {
928       return i;
929     }
930   }
931
932   return 'offboard';
933 }
934
935 // records the XY coords of every square into memory
936 function captureSquareOffsets() {
937   SQUARE_ELS_OFFSETS = {};
938
939   for (var i in SQUARE_ELS_IDS) {
940     if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue;
941
942     SQUARE_ELS_OFFSETS[i] = offset(document.getElementById(SQUARE_ELS_IDS[i]));
943   }
944 }
945
946 function removeSquareHighlights() {
947   boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
948     piece.classList.remove(CSS.highlight1);
949     piece.classList.remove(CSS.highlight2);
950   });
951 }
952
953 function snapbackDraggedPiece() {
954   removeSquareHighlights();
955
956   // animation complete
957   function complete() {
958     drawPositionInstant();
959     draggedPieceEl.style.display = 'none';
960
961     // run their onSnapbackEnd function
962     if (cfg.hasOwnProperty('onSnapbackEnd') === true &&
963       typeof cfg.onSnapbackEnd === 'function') {
964       cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
965         deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
966     }
967   }
968
969   // get source square position
970   var sourceSquarePosition =
971     offset(document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]));
972
973   // animate the piece to the target square
974   draggedPieceEl.addEventListener('transitionend', complete, {once: true});
975   requestAnimationFrame(() => {
976     draggedPieceEl.style.transitionProperty = 'top, left';
977     draggedPieceEl.style.transitionDuration = cfg.snapbackSpeed + 'ms';
978     draggedPieceEl.style.top = sourceSquarePosition.top + 'px';
979     draggedPieceEl.style.left = sourceSquarePosition.left + 'px';
980   });
981
982   // set state
983   DRAGGING_A_PIECE = false;
984 }
985
986 function dropDraggedPieceOnSquare(square) {
987   removeSquareHighlights();
988
989   // update position
990   var newPosition = deepCopy(CURRENT_POSITION);
991   delete newPosition[DRAGGED_PIECE_SOURCE];
992   newPosition[square] = DRAGGED_PIECE;
993   setCurrentPosition(newPosition);
994
995   // get target square information
996   var targetSquarePosition = offset(document.getElementById(SQUARE_ELS_IDS[square]));
997
998   // animation complete
999   var complete = function() {
1000     drawPositionInstant();
1001     draggedPieceEl.style.display = 'none';
1002
1003     // execute their onSnapEnd function
1004     if (cfg.hasOwnProperty('onSnapEnd') === true &&
1005       typeof cfg.onSnapEnd === 'function') {
1006       requestAnimationFrame(() => {  // HACK: so that we don't add event handlers from the callback...
1007         cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
1008       });
1009     }
1010   };
1011
1012   // snap the piece to the target square
1013   draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1014   requestAnimationFrame(() => {
1015     draggedPieceEl.style.transitionProperty = 'top, left';
1016     draggedPieceEl.style.transitionDuration = cfg.snapSpeed + 'ms';
1017     draggedPieceEl.style.top = targetSquarePosition.top + 'px';
1018     draggedPieceEl.style.left = targetSquarePosition.left + 'px';
1019   });
1020
1021   // set state
1022   DRAGGING_A_PIECE = false;
1023 }
1024
1025 function beginDraggingPiece(source, piece, x, y) {
1026   // run their custom onDragStart function
1027   // their custom onDragStart function can cancel drag start
1028   if (typeof cfg.onDragStart === 'function' &&
1029       cfg.onDragStart(source, piece,
1030         deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
1031     return;
1032   }
1033
1034   // set state
1035   DRAGGING_A_PIECE = true;
1036   DRAGGED_PIECE = piece;
1037   DRAGGED_PIECE_SOURCE = source;
1038   DRAGGED_PIECE_LOCATION = source;
1039
1040   // capture the x, y coords of all squares in memory
1041   captureSquareOffsets();
1042
1043   // create the dragged piece
1044   draggedPieceEl.setAttribute('src', buildPieceImgSrc(piece));
1045   draggedPieceEl.style.display = null;
1046   draggedPieceEl.style.position = 'absolute';
1047   draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1048   draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1049
1050   // highlight the source square and hide the piece
1051   let square = document.getElementById(SQUARE_ELS_IDS[source]);
1052   square.classList.add(CSS.highlight1);
1053   square.querySelector('.' + CSS.piece).style.display = 'none';
1054 }
1055
1056 function updateDraggedPiece(x, y) {
1057   // put the dragged piece over the mouse cursor
1058   draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1059   draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1060
1061   // get location
1062   var location = isXYOnSquare(x, y);
1063
1064   // do nothing if the location has not changed
1065   if (location === DRAGGED_PIECE_LOCATION) return;
1066
1067   // remove highlight from previous square
1068   if (validSquare(DRAGGED_PIECE_LOCATION) === true) {
1069     document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION])
1070       .classList.remove(CSS.highlight2);
1071   }
1072
1073   // add highlight to new square
1074   if (validSquare(location) === true) {
1075     document.getElementById(SQUARE_ELS_IDS[location]).classList.add(CSS.highlight2);
1076   }
1077
1078   // run onDragMove
1079   if (typeof cfg.onDragMove === 'function') {
1080     cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1081       DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1082       deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1083   }
1084
1085   // update state
1086   DRAGGED_PIECE_LOCATION = location;
1087 }
1088
1089 function stopDraggedPiece(location) {
1090   // determine what the action should be
1091   var action = 'drop';
1092   if (location === 'offboard' && cfg.dropOffBoard === 'snapback') {
1093     action = 'snapback';
1094   }
1095
1096   // run their onDrop function, which can potentially change the drop action
1097   if (cfg.hasOwnProperty('onDrop') === true &&
1098     typeof cfg.onDrop === 'function') {
1099     var newPosition = deepCopy(CURRENT_POSITION);
1100
1101     // source piece was on the board and position is on the board
1102     if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1103       validSquare(location) === true) {
1104       // move the piece
1105       delete newPosition[DRAGGED_PIECE_SOURCE];
1106       newPosition[location] = DRAGGED_PIECE;
1107     }
1108
1109     var oldPosition = deepCopy(CURRENT_POSITION);
1110
1111     var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE,
1112       newPosition, oldPosition, CURRENT_ORIENTATION);
1113     if (result === 'snapback') {
1114       action = result;
1115     }
1116   }
1117
1118   // do it!
1119   if (action === 'snapback') {
1120     snapbackDraggedPiece();
1121   }
1122   else if (action === 'drop') {
1123     dropDraggedPieceOnSquare(location);
1124   }
1125 }
1126
1127 //------------------------------------------------------------------------------
1128 // Public Methods
1129 //------------------------------------------------------------------------------
1130
1131 // clear the board
1132 widget.clear = function(useAnimation) {
1133   widget.position({}, useAnimation);
1134 };
1135
1136 /*
1137 // get or set config properties
1138 // TODO: write this, GitHub Issue #1
1139 widget.config = function(arg1, arg2) {
1140   // get the current config
1141   if (arguments.length === 0) {
1142     return deepCopy(cfg);
1143   }
1144 };
1145 */
1146
1147 // remove the widget from the page
1148 widget.destroy = function() {
1149   // remove markup
1150   containerEl.innerHTML = '';
1151   draggedPieceEl.remove();
1152 };
1153
1154 // shorthand method to get the current FEN
1155 widget.fen = function() {
1156   return widget.position('fen');
1157 };
1158
1159 // flip orientation
1160 widget.flip = function() {
1161   widget.orientation('flip');
1162 };
1163
1164 /*
1165 // TODO: write this, GitHub Issue #5
1166 widget.highlight = function() {
1167
1168 };
1169 */
1170
1171 // move pieces
1172 widget.move = function() {
1173   // no need to throw an error here; just do nothing
1174   if (arguments.length === 0) return;
1175
1176   var useAnimation = true;
1177
1178   // collect the moves into an object
1179   var moves = {};
1180   for (var i = 0; i < arguments.length; i++) {
1181     // any "false" to this function means no animations
1182     if (arguments[i] === false) {
1183       useAnimation = false;
1184       continue;
1185     }
1186
1187     // skip invalid arguments
1188     if (validMove(arguments[i]) !== true) {
1189       error(2826, 'Invalid move passed to the move method.', arguments[i]);
1190       continue;
1191     }
1192
1193     var tmp = arguments[i].split('-');
1194     moves[tmp[0]] = tmp[1];
1195   }
1196
1197   // calculate position from moves
1198   var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1199
1200   // update the board
1201   widget.position(newPos, useAnimation);
1202
1203   // return the new position object
1204   return newPos;
1205 };
1206
1207 widget.orientation = function(arg) {
1208   // no arguments, return the current orientation
1209   if (arguments.length === 0) {
1210     return CURRENT_ORIENTATION;
1211   }
1212
1213   // set to white or black
1214   if (arg === 'white' || arg === 'black') {
1215     CURRENT_ORIENTATION = arg;
1216     drawBoard();
1217     return;
1218   }
1219
1220   // flip orientation
1221   if (arg === 'flip') {
1222     CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1223     drawBoard();
1224     return;
1225   }
1226
1227   error(5482, 'Invalid value passed to the orientation method.', arg);
1228 };
1229
1230 /**
1231  * @param {!string|!Object} position
1232  * @param {boolean=} useAnimation
1233  */
1234 widget.position = function(position, useAnimation) {
1235   // no arguments, return the current position
1236   if (arguments.length === 0) {
1237     return deepCopy(CURRENT_POSITION);
1238   }
1239
1240   // get position as FEN
1241   if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1242     return objToFen(CURRENT_POSITION);
1243   }
1244
1245   // default for useAnimations is true
1246   if (useAnimation !== false) {
1247     useAnimation = true;
1248   }
1249
1250   // start position
1251   if (typeof position === 'string' && position.toLowerCase() === 'start') {
1252     position = deepCopy(START_POSITION);
1253   }
1254
1255   // convert FEN to position object
1256   if (validFen(position) === true) {
1257     position = fenToObj(position);
1258   }
1259
1260   // validate position object
1261   if (validPositionObject(position) !== true) {
1262     error(6482, 'Invalid value passed to the position method.', position);
1263     return;
1264   }
1265
1266   if (useAnimation === true) {
1267     // start the animations
1268     doAnimations(calculateAnimations(CURRENT_POSITION, position),
1269       CURRENT_POSITION, position);
1270
1271     // set the new position
1272     setCurrentPosition(position);
1273   }
1274   // instant update
1275   else {
1276     setCurrentPosition(position);
1277     drawPositionInstant();
1278   }
1279 };
1280
1281 widget.resize = function() {
1282   // calulate the new square size
1283   SQUARE_SIZE = calculateSquareSize();
1284
1285   // set board width
1286   boardEl.style.width = (SQUARE_SIZE * 8) + 'px';
1287
1288   // set drag piece size
1289   if (draggedPieceEl !== null) {
1290     draggedPieceEl.style.height = SQUARE_SIZE + 'px';
1291     draggedPieceEl.style.width = SQUARE_SIZE + 'px';
1292   }
1293
1294   // redraw the board
1295   drawBoard();
1296 };
1297
1298 // set the starting position
1299 widget.start = function(useAnimation) {
1300   widget.position('start', useAnimation);
1301 };
1302
1303 //------------------------------------------------------------------------------
1304 // Browser Events
1305 //------------------------------------------------------------------------------
1306
1307 function isTouchDevice() {
1308   return ('ontouchstart' in document.documentElement);
1309 }
1310
1311 function mousedownSquare(e) {
1312   let target = e.target.closest('.' + CSS.square);
1313   if (!target) {
1314     return;
1315   }
1316
1317   // do nothing if we're not draggable
1318   if (cfg.draggable !== true) return;
1319
1320   var square = target.getAttribute('data-square');
1321
1322   // no piece on this square
1323   if (validSquare(square) !== true ||
1324       CURRENT_POSITION.hasOwnProperty(square) !== true) {
1325     return;
1326   }
1327
1328   beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1329 }
1330
1331 function touchstartSquare(e) {
1332   let target = e.target.closest('.' + CSS.square);
1333   if (!target) {
1334     return;
1335   }
1336
1337   // do nothing if we're not draggable
1338   if (cfg.draggable !== true) return;
1339
1340   var square = target.getAttribute('data-square');
1341
1342   // no piece on this square
1343   if (validSquare(square) !== true ||
1344       CURRENT_POSITION.hasOwnProperty(square) !== true) {
1345     return;
1346   }
1347
1348   beginDraggingPiece(square, CURRENT_POSITION[square],
1349     e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1350 }
1351
1352 function mousemoveWindow(e) {
1353   // do nothing if we are not dragging a piece
1354   if (DRAGGING_A_PIECE !== true) return;
1355
1356   updateDraggedPiece(e.pageX, e.pageY);
1357 }
1358
1359 function touchmoveWindow(e) {
1360   // do nothing if we are not dragging a piece
1361   if (DRAGGING_A_PIECE !== true) return;
1362
1363   // prevent screen from scrolling
1364   e.preventDefault();
1365
1366   updateDraggedPiece(e.changedTouches[0].pageX,
1367     e.changedTouches[0].pageY);
1368 }
1369
1370 function mouseupWindow(e) {
1371   // do nothing if we are not dragging a piece
1372   if (DRAGGING_A_PIECE !== true) return;
1373
1374   // get the location
1375   var location = isXYOnSquare(e.pageX, e.pageY);
1376
1377   stopDraggedPiece(location);
1378 }
1379
1380 function touchendWindow(e) {
1381   // do nothing if we are not dragging a piece
1382   if (DRAGGING_A_PIECE !== true) return;
1383
1384   // get the location
1385   var location = isXYOnSquare(e.changedTouches[0].pageX,
1386     e.changedTouches[0].pageY);
1387
1388   stopDraggedPiece(location);
1389 }
1390
1391 function mouseenterSquare(e) {
1392   let target = e.target.closest('.' + CSS.square);
1393   if (!target) {
1394     return;
1395   }
1396
1397   // do not fire this event if we are dragging a piece
1398   // NOTE: this should never happen, but it's a safeguard
1399   if (DRAGGING_A_PIECE !== false) return;
1400
1401   if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1402     typeof cfg.onMouseoverSquare !== 'function') return;
1403
1404   // get the square
1405   var square = target.getAttribute('data-square');
1406
1407   // NOTE: this should never happen; defensive
1408   if (validSquare(square) !== true) return;
1409
1410   // get the piece on this square
1411   var piece = false;
1412   if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1413     piece = CURRENT_POSITION[square];
1414   }
1415
1416   // execute their function
1417   cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1418     CURRENT_ORIENTATION);
1419 }
1420
1421 function mouseleaveSquare(e) {
1422   let target = e.target.closest('.' + CSS.square);
1423   if (!target) {
1424     return;
1425   }
1426
1427   // do not fire this event if we are dragging a piece
1428   // NOTE: this should never happen, but it's a safeguard
1429   if (DRAGGING_A_PIECE !== false) return;
1430
1431   if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1432     typeof cfg.onMouseoutSquare !== 'function') return;
1433
1434   // get the square
1435   var square = target.getAttribute('data-square');
1436
1437   // NOTE: this should never happen; defensive
1438   if (validSquare(square) !== true) return;
1439
1440   // get the piece on this square
1441   var piece = false;
1442   if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1443     piece = CURRENT_POSITION[square];
1444   }
1445
1446   // execute their function
1447   cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1448     CURRENT_ORIENTATION);
1449 }
1450
1451 //------------------------------------------------------------------------------
1452 // Initialization
1453 //------------------------------------------------------------------------------
1454
1455 function addEvents() {
1456   // prevent browser "image drag"
1457   let stopDefault = (e) => {
1458     if (e.target.matches('.' + CSS.piece)) {
1459       e.preventDefault();
1460     }
1461   };
1462   document.body.addEventListener('mousedown', stopDefault);
1463   document.body.addEventListener('mousemove', stopDefault);
1464
1465   // mouse drag pieces
1466   boardEl.addEventListener('mousedown', mousedownSquare);
1467
1468   // mouse enter / leave square
1469   boardEl.addEventListener('mouseenter', mouseenterSquare);
1470   boardEl.addEventListener('mouseleave', mouseleaveSquare);
1471
1472   window.addEventListener('mousemove', mousemoveWindow);
1473   window.addEventListener('mouseup', mouseupWindow);
1474
1475   // touch drag pieces
1476   if (isTouchDevice() === true) {
1477     boardEl.addEventListener('touchstart', touchstartSquare);
1478     window.addEventListener('touchmove', touchmoveWindow);
1479     window.addEventListener('touchend', touchendWindow);
1480   }
1481 }
1482
1483 function initDom() {
1484   // build board and save it in memory
1485   containerEl.innerHTML = buildBoardContainer();
1486   boardEl = containerEl.querySelector('.' + CSS.board);
1487
1488   // create the drag piece
1489   var draggedPieceId = createId();
1490   document.body.append(buildPiece('wP', true, draggedPieceId));
1491   draggedPieceEl = document.getElementById(draggedPieceId);
1492
1493   // get the border size
1494   BOARD_BORDER_SIZE = parseInt(boardEl.style.borderLeftWidth, 10);
1495
1496   // set the size and draw the board
1497   widget.resize();
1498 }
1499
1500 function init() {
1501   if (checkDeps() !== true ||
1502       expandConfig() !== true) return;
1503
1504   // create unique IDs for all the elements we will create
1505   createElIds();
1506
1507   initDom();
1508   addEvents();
1509 }
1510
1511 // go time
1512 init();
1513
1514 // return the widget object
1515 return widget;
1516
1517 }; // end window.ChessBoard
1518
1519 // expose util functions
1520 window.ChessBoard.fenToObj = fenToObj;
1521 window.ChessBoard.objToFen = objToFen;
1522
1523 })(); // end anonymous wrapper