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