]> git.sesse.net Git - remoteglot/blob - www/js/chessboard-0.3.0.js
Remove obsolete jQuery version checks.
[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 for dropOffBoard is 'snapback'
378   if (cfg.dropOffBoard !== 'trash') {
379     cfg.dropOffBoard = 'snapback';
380   }
381
382   // default piece theme is wikipedia
383   if (cfg.hasOwnProperty('pieceTheme') !== true ||
384       (typeof cfg.pieceTheme !== 'string' &&
385        typeof cfg.pieceTheme !== 'function')) {
386     cfg.pieceTheme = 'img/chesspieces/wikipedia/{piece}.png';
387   }
388
389   // animation speeds
390   if (cfg.hasOwnProperty('appearSpeed') !== true ||
391       validAnimationSpeed(cfg.appearSpeed) !== true) {
392     cfg.appearSpeed = 200;
393   }
394   if (cfg.hasOwnProperty('moveSpeed') !== true ||
395       validAnimationSpeed(cfg.moveSpeed) !== true) {
396     cfg.moveSpeed = 200;
397   }
398   if (cfg.hasOwnProperty('snapbackSpeed') !== true ||
399       validAnimationSpeed(cfg.snapbackSpeed) !== true) {
400     cfg.snapbackSpeed = 50;
401   }
402   if (cfg.hasOwnProperty('snapSpeed') !== true ||
403       validAnimationSpeed(cfg.snapSpeed) !== true) {
404     cfg.snapSpeed = 25;
405   }
406   if (cfg.hasOwnProperty('trashSpeed') !== true ||
407       validAnimationSpeed(cfg.trashSpeed) !== true) {
408     cfg.trashSpeed = 100;
409   }
410
411   // make sure position is valid
412   if (cfg.hasOwnProperty('position') === true) {
413     if (cfg.position === 'start') {
414       CURRENT_POSITION = deepCopy(START_POSITION);
415     }
416
417     else if (validFen(cfg.position) === true) {
418       CURRENT_POSITION = fenToObj(cfg.position);
419     }
420
421     else if (validPositionObject(cfg.position) === true) {
422       CURRENT_POSITION = deepCopy(cfg.position);
423     }
424
425     else {
426       error(7263, 'Invalid value passed to config.position.', cfg.position);
427     }
428   }
429
430   return true;
431 }
432
433 //------------------------------------------------------------------------------
434 // DOM Misc
435 //------------------------------------------------------------------------------
436
437 // calculates square size based on the width of the container
438 // got a little CSS black magic here, so let me explain:
439 // get the width of the container element (could be anything), reduce by 1 for
440 // fudge factor, and then keep reducing until we find an exact mod 8 for
441 // our square size
442 function calculateSquareSize() {
443   var containerWidth = parseInt(getComputedStyle(containerEl).width, 10);
444
445   // defensive, prevent infinite loop
446   if (! containerWidth || containerWidth <= 0) {
447     return 0;
448   }
449
450   // pad one pixel
451   var boardWidth = containerWidth - 1;
452
453   while (boardWidth % 8 !== 0 && boardWidth > 0) {
454     boardWidth--;
455   }
456
457   return (boardWidth / 8);
458 }
459
460 // create random IDs for elements
461 function createElIds() {
462   // squares on the board
463   for (var i = 0; i < COLUMNS.length; i++) {
464     for (var j = 1; j <= 8; j++) {
465       var square = COLUMNS[i] + j;
466       SQUARE_ELS_IDS[square] = square + '-' + createId();
467     }
468   }
469 }
470
471 //------------------------------------------------------------------------------
472 // Markup Building
473 //------------------------------------------------------------------------------
474
475 function buildBoardContainer() {
476   var html = '<div class="' + CSS.chessboard + '">';
477
478   html += '<div class="' + CSS.board + '"></div>';
479
480   html += '</div>';
481
482   return html;
483 }
484
485 /*
486 var buildSquare = function(color, size, id) {
487   var html = '<div class="' + CSS.square + ' ' + CSSColor[color] + '" ' +
488   'style="width: ' + size + 'px; height: ' + size + 'px" ' +
489   'id="' + id + '">';
490
491   if (cfg.showNotation === true) {
492
493   }
494
495   html += '</div>';
496
497   return html;
498 };
499 */
500
501 function buildBoard(orientation) {
502   if (orientation !== 'black') {
503     orientation = 'white';
504   }
505
506   var html = '';
507
508   // algebraic notation / orientation
509   var alpha = deepCopy(COLUMNS);
510   var row = 8;
511   if (orientation === 'black') {
512     alpha.reverse();
513     row = 1;
514   }
515
516   var squareColor = 'white';
517   for (var i = 0; i < 8; i++) {
518     html += '<div class="' + CSS.row + '">';
519     for (var j = 0; j < 8; j++) {
520       var square = alpha[j] + row;
521
522       html += '<div class="' + CSS.square + ' ' + CSSColor[squareColor] + ' ' +
523         'square-' + square + '" ' +
524         'style="width: ' + SQUARE_SIZE + 'px; height: ' + SQUARE_SIZE + 'px" ' +
525         'id="' + SQUARE_ELS_IDS[square] + '" ' +
526         'data-square="' + square + '">';
527
528       if (cfg.showNotation === true) {
529         // alpha notation
530         if ((orientation === 'white' && row === 1) ||
531             (orientation === 'black' && row === 8)) {
532           html += '<div class="' + CSS.notation + ' ' + CSS.alpha + '">' +
533             alpha[j] + '</div>';
534         }
535
536         // numeric notation
537         if (j === 0) {
538           html += '<div class="' + CSS.notation + ' ' + CSS.numeric + '">' +
539             row + '</div>';
540         }
541       }
542
543       html += '</div>'; // end .square
544
545       squareColor = (squareColor === 'white' ? 'black' : 'white');
546     }
547     html += '<div class="' + CSS.clearfix + '"></div></div>';
548
549     squareColor = (squareColor === 'white' ? 'black' : 'white');
550
551     if (orientation === 'white') {
552       row--;
553     }
554     else {
555       row++;
556     }
557   }
558
559   return html;
560 }
561
562 function buildPieceImgSrc(piece) {
563   if (typeof cfg.pieceTheme === 'function') {
564     return cfg.pieceTheme(piece);
565   }
566
567   if (typeof cfg.pieceTheme === 'string') {
568     return cfg.pieceTheme.replace(/{piece}/g, piece);
569   }
570
571   // NOTE: this should never happen
572   error(8272, 'Unable to build image source for cfg.pieceTheme.');
573   return '';
574 }
575
576 /**
577  * @param {!string} piece
578  * @param {boolean=} hidden
579  * @param {!string=} id
580  */
581 function buildPiece(piece, hidden, id) {
582   let img = document.createElement('img');
583   img.src = buildPieceImgSrc(piece);
584   if (id && typeof id === 'string') {
585     img.setAttribute('id', id);
586   }
587   img.setAttribute('alt', '');
588   img.classList.add(CSS.piece);
589   img.setAttribute('data-piece', piece);
590   img.style.width = SQUARE_SIZE + 'px';
591   img.style.height = SQUARE_SIZE + 'px';
592   if (hidden === true) {
593     img.style.display = 'none';
594   }
595   return img;
596 }
597
598 //------------------------------------------------------------------------------
599 // Animations
600 //------------------------------------------------------------------------------
601
602 function offset(el) {  // From https://youmightnotneedjquery.com/.
603   let box = el.getBoundingClientRect();
604   let docElem = document.documentElement;
605   return {
606     top: box.top + window.pageYOffset - docElem.clientTop,
607     left: box.left + window.pageXOffset - docElem.clientLeft
608   };
609 }
610
611 function animateSquareToSquare(src, dest, piece, completeFn) {
612   // get information about the source and destination squares
613   var srcSquareEl = document.getElementById(SQUARE_ELS_IDS[src]);
614   var srcSquarePosition = offset(srcSquareEl);
615   var destSquareEl = document.getElementById(SQUARE_ELS_IDS[dest]);
616   var destSquarePosition = offset(destSquareEl);
617
618   // create the animated piece and absolutely position it
619   // over the source square
620   var animatedPieceId = createId();
621   document.body.append(buildPiece(piece, true, animatedPieceId));
622   var animatedPieceEl = document.getElementById(animatedPieceId);
623   animatedPieceEl.style.display = null;
624   animatedPieceEl.style.position = 'absolute';
625   animatedPieceEl.style.top = srcSquarePosition.top + 'px';
626   animatedPieceEl.style.left = srcSquarePosition.left + 'px';
627
628   // remove original piece(s) from source square
629   // TODO: multiple pieces should never really happen, but it will if we are moving
630   // while another animation still isn't done
631   srcSquareEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
632
633   // on complete
634   var complete = function() {
635     // add the "real" piece to the destination square
636     destSquareEl.append(buildPiece(piece));
637
638     // remove the animated piece
639     animatedPieceEl.remove();
640
641     // run complete function
642     if (typeof completeFn === 'function') {
643       completeFn();
644     }
645   };
646
647   // animate the piece to the destination square
648   animatedPieceEl.addEventListener('transitionend', complete, {once: true});
649   requestAnimationFrame(() => {
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 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
713     for (var i = 0; i < a.length; i++) {
714       // clear a piece
715       if (a[i].type === 'clear') {
716         document.getElementById(SQUARE_ELS_IDS[a[i].square]).querySelectorAll('.' + CSS.piece).forEach(
717           (piece) => fadeout_pieces.push(piece)
718         );
719       }
720
721       // add a piece
722       if (a[i].type === 'add') {
723         let square = document.getElementById(SQUARE_ELS_IDS[a[i].square]);
724         square.append(buildPiece(a[i].piece, true));
725         let piece = square.querySelector('.' + CSS.piece);
726         fadein_pieces.push(piece);
727       }
728
729       // move a piece
730       if (a[i].type === 'move') {
731         animateSquareToSquare(a[i].source, a[i].destination, a[i].piece,
732           onFinish);
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   });
745 }
746
747 // returns the distance between two squares
748 function squareDistance(s1, s2) {
749   s1 = s1.split('');
750   var s1x = COLUMNS.indexOf(s1[0]) + 1;
751   var s1y = parseInt(s1[1], 10);
752
753   s2 = s2.split('');
754   var s2x = COLUMNS.indexOf(s2[0]) + 1;
755   var s2y = parseInt(s2[1], 10);
756
757   var xDelta = Math.abs(s1x - s2x);
758   var yDelta = Math.abs(s1y - s2y);
759
760   if (xDelta >= yDelta) return xDelta;
761   return yDelta;
762 }
763
764 // returns the square of the closest instance of piece
765 // returns false if no instance of piece is found in position
766 function findClosestPiece(position, piece, square) {
767   let best_square = false;
768   let best_dist = 1e9;
769   for (var i = 0; i < COLUMNS.length; i++) {
770     for (var j = 1; j <= 8; j++) {
771       let other_square = COLUMNS[i] + j;
772
773       if (position[other_square] === piece && square != other_square) {
774         let dist = squareDistance(square, other_square);
775         if (dist < best_dist) {
776           best_square = other_square;
777           best_dist = dist;
778         }
779       }
780     }
781   }
782
783   return best_square;
784 }
785
786 // calculate an array of animations that need to happen in order to get
787 // from pos1 to pos2
788 function calculateAnimations(pos1, pos2) {
789   // make copies of both
790   pos1 = deepCopy(pos1);
791   pos2 = deepCopy(pos2);
792
793   var animations = [];
794   var squaresMovedTo = {};
795
796   // remove pieces that are the same in both positions
797   for (var i in pos2) {
798     if (pos2.hasOwnProperty(i) !== true) continue;
799
800     if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
801       delete pos1[i];
802       delete pos2[i];
803     }
804   }
805
806   // find all the "move" animations
807   for (var i in pos2) {
808     if (pos2.hasOwnProperty(i) !== true) continue;
809
810     var closestPiece = findClosestPiece(pos1, pos2[i], i);
811     if (closestPiece !== false) {
812       animations.push({
813         type: 'move',
814         source: closestPiece,
815         destination: i,
816         piece: pos2[i]
817       });
818
819       delete pos1[closestPiece];
820       delete pos2[i];
821       squaresMovedTo[i] = true;
822     }
823   }
824
825   // add pieces to pos2
826   for (var i in pos2) {
827     if (pos2.hasOwnProperty(i) !== true) continue;
828
829     animations.push({
830       type: 'add',
831       square: i,
832       piece: pos2[i]
833     })
834
835     delete pos2[i];
836   }
837
838   // clear pieces from pos1
839   for (var i in pos1) {
840     if (pos1.hasOwnProperty(i) !== true) continue;
841
842     // do not clear a piece if it is on a square that is the result
843     // of a "move", ie: a piece capture
844     if (squaresMovedTo.hasOwnProperty(i) === true) continue;
845
846     animations.push({
847       type: 'clear',
848       square: i,
849       piece: pos1[i]
850     });
851
852     delete pos1[i];
853   }
854
855   return animations;
856 }
857
858 //------------------------------------------------------------------------------
859 // Control Flow
860 //------------------------------------------------------------------------------
861
862 function drawPositionInstant() {
863   // clear the board
864   boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
865
866   // add the pieces
867   for (var i in CURRENT_POSITION) {
868     if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue;
869
870     document.getElementById(SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i]));
871   }
872 }
873
874 function drawBoard() {
875   boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
876   drawPositionInstant();
877 }
878
879 // given a position and a set of moves, return a new position
880 // with the moves executed
881 function calculatePositionFromMoves(position, moves) {
882   position = deepCopy(position);
883
884   for (var i in moves) {
885     if (moves.hasOwnProperty(i) !== true) continue;
886
887     // skip the move if the position doesn't have a piece on the source square
888     if (position.hasOwnProperty(i) !== true) continue;
889
890     var piece = position[i];
891     delete position[i];
892     position[moves[i]] = piece;
893   }
894
895   return position;
896 }
897
898 function setCurrentPosition(position) {
899   var oldPos = deepCopy(CURRENT_POSITION);
900   var newPos = deepCopy(position);
901   var oldFen = objToFen(oldPos);
902   var newFen = objToFen(newPos);
903
904   // do nothing if no change in position
905   if (oldFen === newFen) return;
906
907   // run their onChange function
908   if (cfg.hasOwnProperty('onChange') === true &&
909     typeof cfg.onChange === 'function') {
910     cfg.onChange(oldPos, newPos);
911   }
912
913   // update state
914   CURRENT_POSITION = position;
915 }
916
917 function isXYOnSquare(x, y) {
918   for (var i in SQUARE_ELS_OFFSETS) {
919     if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue;
920
921     var s = SQUARE_ELS_OFFSETS[i];
922     if (x >= s.left && x < s.left + SQUARE_SIZE &&
923         y >= s.top && y < s.top + SQUARE_SIZE) {
924       return i;
925     }
926   }
927
928   return 'offboard';
929 }
930
931 // records the XY coords of every square into memory
932 function captureSquareOffsets() {
933   SQUARE_ELS_OFFSETS = {};
934
935   for (var i in SQUARE_ELS_IDS) {
936     if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue;
937
938     SQUARE_ELS_OFFSETS[i] = offset(document.getElementById(SQUARE_ELS_IDS[i]));
939   }
940 }
941
942 function removeSquareHighlights() {
943   boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
944     piece.classList.remove(CSS.highlight1);
945     piece.classList.remove(CSS.highlight2);
946   });
947 }
948
949 function snapbackDraggedPiece() {
950   removeSquareHighlights();
951
952   // animation complete
953   function complete() {
954     drawPositionInstant();
955     draggedPieceEl.style.display = 'none';
956
957     // run their onSnapbackEnd function
958     if (cfg.hasOwnProperty('onSnapbackEnd') === true &&
959       typeof cfg.onSnapbackEnd === 'function') {
960       cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
961         deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
962     }
963   }
964
965   // get source square position
966   var sourceSquarePosition =
967     offset(document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]));
968
969   // animate the piece to the target square
970   draggedPieceEl.addEventListener('transitionend', complete, {once: true});
971   requestAnimationFrame(() => {
972     draggedPieceEl.style.transitionProperty = 'top, left';
973     draggedPieceEl.style.transitionDuration = cfg.snapbackSpeed + 'ms';
974     draggedPieceEl.style.top = sourceSquarePosition.top + 'px';
975     draggedPieceEl.style.left = sourceSquarePosition.left + 'px';
976   });
977
978   // set state
979   DRAGGING_A_PIECE = false;
980 }
981
982 function trashDraggedPiece() {
983   removeSquareHighlights();
984
985   // remove the source piece
986   var newPosition = deepCopy(CURRENT_POSITION);
987   delete newPosition[DRAGGED_PIECE_SOURCE];
988   setCurrentPosition(newPosition);
989
990   // redraw the position
991   drawPositionInstant();
992
993   // hide the dragged piece
994   // FIXME: support this for non-jquery
995   //$(draggedPieceEl).fadeOut(cfg.trashSpeed);
996
997   // set state
998   DRAGGING_A_PIECE = false;
999 }
1000
1001 function dropDraggedPieceOnSquare(square) {
1002   removeSquareHighlights();
1003
1004   // update position
1005   var newPosition = deepCopy(CURRENT_POSITION);
1006   delete newPosition[DRAGGED_PIECE_SOURCE];
1007   newPosition[square] = DRAGGED_PIECE;
1008   setCurrentPosition(newPosition);
1009
1010   // get target square information
1011   var targetSquarePosition = offset(document.getElementById(SQUARE_ELS_IDS[square]));
1012
1013   // animation complete
1014   var complete = function() {
1015     drawPositionInstant();
1016     draggedPieceEl.style.display = 'none';
1017
1018     // execute their onSnapEnd function
1019     if (cfg.hasOwnProperty('onSnapEnd') === true &&
1020       typeof cfg.onSnapEnd === 'function') {
1021       requestAnimationFrame(() => {  // HACK: so that we don't add event handlers from the callback...
1022         cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
1023       });
1024     }
1025   };
1026
1027   // snap the piece to the target square
1028   draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1029   requestAnimationFrame(() => {
1030     draggedPieceEl.style.transitionProperty = 'top, left';
1031     draggedPieceEl.style.transitionDuration = cfg.snapSpeed + 'ms';
1032     draggedPieceEl.style.top = targetSquarePosition.top + 'px';
1033     draggedPieceEl.style.left = targetSquarePosition.left + 'px';
1034   });
1035
1036   // set state
1037   DRAGGING_A_PIECE = false;
1038 }
1039
1040 function beginDraggingPiece(source, piece, x, y) {
1041   // run their custom onDragStart function
1042   // their custom onDragStart function can cancel drag start
1043   if (typeof cfg.onDragStart === 'function' &&
1044       cfg.onDragStart(source, piece,
1045         deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
1046     return;
1047   }
1048
1049   // set state
1050   DRAGGING_A_PIECE = true;
1051   DRAGGED_PIECE = piece;
1052   DRAGGED_PIECE_SOURCE = source;
1053   DRAGGED_PIECE_LOCATION = source;
1054
1055   // capture the x, y coords of all squares in memory
1056   captureSquareOffsets();
1057
1058   // create the dragged piece
1059   draggedPieceEl.setAttribute('src', buildPieceImgSrc(piece));
1060   draggedPieceEl.style.display = null;
1061   draggedPieceEl.style.position = 'absolute';
1062   draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1063   draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1064
1065   // highlight the source square and hide the piece
1066   let square = document.getElementById(SQUARE_ELS_IDS[source]);
1067   square.classList.add(CSS.highlight1);
1068   square.querySelector('.' + CSS.piece).style.display = 'none';
1069 }
1070
1071 function updateDraggedPiece(x, y) {
1072   // put the dragged piece over the mouse cursor
1073   draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1074   draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1075
1076   // get location
1077   var location = isXYOnSquare(x, y);
1078
1079   // do nothing if the location has not changed
1080   if (location === DRAGGED_PIECE_LOCATION) return;
1081
1082   // remove highlight from previous square
1083   if (validSquare(DRAGGED_PIECE_LOCATION) === true) {
1084     document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION])
1085       .classList.remove(CSS.highlight2);
1086   }
1087
1088   // add highlight to new square
1089   if (validSquare(location) === true) {
1090     document.getElementById(SQUARE_ELS_IDS[location]).classList.add(CSS.highlight2);
1091   }
1092
1093   // run onDragMove
1094   if (typeof cfg.onDragMove === 'function') {
1095     cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1096       DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1097       deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1098   }
1099
1100   // update state
1101   DRAGGED_PIECE_LOCATION = location;
1102 }
1103
1104 function stopDraggedPiece(location) {
1105   // determine what the action should be
1106   var action = 'drop';
1107   if (location === 'offboard' && cfg.dropOffBoard === 'snapback') {
1108     action = 'snapback';
1109   }
1110   if (location === 'offboard' && cfg.dropOffBoard === 'trash') {
1111     action = 'trash';
1112   }
1113
1114   // run their onDrop function, which can potentially change the drop action
1115   if (cfg.hasOwnProperty('onDrop') === true &&
1116     typeof cfg.onDrop === 'function') {
1117     var newPosition = deepCopy(CURRENT_POSITION);
1118
1119     // source piece was on the board and position is off the board
1120     if (validSquare(DRAGGED_PIECE_SOURCE) === true && location === 'offboard') {
1121       // remove the piece from the board
1122       delete newPosition[DRAGGED_PIECE_SOURCE];
1123     }
1124
1125     // source piece was on the board and position is on the board
1126     if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1127       validSquare(location) === true) {
1128       // move the piece
1129       delete newPosition[DRAGGED_PIECE_SOURCE];
1130       newPosition[location] = DRAGGED_PIECE;
1131     }
1132
1133     var oldPosition = deepCopy(CURRENT_POSITION);
1134
1135     var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE,
1136       newPosition, oldPosition, CURRENT_ORIENTATION);
1137     if (result === 'snapback' || result === 'trash') {
1138       action = result;
1139     }
1140   }
1141
1142   // do it!
1143   if (action === 'snapback') {
1144     snapbackDraggedPiece();
1145   }
1146   else if (action === 'trash') {
1147     trashDraggedPiece();
1148   }
1149   else if (action === 'drop') {
1150     dropDraggedPieceOnSquare(location);
1151   }
1152 }
1153
1154 //------------------------------------------------------------------------------
1155 // Public Methods
1156 //------------------------------------------------------------------------------
1157
1158 // clear the board
1159 widget.clear = function(useAnimation) {
1160   widget.position({}, useAnimation);
1161 };
1162
1163 /*
1164 // get or set config properties
1165 // TODO: write this, GitHub Issue #1
1166 widget.config = function(arg1, arg2) {
1167   // get the current config
1168   if (arguments.length === 0) {
1169     return deepCopy(cfg);
1170   }
1171 };
1172 */
1173
1174 // remove the widget from the page
1175 widget.destroy = function() {
1176   // remove markup
1177   containerEl.innerHTML = '';
1178   draggedPieceEl.remove();
1179 };
1180
1181 // shorthand method to get the current FEN
1182 widget.fen = function() {
1183   return widget.position('fen');
1184 };
1185
1186 // flip orientation
1187 widget.flip = function() {
1188   widget.orientation('flip');
1189 };
1190
1191 /*
1192 // TODO: write this, GitHub Issue #5
1193 widget.highlight = function() {
1194
1195 };
1196 */
1197
1198 // move pieces
1199 widget.move = function() {
1200   // no need to throw an error here; just do nothing
1201   if (arguments.length === 0) return;
1202
1203   var useAnimation = true;
1204
1205   // collect the moves into an object
1206   var moves = {};
1207   for (var i = 0; i < arguments.length; i++) {
1208     // any "false" to this function means no animations
1209     if (arguments[i] === false) {
1210       useAnimation = false;
1211       continue;
1212     }
1213
1214     // skip invalid arguments
1215     if (validMove(arguments[i]) !== true) {
1216       error(2826, 'Invalid move passed to the move method.', arguments[i]);
1217       continue;
1218     }
1219
1220     var tmp = arguments[i].split('-');
1221     moves[tmp[0]] = tmp[1];
1222   }
1223
1224   // calculate position from moves
1225   var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1226
1227   // update the board
1228   widget.position(newPos, useAnimation);
1229
1230   // return the new position object
1231   return newPos;
1232 };
1233
1234 widget.orientation = function(arg) {
1235   // no arguments, return the current orientation
1236   if (arguments.length === 0) {
1237     return CURRENT_ORIENTATION;
1238   }
1239
1240   // set to white or black
1241   if (arg === 'white' || arg === 'black') {
1242     CURRENT_ORIENTATION = arg;
1243     drawBoard();
1244     return;
1245   }
1246
1247   // flip orientation
1248   if (arg === 'flip') {
1249     CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1250     drawBoard();
1251     return;
1252   }
1253
1254   error(5482, 'Invalid value passed to the orientation method.', arg);
1255 };
1256
1257 /**
1258  * @param {!string|!Object} position
1259  * @param {boolean=} useAnimation
1260  */
1261 widget.position = function(position, useAnimation) {
1262   // no arguments, return the current position
1263   if (arguments.length === 0) {
1264     return deepCopy(CURRENT_POSITION);
1265   }
1266
1267   // get position as FEN
1268   if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1269     return objToFen(CURRENT_POSITION);
1270   }
1271
1272   // default for useAnimations is true
1273   if (useAnimation !== false) {
1274     useAnimation = true;
1275   }
1276
1277   // start position
1278   if (typeof position === 'string' && position.toLowerCase() === 'start') {
1279     position = deepCopy(START_POSITION);
1280   }
1281
1282   // convert FEN to position object
1283   if (validFen(position) === true) {
1284     position = fenToObj(position);
1285   }
1286
1287   // validate position object
1288   if (validPositionObject(position) !== true) {
1289     error(6482, 'Invalid value passed to the position method.', position);
1290     return;
1291   }
1292
1293   if (useAnimation === true) {
1294     // start the animations
1295     doAnimations(calculateAnimations(CURRENT_POSITION, position),
1296       CURRENT_POSITION, position);
1297
1298     // set the new position
1299     setCurrentPosition(position);
1300   }
1301   // instant update
1302   else {
1303     setCurrentPosition(position);
1304     drawPositionInstant();
1305   }
1306 };
1307
1308 widget.resize = function() {
1309   // calulate the new square size
1310   SQUARE_SIZE = calculateSquareSize();
1311
1312   // set board width
1313   boardEl.style.width = (SQUARE_SIZE * 8) + 'px';
1314
1315   // set drag piece size
1316   if (draggedPieceEl !== null) {
1317     draggedPieceEl.style.height = SQUARE_SIZE + 'px';
1318     draggedPieceEl.style.width = SQUARE_SIZE + 'px';
1319   }
1320
1321   // redraw the board
1322   drawBoard();
1323 };
1324
1325 // set the starting position
1326 widget.start = function(useAnimation) {
1327   widget.position('start', useAnimation);
1328 };
1329
1330 //------------------------------------------------------------------------------
1331 // Browser Events
1332 //------------------------------------------------------------------------------
1333
1334 function isTouchDevice() {
1335   return ('ontouchstart' in document.documentElement);
1336 }
1337
1338 function mousedownSquare(e) {
1339   let target = e.target.closest('.' + CSS.square);
1340   if (!target) {
1341     return;
1342   }
1343
1344   // do nothing if we're not draggable
1345   if (cfg.draggable !== true) return;
1346
1347   var square = target.getAttribute('data-square');
1348
1349   // no piece on this square
1350   if (validSquare(square) !== true ||
1351       CURRENT_POSITION.hasOwnProperty(square) !== true) {
1352     return;
1353   }
1354
1355   beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1356 }
1357
1358 function touchstartSquare(e) {
1359   let target = e.target.closest('.' + CSS.square);
1360   if (!target) {
1361     return;
1362   }
1363
1364   // do nothing if we're not draggable
1365   if (cfg.draggable !== true) return;
1366
1367   var square = target.getAttribute('data-square');
1368
1369   // no piece on this square
1370   if (validSquare(square) !== true ||
1371       CURRENT_POSITION.hasOwnProperty(square) !== true) {
1372     return;
1373   }
1374
1375   beginDraggingPiece(square, CURRENT_POSITION[square],
1376     e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1377 }
1378
1379 function mousemoveWindow(e) {
1380   // do nothing if we are not dragging a piece
1381   if (DRAGGING_A_PIECE !== true) return;
1382
1383   updateDraggedPiece(e.pageX, e.pageY);
1384 }
1385
1386 function touchmoveWindow(e) {
1387   // do nothing if we are not dragging a piece
1388   if (DRAGGING_A_PIECE !== true) return;
1389
1390   // prevent screen from scrolling
1391   e.preventDefault();
1392
1393   updateDraggedPiece(e.changedTouches[0].pageX,
1394     e.changedTouches[0].pageY);
1395 }
1396
1397 function mouseupWindow(e) {
1398   // do nothing if we are not dragging a piece
1399   if (DRAGGING_A_PIECE !== true) return;
1400
1401   // get the location
1402   var location = isXYOnSquare(e.pageX, e.pageY);
1403
1404   stopDraggedPiece(location);
1405 }
1406
1407 function touchendWindow(e) {
1408   // do nothing if we are not dragging a piece
1409   if (DRAGGING_A_PIECE !== true) return;
1410
1411   // get the location
1412   var location = isXYOnSquare(e.changedTouches[0].pageX,
1413     e.changedTouches[0].pageY);
1414
1415   stopDraggedPiece(location);
1416 }
1417
1418 function mouseenterSquare(e) {
1419   let target = e.target.closest('.' + CSS.square);
1420   if (!target) {
1421     return;
1422   }
1423
1424   // do not fire this event if we are dragging a piece
1425   // NOTE: this should never happen, but it's a safeguard
1426   if (DRAGGING_A_PIECE !== false) return;
1427
1428   if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1429     typeof cfg.onMouseoverSquare !== 'function') return;
1430
1431   // get the square
1432   var square = target.getAttribute('data-square');
1433
1434   // NOTE: this should never happen; defensive
1435   if (validSquare(square) !== true) return;
1436
1437   // get the piece on this square
1438   var piece = false;
1439   if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1440     piece = CURRENT_POSITION[square];
1441   }
1442
1443   // execute their function
1444   cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1445     CURRENT_ORIENTATION);
1446 }
1447
1448 function mouseleaveSquare(e) {
1449   let target = e.target.closest('.' + CSS.square);
1450   if (!target) {
1451     return;
1452   }
1453
1454   // do not fire this event if we are dragging a piece
1455   // NOTE: this should never happen, but it's a safeguard
1456   if (DRAGGING_A_PIECE !== false) return;
1457
1458   if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1459     typeof cfg.onMouseoutSquare !== 'function') return;
1460
1461   // get the square
1462   var square = target.getAttribute('data-square');
1463
1464   // NOTE: this should never happen; defensive
1465   if (validSquare(square) !== true) return;
1466
1467   // get the piece on this square
1468   var piece = false;
1469   if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1470     piece = CURRENT_POSITION[square];
1471   }
1472
1473   // execute their function
1474   cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1475     CURRENT_ORIENTATION);
1476 }
1477
1478 //------------------------------------------------------------------------------
1479 // Initialization
1480 //------------------------------------------------------------------------------
1481
1482 function addEvents() {
1483   // prevent browser "image drag"
1484   let stopDefault = (e) => {
1485     if (e.target.matches('.' + CSS.piece)) {
1486       e.preventDefault();
1487     }
1488   };
1489   document.body.addEventListener('mousedown', stopDefault);
1490   document.body.addEventListener('mousemove', stopDefault);
1491
1492   // mouse drag pieces
1493   boardEl.addEventListener('mousedown', mousedownSquare);
1494
1495   // mouse enter / leave square
1496   boardEl.addEventListener('mouseenter', mouseenterSquare);
1497   boardEl.addEventListener('mouseleave', mouseleaveSquare);
1498
1499   window.addEventListener('mousemove', mousemoveWindow);
1500   window.addEventListener('mouseup', mouseupWindow);
1501
1502   // touch drag pieces
1503   if (isTouchDevice() === true) {
1504     boardEl.addEventListener('touchstart', touchstartSquare);
1505     window.addEventListener('touchmove', touchmoveWindow);
1506     window.addEventListener('touchend', touchendWindow);
1507   }
1508 }
1509
1510 function initDom() {
1511   // build board and save it in memory
1512   containerEl.innerHTML = buildBoardContainer();
1513   boardEl = containerEl.querySelector('.' + CSS.board);
1514
1515   // create the drag piece
1516   var draggedPieceId = createId();
1517   document.body.append(buildPiece('wP', true, draggedPieceId));
1518   draggedPieceEl = document.getElementById(draggedPieceId);
1519
1520   // get the border size
1521   BOARD_BORDER_SIZE = parseInt(boardEl.style.borderLeftWidth, 10);
1522
1523   // set the size and draw the board
1524   widget.resize();
1525 }
1526
1527 function init() {
1528   if (checkDeps() !== true ||
1529       expandConfig() !== true) return;
1530
1531   // create unique IDs for all the elements we will create
1532   createElIds();
1533
1534   initDom();
1535   addEvents();
1536 }
1537
1538 // go time
1539 init();
1540
1541 // return the widget object
1542 return widget;
1543
1544 }; // end window.ChessBoard
1545
1546 // expose util functions
1547 window.ChessBoard.fenToObj = fenToObj;
1548 window.ChessBoard.objToFen = objToFen;
1549
1550 })(); // end anonymous wrapper