]> git.sesse.net Git - remoteglot/blob - www/js/chessboard-0.3.0.js
Fix touch events post-jQuery.
[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(piece, onFinish) {
772   piece.style.opacity = 0;
773   piece.style.display = null;
774   piece.addEventListener('transitionend', onFinish, {once: true});
775   requestAnimationFrame(() => {
776     piece.style.transitionProperty = 'opacity';
777     piece.style.transitionDuration = cfg.appearSpeed + 'ms';
778     piece.style.opacity = 1;
779   });
780 }
781
782 function fadeOut(piece, onFinish) {
783   piece.style.opacity = 1;
784   piece.style.display = null;
785   piece.addEventListener('transitionend', onFinish, {once: true});
786   requestAnimationFrame(() => {
787     piece.style.transitionProperty = 'opacity';
788     piece.style.transitionDuration = cfg.trashSpeed + 'ms';
789     piece.style.opacity = 0;
790   });
791 }
792
793 // execute an array of animations
794 function doAnimations(a, oldPos, newPos) {
795   ANIMATION_HAPPENING = true;
796
797   var numFinished = 0;
798   function onFinish(e) {
799     if (e && e.target) {
800       e.target.transitionProperty = null;
801     }
802
803     numFinished++;
804
805     // exit if all the animations aren't finished
806     if (numFinished !== a.length) return;
807
808     drawPositionInstant();
809     ANIMATION_HAPPENING = false;
810
811     // run their onMoveEnd function
812     if (cfg.hasOwnProperty('onMoveEnd') === true &&
813       typeof cfg.onMoveEnd === 'function') {
814       cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
815     }
816   }
817
818   requestAnimationFrame(() => {  // Firefox workaround.
819     for (var i = 0; i < a.length; i++) {
820       // clear a piece
821       if (a[i].type === 'clear') {
822         document.getElementById(SQUARE_ELS_IDS[a[i].square]).querySelectorAll('.' + CSS.piece).forEach(
823           (piece) => fadeOut(piece, onFinish)
824         );
825       }
826
827       // add a piece (no spare pieces)
828       if (a[i].type === 'add' && cfg.sparePieces !== true) {
829         let square = document.getElementById(SQUARE_ELS_IDS[a[i].square]);
830         square.append(buildPiece(a[i].piece, true));
831         let piece = square.querySelector('.' + CSS.piece);
832         fadeIn(piece, onFinish);
833       }
834
835       // add a piece from a spare piece
836       if (a[i].type === 'add' && cfg.sparePieces === true) {
837         animateSparePieceToSquare(a[i].piece, a[i].square, onFinish);
838       }
839
840       // move a piece
841       if (a[i].type === 'move') {
842         animateSquareToSquare(a[i].source, a[i].destination, a[i].piece,
843           onFinish);
844       }
845     }
846   });
847 }
848
849 // returns the distance between two squares
850 function squareDistance(s1, s2) {
851   s1 = s1.split('');
852   var s1x = COLUMNS.indexOf(s1[0]) + 1;
853   var s1y = parseInt(s1[1], 10);
854
855   s2 = s2.split('');
856   var s2x = COLUMNS.indexOf(s2[0]) + 1;
857   var s2y = parseInt(s2[1], 10);
858
859   var xDelta = Math.abs(s1x - s2x);
860   var yDelta = Math.abs(s1y - s2y);
861
862   if (xDelta >= yDelta) return xDelta;
863   return yDelta;
864 }
865
866 // returns an array of closest squares from square
867 function createRadius(square) {
868   var squares = [];
869
870   // calculate distance of all squares
871   for (var i = 0; i < 8; i++) {
872     for (var j = 0; j < 8; j++) {
873       var s = COLUMNS[i] + (j + 1);
874
875       // skip the square we're starting from
876       if (square === s) continue;
877
878       squares.push({
879         square: s,
880         distance: squareDistance(square, s)
881       });
882     }
883   }
884
885   // sort by distance
886   squares.sort(function(a, b) {
887     return a.distance - b.distance;
888   });
889
890   // just return the square code
891   var squares2 = [];
892   for (var i = 0; i < squares.length; i++) {
893     squares2.push(squares[i].square);
894   }
895
896   return squares2;
897 }
898
899 // returns the square of the closest instance of piece
900 // returns false if no instance of piece is found in position
901 function findClosestPiece(position, piece, square) {
902   // create array of closest squares from square
903   var closestSquares = createRadius(square);
904
905   // search through the position in order of distance for the piece
906   for (var i = 0; i < closestSquares.length; i++) {
907     var s = closestSquares[i];
908
909     if (position.hasOwnProperty(s) === true && position[s] === piece) {
910       return s;
911     }
912   }
913
914   return false;
915 }
916
917 // calculate an array of animations that need to happen in order to get
918 // from pos1 to pos2
919 function calculateAnimations(pos1, pos2) {
920   // make copies of both
921   pos1 = deepCopy(pos1);
922   pos2 = deepCopy(pos2);
923
924   var animations = [];
925   var squaresMovedTo = {};
926
927   // remove pieces that are the same in both positions
928   for (var i in pos2) {
929     if (pos2.hasOwnProperty(i) !== true) continue;
930
931     if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
932       delete pos1[i];
933       delete pos2[i];
934     }
935   }
936
937   // find all the "move" animations
938   for (var i in pos2) {
939     if (pos2.hasOwnProperty(i) !== true) continue;
940
941     var closestPiece = findClosestPiece(pos1, pos2[i], i);
942     if (closestPiece !== false) {
943       animations.push({
944         type: 'move',
945         source: closestPiece,
946         destination: i,
947         piece: pos2[i]
948       });
949
950       delete pos1[closestPiece];
951       delete pos2[i];
952       squaresMovedTo[i] = true;
953     }
954   }
955
956   // add pieces to pos2
957   for (var i in pos2) {
958     if (pos2.hasOwnProperty(i) !== true) continue;
959
960     animations.push({
961       type: 'add',
962       square: i,
963       piece: pos2[i]
964     })
965
966     delete pos2[i];
967   }
968
969   // clear pieces from pos1
970   for (var i in pos1) {
971     if (pos1.hasOwnProperty(i) !== true) continue;
972
973     // do not clear a piece if it is on a square that is the result
974     // of a "move", ie: a piece capture
975     if (squaresMovedTo.hasOwnProperty(i) === true) continue;
976
977     animations.push({
978       type: 'clear',
979       square: i,
980       piece: pos1[i]
981     });
982
983     delete pos1[i];
984   }
985
986   return animations;
987 }
988
989 //------------------------------------------------------------------------------
990 // Control Flow
991 //------------------------------------------------------------------------------
992
993 function drawPositionInstant() {
994   // clear the board
995   boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
996
997   // add the pieces
998   for (var i in CURRENT_POSITION) {
999     if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue;
1000
1001     document.getElementById(SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i]));
1002   }
1003 }
1004
1005 function drawBoard() {
1006   boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
1007   drawPositionInstant();
1008
1009   if (cfg.sparePieces === true) {
1010     if (CURRENT_ORIENTATION === 'white') {
1011       sparePiecesTopEl.innerHTML = buildSparePieces('black');
1012       sparePiecesBottomEl.innerHTML = buildSparePieces('white');
1013     }
1014     else {
1015       sparePiecesTopEl.innerHTML = buildSparePieces('white');
1016       sparePiecesBottomEl.innerHTML = buildSparePieces('black');
1017     }
1018   }
1019 }
1020
1021 // given a position and a set of moves, return a new position
1022 // with the moves executed
1023 function calculatePositionFromMoves(position, moves) {
1024   position = deepCopy(position);
1025
1026   for (var i in moves) {
1027     if (moves.hasOwnProperty(i) !== true) continue;
1028
1029     // skip the move if the position doesn't have a piece on the source square
1030     if (position.hasOwnProperty(i) !== true) continue;
1031
1032     var piece = position[i];
1033     delete position[i];
1034     position[moves[i]] = piece;
1035   }
1036
1037   return position;
1038 }
1039
1040 function setCurrentPosition(position) {
1041   var oldPos = deepCopy(CURRENT_POSITION);
1042   var newPos = deepCopy(position);
1043   var oldFen = objToFen(oldPos);
1044   var newFen = objToFen(newPos);
1045
1046   // do nothing if no change in position
1047   if (oldFen === newFen) return;
1048
1049   // run their onChange function
1050   if (cfg.hasOwnProperty('onChange') === true &&
1051     typeof cfg.onChange === 'function') {
1052     cfg.onChange(oldPos, newPos);
1053   }
1054
1055   // update state
1056   CURRENT_POSITION = position;
1057 }
1058
1059 function isXYOnSquare(x, y) {
1060   for (var i in SQUARE_ELS_OFFSETS) {
1061     if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue;
1062
1063     var s = SQUARE_ELS_OFFSETS[i];
1064     if (x >= s.left && x < s.left + SQUARE_SIZE &&
1065         y >= s.top && y < s.top + SQUARE_SIZE) {
1066       return i;
1067     }
1068   }
1069
1070   return 'offboard';
1071 }
1072
1073 // records the XY coords of every square into memory
1074 function captureSquareOffsets() {
1075   SQUARE_ELS_OFFSETS = {};
1076
1077   for (var i in SQUARE_ELS_IDS) {
1078     if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue;
1079
1080     SQUARE_ELS_OFFSETS[i] = offset(document.getElementById(SQUARE_ELS_IDS[i]));
1081   }
1082 }
1083
1084 function removeSquareHighlights() {
1085   boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
1086     piece.classList.remove(CSS.highlight1);
1087     piece.classList.remove(CSS.highlight2);
1088   });
1089 }
1090
1091 function snapbackDraggedPiece() {
1092   // there is no "snapback" for spare pieces
1093   if (DRAGGED_PIECE_SOURCE === 'spare') {
1094     trashDraggedPiece();
1095     return;
1096   }
1097
1098   removeSquareHighlights();
1099
1100   // animation complete
1101   function complete() {
1102     drawPositionInstant();
1103     draggedPieceEl.style.display = 'none';
1104
1105     // run their onSnapbackEnd function
1106     if (cfg.hasOwnProperty('onSnapbackEnd') === true &&
1107       typeof cfg.onSnapbackEnd === 'function') {
1108       cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
1109         deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1110     }
1111   }
1112
1113   // get source square position
1114   var sourceSquarePosition =
1115     offset(document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]));
1116
1117   // animate the piece to the target square
1118   draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1119   requestAnimationFrame(() => {
1120     draggedPieceEl.style.transitionProperty = 'top, left';
1121     draggedPieceEl.style.transitionDuration = cfg.snapbackSpeed + 'ms';
1122     draggedPieceEl.style.top = sourceSquarePosition.top + 'px';
1123     draggedPieceEl.style.left = sourceSquarePosition.left + 'px';
1124   });
1125
1126   // set state
1127   DRAGGING_A_PIECE = false;
1128 }
1129
1130 function trashDraggedPiece() {
1131   removeSquareHighlights();
1132
1133   // remove the source piece
1134   var newPosition = deepCopy(CURRENT_POSITION);
1135   delete newPosition[DRAGGED_PIECE_SOURCE];
1136   setCurrentPosition(newPosition);
1137
1138   // redraw the position
1139   drawPositionInstant();
1140
1141   // hide the dragged piece
1142   // FIXME: support this for non-jquery
1143   //$(draggedPieceEl).fadeOut(cfg.trashSpeed);
1144
1145   // set state
1146   DRAGGING_A_PIECE = false;
1147 }
1148
1149 function dropDraggedPieceOnSquare(square) {
1150   removeSquareHighlights();
1151
1152   // update position
1153   var newPosition = deepCopy(CURRENT_POSITION);
1154   delete newPosition[DRAGGED_PIECE_SOURCE];
1155   newPosition[square] = DRAGGED_PIECE;
1156   setCurrentPosition(newPosition);
1157
1158   // get target square information
1159   var targetSquarePosition = offset(document.getElementById(SQUARE_ELS_IDS[square]));
1160
1161   // animation complete
1162   var complete = function() {
1163     drawPositionInstant();
1164     draggedPieceEl.style.display = 'none';
1165
1166     // execute their onSnapEnd function
1167     if (cfg.hasOwnProperty('onSnapEnd') === true &&
1168       typeof cfg.onSnapEnd === 'function') {
1169       requestAnimationFrame(() => {  // HACK: so that we don't add event handlers from the callback...
1170         cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
1171       });
1172     }
1173   };
1174
1175   // snap the piece to the target square
1176   draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1177   requestAnimationFrame(() => {
1178     draggedPieceEl.style.transitionProperty = 'top, left';
1179     draggedPieceEl.style.transitionDuration = cfg.snapSpeed + 'ms';
1180     draggedPieceEl.style.top = targetSquarePosition.top + 'px';
1181     draggedPieceEl.style.left = targetSquarePosition.left + 'px';
1182   });
1183
1184   // set state
1185   DRAGGING_A_PIECE = false;
1186 }
1187
1188 function beginDraggingPiece(source, piece, x, y) {
1189   // run their custom onDragStart function
1190   // their custom onDragStart function can cancel drag start
1191   if (typeof cfg.onDragStart === 'function' &&
1192       cfg.onDragStart(source, piece,
1193         deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
1194     return;
1195   }
1196
1197   // set state
1198   DRAGGING_A_PIECE = true;
1199   DRAGGED_PIECE = piece;
1200   DRAGGED_PIECE_SOURCE = source;
1201
1202   // if the piece came from spare pieces, location is offboard
1203   if (source === 'spare') {
1204     DRAGGED_PIECE_LOCATION = 'offboard';
1205   }
1206   else {
1207     DRAGGED_PIECE_LOCATION = source;
1208   }
1209
1210   // capture the x, y coords of all squares in memory
1211   captureSquareOffsets();
1212
1213   // create the dragged piece
1214   draggedPieceEl.setAttribute('src', buildPieceImgSrc(piece));
1215   draggedPieceEl.style.display = null;
1216   draggedPieceEl.style.position = 'absolute';
1217   draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1218   draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1219
1220   if (source !== 'spare') {
1221     // highlight the source square and hide the piece
1222     let square = document.getElementById(SQUARE_ELS_IDS[source]);
1223     square.classList.add(CSS.highlight1);
1224     square.querySelector('.' + CSS.piece).style.display = 'none';
1225   }
1226 }
1227
1228 function updateDraggedPiece(x, y) {
1229   // put the dragged piece over the mouse cursor
1230   draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1231   draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1232
1233   // get location
1234   var location = isXYOnSquare(x, y);
1235
1236   // do nothing if the location has not changed
1237   if (location === DRAGGED_PIECE_LOCATION) return;
1238
1239   // remove highlight from previous square
1240   if (validSquare(DRAGGED_PIECE_LOCATION) === true) {
1241     document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION])
1242       .classList.remove(CSS.highlight2);
1243   }
1244
1245   // add highlight to new square
1246   if (validSquare(location) === true) {
1247     document.getElementById(SQUARE_ELS_IDS[location]).classList.add(CSS.highlight2);
1248   }
1249
1250   // run onDragMove
1251   if (typeof cfg.onDragMove === 'function') {
1252     cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1253       DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1254       deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1255   }
1256
1257   // update state
1258   DRAGGED_PIECE_LOCATION = location;
1259 }
1260
1261 function stopDraggedPiece(location) {
1262   // determine what the action should be
1263   var action = 'drop';
1264   if (location === 'offboard' && cfg.dropOffBoard === 'snapback') {
1265     action = 'snapback';
1266   }
1267   if (location === 'offboard' && cfg.dropOffBoard === 'trash') {
1268     action = 'trash';
1269   }
1270
1271   // run their onDrop function, which can potentially change the drop action
1272   if (cfg.hasOwnProperty('onDrop') === true &&
1273     typeof cfg.onDrop === 'function') {
1274     var newPosition = deepCopy(CURRENT_POSITION);
1275
1276     // source piece is a spare piece and position is off the board
1277     //if (DRAGGED_PIECE_SOURCE === 'spare' && location === 'offboard') {...}
1278     // position has not changed; do nothing
1279
1280     // source piece is a spare piece and position is on the board
1281     if (DRAGGED_PIECE_SOURCE === 'spare' && validSquare(location) === true) {
1282       // add the piece to the board
1283       newPosition[location] = DRAGGED_PIECE;
1284     }
1285
1286     // source piece was on the board and position is off the board
1287     if (validSquare(DRAGGED_PIECE_SOURCE) === true && location === 'offboard') {
1288       // remove the piece from the board
1289       delete newPosition[DRAGGED_PIECE_SOURCE];
1290     }
1291
1292     // source piece was on the board and position is on the board
1293     if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1294       validSquare(location) === true) {
1295       // move the piece
1296       delete newPosition[DRAGGED_PIECE_SOURCE];
1297       newPosition[location] = DRAGGED_PIECE;
1298     }
1299
1300     var oldPosition = deepCopy(CURRENT_POSITION);
1301
1302     var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE,
1303       newPosition, oldPosition, CURRENT_ORIENTATION);
1304     if (result === 'snapback' || result === 'trash') {
1305       action = result;
1306     }
1307   }
1308
1309   // do it!
1310   if (action === 'snapback') {
1311     snapbackDraggedPiece();
1312   }
1313   else if (action === 'trash') {
1314     trashDraggedPiece();
1315   }
1316   else if (action === 'drop') {
1317     dropDraggedPieceOnSquare(location);
1318   }
1319 }
1320
1321 //------------------------------------------------------------------------------
1322 // Public Methods
1323 //------------------------------------------------------------------------------
1324
1325 // clear the board
1326 widget.clear = function(useAnimation) {
1327   widget.position({}, useAnimation);
1328 };
1329
1330 /*
1331 // get or set config properties
1332 // TODO: write this, GitHub Issue #1
1333 widget.config = function(arg1, arg2) {
1334   // get the current config
1335   if (arguments.length === 0) {
1336     return deepCopy(cfg);
1337   }
1338 };
1339 */
1340
1341 // remove the widget from the page
1342 widget.destroy = function() {
1343   // remove markup
1344   containerEl.innerHTML = '';
1345   draggedPieceEl.remove();
1346 };
1347
1348 // shorthand method to get the current FEN
1349 widget.fen = function() {
1350   return widget.position('fen');
1351 };
1352
1353 // flip orientation
1354 widget.flip = function() {
1355   widget.orientation('flip');
1356 };
1357
1358 /*
1359 // TODO: write this, GitHub Issue #5
1360 widget.highlight = function() {
1361
1362 };
1363 */
1364
1365 // move pieces
1366 widget.move = function() {
1367   // no need to throw an error here; just do nothing
1368   if (arguments.length === 0) return;
1369
1370   var useAnimation = true;
1371
1372   // collect the moves into an object
1373   var moves = {};
1374   for (var i = 0; i < arguments.length; i++) {
1375     // any "false" to this function means no animations
1376     if (arguments[i] === false) {
1377       useAnimation = false;
1378       continue;
1379     }
1380
1381     // skip invalid arguments
1382     if (validMove(arguments[i]) !== true) {
1383       error(2826, 'Invalid move passed to the move method.', arguments[i]);
1384       continue;
1385     }
1386
1387     var tmp = arguments[i].split('-');
1388     moves[tmp[0]] = tmp[1];
1389   }
1390
1391   // calculate position from moves
1392   var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1393
1394   // update the board
1395   widget.position(newPos, useAnimation);
1396
1397   // return the new position object
1398   return newPos;
1399 };
1400
1401 widget.orientation = function(arg) {
1402   // no arguments, return the current orientation
1403   if (arguments.length === 0) {
1404     return CURRENT_ORIENTATION;
1405   }
1406
1407   // set to white or black
1408   if (arg === 'white' || arg === 'black') {
1409     CURRENT_ORIENTATION = arg;
1410     drawBoard();
1411     return;
1412   }
1413
1414   // flip orientation
1415   if (arg === 'flip') {
1416     CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1417     drawBoard();
1418     return;
1419   }
1420
1421   error(5482, 'Invalid value passed to the orientation method.', arg);
1422 };
1423
1424 /**
1425  * @param {!string|!Object} position
1426  * @param {boolean=} useAnimation
1427  */
1428 widget.position = function(position, useAnimation) {
1429   // no arguments, return the current position
1430   if (arguments.length === 0) {
1431     return deepCopy(CURRENT_POSITION);
1432   }
1433
1434   // get position as FEN
1435   if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1436     return objToFen(CURRENT_POSITION);
1437   }
1438
1439   // default for useAnimations is true
1440   if (useAnimation !== false) {
1441     useAnimation = true;
1442   }
1443
1444   // start position
1445   if (typeof position === 'string' && position.toLowerCase() === 'start') {
1446     position = deepCopy(START_POSITION);
1447   }
1448
1449   // convert FEN to position object
1450   if (validFen(position) === true) {
1451     position = fenToObj(position);
1452   }
1453
1454   // validate position object
1455   if (validPositionObject(position) !== true) {
1456     error(6482, 'Invalid value passed to the position method.', position);
1457     return;
1458   }
1459
1460   if (useAnimation === true) {
1461     // start the animations
1462     doAnimations(calculateAnimations(CURRENT_POSITION, position),
1463       CURRENT_POSITION, position);
1464
1465     // set the new position
1466     setCurrentPosition(position);
1467   }
1468   // instant update
1469   else {
1470     setCurrentPosition(position);
1471     drawPositionInstant();
1472   }
1473 };
1474
1475 widget.resize = function() {
1476   // calulate the new square size
1477   SQUARE_SIZE = calculateSquareSize();
1478
1479   // set board width
1480   boardEl.style.width = (SQUARE_SIZE * 8) + 'px';
1481
1482   // set drag piece size
1483   if (draggedPieceEl !== null) {
1484     draggedPieceEl.style.height = SQUARE_SIZE + 'px';
1485     draggedPieceEl.style.width = SQUARE_SIZE + 'px';
1486   }
1487
1488   // spare pieces
1489   if (cfg.sparePieces === true) {
1490     containerEl.querySelector('.' + CSS.sparePieces)
1491       .style.paddingLeft = (SQUARE_SIZE + BOARD_BORDER_SIZE) + 'px';
1492   }
1493
1494   // redraw the board
1495   drawBoard();
1496 };
1497
1498 // set the starting position
1499 widget.start = function(useAnimation) {
1500   widget.position('start', useAnimation);
1501 };
1502
1503 //------------------------------------------------------------------------------
1504 // Browser Events
1505 //------------------------------------------------------------------------------
1506
1507 function isTouchDevice() {
1508   return ('ontouchstart' in document.documentElement);
1509 }
1510
1511 function mousedownSquare(e) {
1512   let target = e.target.closest('.' + CSS.square);
1513   if (!target) {
1514     return;
1515   }
1516
1517   // do nothing if we're not draggable
1518   if (cfg.draggable !== true) return;
1519
1520   var square = target.getAttribute('data-square');
1521
1522   // no piece on this square
1523   if (validSquare(square) !== true ||
1524       CURRENT_POSITION.hasOwnProperty(square) !== true) {
1525     return;
1526   }
1527
1528   beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1529 }
1530
1531 function touchstartSquare(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],
1549     e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1550 }
1551
1552 function mousedownSparePiece(e) {
1553   if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1554     return;
1555   }
1556
1557   // do nothing if sparePieces is not enabled
1558   if (cfg.sparePieces !== true) return;
1559
1560   var piece = e.target.getAttribute('data-piece');
1561
1562   beginDraggingPiece('spare', piece, e.pageX, e.pageY);
1563 }
1564
1565 function touchstartSparePiece(e) {
1566   if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1567     return;
1568   }
1569
1570   // do nothing if sparePieces is not enabled
1571   if (cfg.sparePieces !== true) return;
1572
1573   var piece = e.target.getAttribute('data-piece');
1574
1575   beginDraggingPiece('spare', piece,
1576     e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1577 }
1578
1579 function mousemoveWindow(e) {
1580   // do nothing if we are not dragging a piece
1581   if (DRAGGING_A_PIECE !== true) return;
1582
1583   updateDraggedPiece(e.pageX, e.pageY);
1584 }
1585
1586 function touchmoveWindow(e) {
1587   // do nothing if we are not dragging a piece
1588   if (DRAGGING_A_PIECE !== true) return;
1589
1590   // prevent screen from scrolling
1591   e.preventDefault();
1592
1593   updateDraggedPiece(e.changedTouches[0].pageX,
1594     e.changedTouches[0].pageY);
1595 }
1596
1597 function mouseupWindow(e) {
1598   // do nothing if we are not dragging a piece
1599   if (DRAGGING_A_PIECE !== true) return;
1600
1601   // get the location
1602   var location = isXYOnSquare(e.pageX, e.pageY);
1603
1604   stopDraggedPiece(location);
1605 }
1606
1607 function touchendWindow(e) {
1608   // do nothing if we are not dragging a piece
1609   if (DRAGGING_A_PIECE !== true) return;
1610
1611   // get the location
1612   var location = isXYOnSquare(e.changedTouches[0].pageX,
1613     e.changedTouches[0].pageY);
1614
1615   stopDraggedPiece(location);
1616 }
1617
1618 function mouseenterSquare(e) {
1619   let target = e.target.closest('.' + CSS.square);
1620   if (!target) {
1621     return;
1622   }
1623
1624   // do not fire this event if we are dragging a piece
1625   // NOTE: this should never happen, but it's a safeguard
1626   if (DRAGGING_A_PIECE !== false) return;
1627
1628   if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1629     typeof cfg.onMouseoverSquare !== 'function') return;
1630
1631   // get the square
1632   var square = target.getAttribute('data-square');
1633
1634   // NOTE: this should never happen; defensive
1635   if (validSquare(square) !== true) return;
1636
1637   // get the piece on this square
1638   var piece = false;
1639   if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1640     piece = CURRENT_POSITION[square];
1641   }
1642
1643   // execute their function
1644   cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1645     CURRENT_ORIENTATION);
1646 }
1647
1648 function mouseleaveSquare(e) {
1649   let target = e.target.closest('.' + CSS.square);
1650   if (!target) {
1651     return;
1652   }
1653
1654   // do not fire this event if we are dragging a piece
1655   // NOTE: this should never happen, but it's a safeguard
1656   if (DRAGGING_A_PIECE !== false) return;
1657
1658   if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1659     typeof cfg.onMouseoutSquare !== 'function') return;
1660
1661   // get the square
1662   var square = target.getAttribute('data-square');
1663
1664   // NOTE: this should never happen; defensive
1665   if (validSquare(square) !== true) return;
1666
1667   // get the piece on this square
1668   var piece = false;
1669   if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1670     piece = CURRENT_POSITION[square];
1671   }
1672
1673   // execute their function
1674   cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1675     CURRENT_ORIENTATION);
1676 }
1677
1678 //------------------------------------------------------------------------------
1679 // Initialization
1680 //------------------------------------------------------------------------------
1681
1682 function addEvents() {
1683   // prevent browser "image drag"
1684   let stopDefault = (e) => {
1685     if (e.target.matches('.' + CSS.piece)) {
1686       e.preventDefault();
1687     }
1688   };
1689   document.body.addEventListener('mousedown', stopDefault);
1690   document.body.addEventListener('mousemove', stopDefault);
1691
1692   // mouse drag pieces
1693   boardEl.addEventListener('mousedown', mousedownSquare);
1694   containerEl.addEventListener('mousedown', mousedownSparePiece);
1695
1696   // mouse enter / leave square
1697   boardEl.addEventListener('mouseenter', mouseenterSquare);
1698   boardEl.addEventListener('mouseleave', mouseleaveSquare);
1699
1700   window.addEventListener('mousemove', mousemoveWindow);
1701   window.addEventListener('mouseup', mouseupWindow);
1702
1703   // touch drag pieces
1704   if (isTouchDevice() === true) {
1705     boardEl.addEventListener('touchstart', touchstartSquare);
1706     containerEl.addEventListener('touchstart', touchstartSparePiece);
1707     window.addEventListener('touchmove', touchmoveWindow);
1708     window.addEventListener('touchend', touchendWindow);
1709   }
1710 }
1711
1712 function initDom() {
1713   // build board and save it in memory
1714   containerEl.innerHTML = buildBoardContainer();
1715   boardEl = containerEl.querySelector('.' + CSS.board);
1716
1717   if (cfg.sparePieces === true) {
1718     sparePiecesTopEl = containerEl.querySelector('.' + CSS.sparePiecesTop);
1719     sparePiecesBottomEl = containerEl.querySelector('.' + CSS.sparePiecesBottom);
1720   }
1721
1722   // create the drag piece
1723   var draggedPieceId = createId();
1724   document.body.append(buildPiece('wP', true, draggedPieceId));
1725   draggedPieceEl = document.getElementById(draggedPieceId);
1726
1727   // get the border size
1728   BOARD_BORDER_SIZE = parseInt(boardEl.style.borderLeftWidth, 10);
1729
1730   // set the size and draw the board
1731   widget.resize();
1732 }
1733
1734 function init() {
1735   if (checkDeps() !== true ||
1736       expandConfig() !== true) return;
1737
1738   // create unique IDs for all the elements we will create
1739   createElIds();
1740
1741   initDom();
1742   addEvents();
1743 }
1744
1745 // go time
1746 init();
1747
1748 // return the widget object
1749 return widget;
1750
1751 }; // end window.ChessBoard
1752
1753 // expose util functions
1754 window.ChessBoard.fenToObj = fenToObj;
1755 window.ChessBoard.objToFen = objToFen;
1756
1757 })(); // end anonymous wrapper