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