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