]> git.sesse.net Git - remoteglot/blob - www/js/chessboard-0.3.0.js
Handle streaming PGNs, like from Lichess (although this might break non-streaming...
[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 // execute an array of animations
554 function doAnimations(a, oldPos, newPos) {
555   let fadeout_pieces = [];
556   let fadein_pieces = [];
557   let move_pieces = [];
558   let squares_to_clear = [];
559   let squares_to_fill = {};
560   let removed_pieces = [];
561
562   for (var i = 0; i < a.length; i++) {
563     // clear a piece
564     if (a[i].type === 'clear') {
565       let square = a[i].square;
566       let piece = PIECE_ON_SQUARE[square];
567       if (piece) {
568         fadeout_pieces.push(piece);
569         squares_to_clear.push(square);
570         removed_pieces.push(piece);
571       }
572     }
573
574     // add a piece
575     if (a[i].type === 'add') {
576       let square = a[i].square;
577       let pos = findSquarePosition(square);
578       let piece = buildPiece(a[i].piece, true);
579       piece.style.left = pos.left;
580       piece.style.top = pos.top;
581       boardEl.append(piece);
582       squares_to_fill[square] = piece;
583       fadein_pieces.push(piece);
584     }
585
586     // move a piece
587     if (a[i].type === 'move') {
588       let piece = PIECE_ON_SQUARE[a[i].source];
589       move_pieces.push([piece, a[i].destination]);
590       squares_to_clear.push(a[i].source);
591       squares_to_fill[a[i].destination] = piece;
592
593       // This is O(n²), but OK.
594       let replaced_piece = PIECE_ON_SQUARE[a[i].destination];
595       if (replaced_piece && !a.some(e => e.type === 'move' && e.source === a[i].destination)) {
596         removed_pieces.push(replaced_piece);
597       }
598     }
599   }
600
601   for (const square of squares_to_clear) {
602     delete PIECE_ON_SQUARE[square];
603   }
604   for (const [square, piece] of Object.entries(squares_to_fill)) {
605     PIECE_ON_SQUARE[square] = piece;
606     piece.setAttribute('data-square', square);
607   }
608
609   var numFinished = 0;
610   function onFinish(e, opt_force) {
611     if (++numFinished === a.length) {
612       for (let piece of removed_pieces) {
613         piece.remove();
614       }
615
616       // run their onMoveEnd function
617       if (cfg.hasOwnProperty('onMoveEnd') &&
618         typeof cfg.onMoveEnd === 'function') {
619         cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
620       }
621     }
622   }
623
624   fadein_pieces.forEach((piece) => {
625     piece.style.display = null;
626     piece.style.opacity = 1;
627     piece.animate(
628       [ { opacity: 0 }, { opacity: 1 } ],
629       { duration: cfg.appearSpeed }
630     ).addEventListener('finish', onFinish);
631   });
632   fadeout_pieces.forEach((piece) => {
633     piece.style.display = null;
634     piece.style.opacity = 0;
635     piece.animate(
636       [ { opacity: 1 }, { opacity: 0 } ],
637       { duration: cfg.trashSpeed }
638     ).addEventListener('finish', onFinish);
639   });
640   for (const [piece, destination] of move_pieces) {
641     // Move it to the end of the stack, which changes the implicit z-index
642     // so that it will go on top of any pieces it's replacing.
643     piece.remove();
644     boardEl.appendChild(piece);
645
646     let destSquarePosition = findSquarePosition(destination);
647     piece.animate(
648       [
649         { top: piece.style.top, left: piece.style.left },
650         { top: destSquarePosition.top, left: destSquarePosition.left }
651       ],
652       { duration: cfg.moveSpeed }
653     ).addEventListener('finish', onFinish);
654     piece.style.top = destSquarePosition.top;
655     piece.style.left = destSquarePosition.left;
656   }
657 }
658
659 // returns the distance between two squares
660 function squareDistance(s1, s2) {
661   s1 = s1.split('');
662   var s1x = COLUMNS.indexOf(s1[0]) + 1;
663   var s1y = parseInt(s1[1], 10);
664
665   s2 = s2.split('');
666   var s2x = COLUMNS.indexOf(s2[0]) + 1;
667   var s2y = parseInt(s2[1], 10);
668
669   var xDelta = Math.abs(s1x - s2x);
670   var yDelta = Math.abs(s1y - s2y);
671
672   if (xDelta >= yDelta) return xDelta;
673   return yDelta;
674 }
675
676 // returns the square of the closest instance of piece
677 // returns false if no instance of piece is found in position
678 function findClosestPiece(position, piece, square) {
679   let best_square = false;
680   let best_dist = 1e9;
681   for (var i = 0; i < COLUMNS.length; i++) {
682     for (var j = 1; j <= 8; j++) {
683       let other_square = COLUMNS[i] + j;
684
685       if (position[other_square] === piece && square != other_square) {
686         let dist = squareDistance(square, other_square);
687         if (dist < best_dist) {
688           best_square = other_square;
689           best_dist = dist;
690         }
691       }
692     }
693   }
694
695   return best_square;
696 }
697
698 // calculate an array of animations that need to happen in order to get
699 // from pos1 to pos2
700 function calculateAnimations(pos1, pos2) {
701   // make copies of both
702   pos1 = deepCopy(pos1);
703   pos2 = deepCopy(pos2);
704
705   var animations = [];
706   var squaresMovedTo = {};
707
708   // remove pieces that are the same in both positions
709   for (var i in pos2) {
710     if (!pos2.hasOwnProperty(i)) continue;
711
712     if (pos1.hasOwnProperty(i) && pos1[i] === pos2[i]) {
713       delete pos1[i];
714       delete pos2[i];
715     }
716   }
717
718   // find all the "move" animations
719   for (var i in pos2) {
720     if (!pos2.hasOwnProperty(i)) continue;
721
722     var closestPiece = findClosestPiece(pos1, pos2[i], i);
723     if (closestPiece !== false) {
724       animations.push({
725         type: 'move',
726         source: closestPiece,
727         destination: i,
728         piece: pos2[i]
729       });
730
731       delete pos1[closestPiece];
732       delete pos2[i];
733       squaresMovedTo[i] = true;
734     }
735   }
736
737   // add pieces to pos2
738   for (var i in pos2) {
739     if (!pos2.hasOwnProperty(i)) continue;
740
741     animations.push({
742       type: 'add',
743       square: i,
744       piece: pos2[i]
745     })
746
747     delete pos2[i];
748   }
749
750   // clear pieces from pos1
751   for (var i in pos1) {
752     if (!pos1.hasOwnProperty(i)) continue;
753
754     // do not clear a piece if it is on a square that is the result
755     // of a "move", ie: a piece capture
756     if (squaresMovedTo.hasOwnProperty(i)) continue;
757
758     animations.push({
759       type: 'clear',
760       square: i,
761       piece: pos1[i]
762     });
763
764     delete pos1[i];
765   }
766
767   return animations;
768 }
769
770 //------------------------------------------------------------------------------
771 // Control Flow
772 //------------------------------------------------------------------------------
773
774 function drawPositionInstant() {
775   // clear the board
776   boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
777
778   // add the pieces
779   for (const [square, piece] of Object.entries(CURRENT_POSITION)) {
780     let pos = findSquarePosition(square);
781     let pieceEl = buildPiece(piece);
782     pieceEl.style.left = pos.left;
783     pieceEl.style.top = pos.top;
784     pieceEl.setAttribute('data-square', square);
785     boardEl.append(pieceEl);
786     PIECE_ON_SQUARE[square] = pieceEl;
787   }
788 }
789
790 function drawBoard() {
791   boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
792   drawPositionInstant();
793 }
794
795 // given a position and a set of moves, return a new position
796 // with the moves executed
797 function calculatePositionFromMoves(position, moves) {
798   position = deepCopy(position);
799
800   for (var i in moves) {
801     if (!moves.hasOwnProperty(i)) continue;
802
803     // skip the move if the position doesn't have a piece on the source square
804     if (!position.hasOwnProperty(i)) continue;
805
806     var piece = position[i];
807     delete position[i];
808     position[moves[i]] = piece;
809   }
810
811   return position;
812 }
813
814 function setCurrentPosition(position) {
815   var oldPos = deepCopy(CURRENT_POSITION);
816   var newPos = deepCopy(position);
817   var oldFen = objToFen(oldPos);
818   var newFen = objToFen(newPos);
819
820   // do nothing if no change in position
821   if (oldFen === newFen) return;
822
823   // run their onChange function
824   if (cfg.hasOwnProperty('onChange') &&
825     typeof cfg.onChange === 'function') {
826     cfg.onChange(oldPos, newPos);
827   }
828
829   // update state
830   CURRENT_POSITION = position;
831 }
832
833 function removeSquareHighlights() {
834   boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
835     piece.classList.remove(CSS.highlight1);
836     piece.classList.remove(CSS.highlight2);
837   });
838 }
839
840 function snapbackDraggedPiece() {
841   removeSquareHighlights();
842
843   // animation complete
844   function complete() {
845     drawPositionInstant();
846
847     // run their onSnapbackEnd function
848     if (cfg.hasOwnProperty('onSnapbackEnd') &&
849       typeof cfg.onSnapbackEnd === 'function') {
850       cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
851         deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
852     }
853   }
854
855   // get source square position
856   var sourceSquarePosition = findSquarePosition(DRAGGED_PIECE_SOURCE);
857
858   // animate the piece to the target square
859   DRAGGED_PIECE.animate(
860     [
861       { top: DRAGGED_PIECE.style.top, left: DRAGGED_PIECE.style.left },
862       { top: sourceSquarePosition.top, left: sourceSquarePosition.left }
863     ],
864     { duration: cfg.snapbackSpeed }
865   ).addEventListener('finish', complete);
866   DRAGGED_PIECE.style.top = sourceSquarePosition.top;
867   DRAGGED_PIECE.style.left = sourceSquarePosition.left;
868
869   // set state
870   DRAGGING_A_PIECE = false;
871 }
872
873 function dropDraggedPieceOnSquare(square) {
874   removeSquareHighlights();
875   DRAGGING_A_PIECE = false;
876
877   if (DRAGGED_PIECE_SOURCE === square) {
878     // Nothing to do, but call onSnapEnd anyway
879     if (cfg.hasOwnProperty('onSnapEnd') && typeof cfg.onSnapEnd === 'function') {
880       cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
881     }
882     return;
883   }
884
885   // update position
886   var newPosition = deepCopy(CURRENT_POSITION);
887   newPosition[square] = newPosition[DRAGGED_PIECE_SOURCE];
888   delete newPosition[DRAGGED_PIECE_SOURCE];
889   setCurrentPosition(newPosition);
890
891   delete PIECE_ON_SQUARE[DRAGGED_PIECE_SOURCE];
892   PIECE_ON_SQUARE[square] = DRAGGED_PIECE;
893   DRAGGED_PIECE.setAttribute('data-square', square);
894
895   // get target square information
896   var targetSquarePosition = findSquarePosition(square);
897
898   // animation complete
899   var complete = function() {
900     drawPositionInstant();
901
902     // execute their onSnapEnd function
903     if (cfg.hasOwnProperty('onSnapEnd') &&
904       typeof cfg.onSnapEnd === 'function') {
905       requestAnimationFrame(() => {  // HACK: so that we don't add event handlers from the callback...
906         cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
907       });
908     }
909   };
910
911   // snap the piece to the target square
912   DRAGGED_PIECE.animate(
913     [
914       { top: DRAGGED_PIECE.style.top, left: DRAGGED_PIECE.style.left },
915       { top: targetSquarePosition.top, left: targetSquarePosition.left }
916     ],
917     { duration: cfg.snapSpeed }
918   ).addEventListener('finish', complete);
919   DRAGGED_PIECE.style.top = targetSquarePosition.top;
920   DRAGGED_PIECE.style.left = targetSquarePosition.left;
921 }
922
923 function beginDraggingPiece(source, piece, x, y) {
924   // run their custom onDragStart function
925   // their custom onDragStart function can cancel drag start
926   if (typeof cfg.onDragStart === 'function' &&
927       cfg.onDragStart(source, piece,
928         deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
929     return;
930   }
931
932   // set state
933   DRAGGING_A_PIECE = true;
934   DRAGGED_PIECE = PIECE_ON_SQUARE[source];
935   DRAGGED_PIECE_SOURCE = source;
936   DRAGGED_PIECE_LOCATION = source;
937
938   // Move it to the end of the stack, which changes the implicit z-index
939   // so that it will go on top of any pieces it's replacing.
940   DRAGGED_PIECE.remove();
941   boardEl.appendChild(DRAGGED_PIECE);
942
943   // highlight the source square
944   let square = document.querySelector('.' + CSS.square + '[data-square="' + source + '"]');
945   square.classList.add(CSS.highlight1);
946 }
947
948 function findSquareFromEvent(pageX, pageY) {
949   let o = offset(boardEl);
950   let x = pageX - o.left;
951   let y = pageY - o.top;
952
953   let position = {
954     x: x,
955     y: y,
956     left: Math.floor(x * 8 / boardEl.getBoundingClientRect().width),
957     top: Math.floor(y * 8 / boardEl.getBoundingClientRect().width)
958   };
959   if (CURRENT_ORIENTATION === 'white') {
960     position.top = 7 - position.top;
961   }
962   if (position.left >= 0 && position.left < 8 && position.top >= 0 && position.top < 8) {
963     position.square = COLUMNS[position.left] + (position.top + 1);
964   } else {
965     position.square = 'offboard';
966   }
967   return position;
968 }
969
970 function updateDraggedPiece(position) {
971   // put the dragged piece over the mouse cursor
972   DRAGGED_PIECE.style.left = 'calc(' + position.x + 'px - 6.25%)';
973   DRAGGED_PIECE.style.top = 'calc(' + position.y + 'px - 6.25%)';
974
975   // do nothing if the location has not changed
976   if (position === DRAGGED_PIECE_LOCATION) return;
977
978   // remove highlight from previous square
979   if (validSquare(DRAGGED_PIECE_LOCATION)) {
980     document.querySelector('.' + CSS.square + '[data-square="' + DRAGGED_PIECE_LOCATION + '"]')
981       .classList.remove(CSS.highlight2);
982   }
983
984   // add highlight to new square
985   if (validSquare(position.square)) {
986     document.querySelector('.' + CSS.square + '[data-square="' + position.square + '"]')
987       .classList.add(CSS.highlight2);
988   }
989
990   // run onDragMove
991   if (typeof cfg.onDragMove === 'function') {
992     cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
993       DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
994       deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
995   }
996
997   // update state
998   DRAGGED_PIECE_LOCATION = position.square;
999 }
1000
1001 function stopDraggedPiece(location) {
1002   // determine what the action should be
1003   var action = 'drop';
1004   if (location.square === 'offboard' && cfg.dropOffBoard === 'snapback') {
1005     action = 'snapback';
1006   }
1007
1008   // run their onDrop function, which can potentially change the drop action
1009   if (cfg.hasOwnProperty('onDrop') &&
1010     typeof cfg.onDrop === 'function') {
1011     var newPosition = deepCopy(CURRENT_POSITION);
1012
1013     // source piece was on the board and position is on the board
1014     if (validSquare(DRAGGED_PIECE_SOURCE) &&
1015       validSquare(location.square)) {
1016       // move the piece
1017       delete newPosition[DRAGGED_PIECE_SOURCE];
1018       newPosition[location.square] = DRAGGED_PIECE;
1019       if (location.square !== DRAGGED_PIECE_SOURCE) {
1020         PIECE_ON_SQUARE[location.square] = PIECE_ON_SQUARE[DRAGGED_PIECE_SOURCE];
1021         DRAGGED_PIECE.setAttribute('data-square', location.square);
1022         delete PIECE_ON_SQUARE[DRAGGED_PIECE_SOURCE];
1023       }
1024     }
1025
1026     var oldPosition = deepCopy(CURRENT_POSITION);
1027
1028     var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location.square, DRAGGED_PIECE,
1029       newPosition, oldPosition, CURRENT_ORIENTATION);
1030     if (result === 'snapback') {
1031       action = result;
1032     }
1033   }
1034
1035   // do it!
1036   if (action === 'snapback') {
1037     snapbackDraggedPiece();
1038   }
1039   else if (action === 'drop') {
1040     dropDraggedPieceOnSquare(location.square);
1041   }
1042 }
1043
1044 //------------------------------------------------------------------------------
1045 // Public Methods
1046 //------------------------------------------------------------------------------
1047
1048 // clear the board
1049 widget.clear = function(useAnimation) {
1050   widget.position({}, useAnimation);
1051 };
1052
1053 /*
1054 // get or set config properties
1055 // TODO: write this, GitHub Issue #1
1056 widget.config = function(arg1, arg2) {
1057   // get the current config
1058   if (arguments.length === 0) {
1059     return deepCopy(cfg);
1060   }
1061 };
1062 */
1063
1064 // remove the widget from the page
1065 widget.destroy = function() {
1066   // remove markup
1067   containerEl.innerHTML = '';
1068   draggedPieceEl.remove();
1069 };
1070
1071 // shorthand method to get the current FEN
1072 widget.fen = function() {
1073   return widget.position('fen');
1074 };
1075
1076 // flip orientation
1077 widget.flip = function() {
1078   widget.orientation('flip');
1079 };
1080
1081 /*
1082 // TODO: write this, GitHub Issue #5
1083 widget.highlight = function() {
1084
1085 };
1086 */
1087
1088 // move pieces
1089 widget.move = function() {
1090   // no need to throw an error here; just do nothing
1091   if (arguments.length === 0) return;
1092
1093   var useAnimation = true;
1094
1095   // collect the moves into an object
1096   var moves = {};
1097   for (var i = 0; i < arguments.length; i++) {
1098     // any "false" to this function means no animations
1099     if (arguments[i] === false) {
1100       useAnimation = false;
1101       continue;
1102     }
1103
1104     // skip invalid arguments
1105     if (!validMove(arguments[i])) {
1106       error(2826, 'Invalid move passed to the move method.', arguments[i]);
1107       continue;
1108     }
1109
1110     var tmp = arguments[i].split('-');
1111     moves[tmp[0]] = tmp[1];
1112   }
1113
1114   // calculate position from moves
1115   var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1116
1117   // update the board
1118   widget.position(newPos, useAnimation);
1119
1120   // return the new position object
1121   return newPos;
1122 };
1123
1124 widget.orientation = function(arg) {
1125   // no arguments, return the current orientation
1126   if (arguments.length === 0) {
1127     return CURRENT_ORIENTATION;
1128   }
1129
1130   // set to white or black
1131   if (arg === 'white' || arg === 'black') {
1132     CURRENT_ORIENTATION = arg;
1133     drawBoard();
1134     return;
1135   }
1136
1137   // flip orientation
1138   if (arg === 'flip') {
1139     CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1140     drawBoard();
1141     return;
1142   }
1143
1144   error(5482, 'Invalid value passed to the orientation method.', arg);
1145 };
1146
1147 /**
1148  * @param {!string|!Object} position
1149  * @param {boolean=} useAnimation
1150  */
1151 widget.position = function(position, useAnimation) {
1152   // no arguments, return the current position
1153   if (arguments.length === 0) {
1154     return deepCopy(CURRENT_POSITION);
1155   }
1156
1157   // get position as FEN
1158   if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1159     return objToFen(CURRENT_POSITION);
1160   }
1161
1162   // default for useAnimations is true
1163   if (useAnimation !== false) {
1164     useAnimation = true;
1165   }
1166
1167   // start position
1168   if (typeof position === 'string' && position.toLowerCase() === 'start') {
1169     position = deepCopy(START_POSITION);
1170   }
1171
1172   // convert FEN to position object
1173   if (validFen(position)) {
1174     position = fenToObj(position);
1175   }
1176
1177   // validate position object
1178   if (!validPositionObject(position)) {
1179     error(6482, 'Invalid value passed to the position method.', position);
1180     return;
1181   }
1182
1183   if (useAnimation) {
1184     // start the animations
1185     doAnimations(calculateAnimations(CURRENT_POSITION, position),
1186       CURRENT_POSITION, position);
1187
1188     // set the new position
1189     setCurrentPosition(position);
1190   }
1191   // instant update
1192   else {
1193     setCurrentPosition(position);
1194     drawPositionInstant();
1195   }
1196 };
1197
1198 widget.resize = function() {
1199   // redraw the board
1200   drawBoard();
1201 };
1202
1203 // set the starting position
1204 widget.start = function(useAnimation) {
1205   widget.position('start', useAnimation);
1206 };
1207
1208 //------------------------------------------------------------------------------
1209 // Browser Events
1210 //------------------------------------------------------------------------------
1211
1212 function isTouchDevice() {
1213   return ('ontouchstart' in document.documentElement);
1214 }
1215
1216 function mousedownSquare(e) {
1217   let square = e.target.getAttribute('data-square');
1218
1219   // no piece on this square
1220   if (!validSquare(square) ||
1221       !CURRENT_POSITION.hasOwnProperty(square)) {
1222     return;
1223   }
1224
1225   // do nothing if we're not draggable
1226   if (!cfg.draggable) return;
1227
1228   beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1229 }
1230
1231 function touchstartSquare(e) {
1232   let target = e.target.closest('.' + CSS.square);
1233   if (!target) {
1234     return;
1235   }
1236
1237   // do nothing if we're not draggable
1238   if (!cfg.draggable) return;
1239
1240   var square = target.getAttribute('data-square');
1241
1242   // no piece on this square
1243   if (!validSquare(square) ||
1244       !CURRENT_POSITION.hasOwnProperty(square)) {
1245     return;
1246   }
1247
1248   beginDraggingPiece(square, CURRENT_POSITION[square],
1249     e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1250 }
1251
1252 function mousemoveWindow(e) {
1253   // do nothing if we are not dragging a piece
1254   if (!DRAGGING_A_PIECE) return;
1255
1256   updateDraggedPiece(findSquareFromEvent(e.pageX, e.pageY));
1257 }
1258
1259 function touchmoveWindow(e) {
1260   // do nothing if we are not dragging a piece
1261   if (!DRAGGING_A_PIECE) return;
1262
1263   // prevent screen from scrolling
1264   e.preventDefault();
1265
1266   updateDraggedPiece(findSquareFromEvent(e.changedTouches[0].pageX,
1267     e.changedTouches[0].pageY));
1268 }
1269
1270 function mouseupWindow(e) {
1271   // do nothing if we are not dragging a piece
1272   if (!DRAGGING_A_PIECE) return;
1273
1274   stopDraggedPiece(findSquareFromEvent(e.pageX, e.pageY));
1275 }
1276
1277 function touchendWindow(e) {
1278   // do nothing if we are not dragging a piece
1279   if (!DRAGGING_A_PIECE) return;
1280
1281   stopDraggedPiece(findSquareFromEvent(e.changedTouches[0].pageX,
1282     e.changedTouches[0].pageY));
1283 }
1284
1285 function mouseenterSquare(e) {
1286   let target = e.target.closest('.' + CSS.square);
1287   if (!target) {
1288     return;
1289   }
1290
1291   // do not fire this event if we are dragging a piece
1292   // NOTE: this should never happen, but it's a safeguard
1293   if (DRAGGING_A_PIECE !== false) return;
1294
1295   if (!cfg.hasOwnProperty('onMouseoverSquare') ||
1296     typeof cfg.onMouseoverSquare !== 'function') return;
1297
1298   // get the square
1299   var square = target.getAttribute('data-square');
1300
1301   // NOTE: this should never happen; defensive
1302   if (!validSquare(square)) return;
1303
1304   // get the piece on this square
1305   var piece = false;
1306   if (CURRENT_POSITION.hasOwnProperty(square)) {
1307     piece = CURRENT_POSITION[square];
1308   }
1309
1310   // execute their function
1311   cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1312     CURRENT_ORIENTATION);
1313 }
1314
1315 function mouseleaveSquare(e) {
1316   let target = e.target.closest('.' + CSS.square);
1317   if (!target) {
1318     return;
1319   }
1320
1321   // do not fire this event if we are dragging a piece
1322   // NOTE: this should never happen, but it's a safeguard
1323   if (DRAGGING_A_PIECE !== false) return;
1324
1325   if (!cfg.hasOwnProperty('onMouseoutSquare') ||
1326     typeof cfg.onMouseoutSquare !== 'function') return;
1327
1328   // get the square
1329   var square = target.getAttribute('data-square');
1330
1331   // NOTE: this should never happen; defensive
1332   if (!validSquare(square)) return;
1333
1334   // get the piece on this square
1335   var piece = false;
1336   if (CURRENT_POSITION.hasOwnProperty(square)) {
1337     piece = CURRENT_POSITION[square];
1338   }
1339
1340   // execute their function
1341   cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1342     CURRENT_ORIENTATION);
1343 }
1344
1345 //------------------------------------------------------------------------------
1346 // Initialization
1347 //------------------------------------------------------------------------------
1348
1349 function addEvents() {
1350   // prevent browser "image drag"
1351   let stopDefault = (e) => {
1352     if (e.target.matches('.' + CSS.piece)) {
1353       e.preventDefault();
1354     }
1355   };
1356   document.body.addEventListener('mousedown', stopDefault);
1357   document.body.addEventListener('mousemove', stopDefault);
1358
1359   // mouse drag pieces
1360   boardEl.addEventListener('mousedown', mousedownSquare);
1361
1362   // mouse enter / leave square
1363   boardEl.addEventListener('mouseenter', mouseenterSquare);
1364   boardEl.addEventListener('mouseleave', mouseleaveSquare);
1365
1366   window.addEventListener('mousemove', mousemoveWindow);
1367   window.addEventListener('mouseup', mouseupWindow);
1368
1369   // touch drag pieces
1370   if (isTouchDevice()) {
1371     boardEl.addEventListener('touchstart', touchstartSquare);
1372     window.addEventListener('touchmove', touchmoveWindow);
1373     window.addEventListener('touchend', touchendWindow);
1374   }
1375 }
1376
1377 function initDom() {
1378   // build board and save it in memory
1379   containerEl.innerHTML = buildBoardContainer();
1380   boardEl = containerEl.querySelector('.' + CSS.board);
1381
1382   // set the size and draw the board
1383   widget.resize();
1384 }
1385
1386 function init() {
1387   if (!checkDeps() || !expandConfig()) return;
1388
1389   initDom();
1390   addEvents();
1391 }
1392
1393 // go time
1394 init();
1395
1396 // return the widget object
1397 return widget;
1398
1399 }; // end window.ChessBoard
1400
1401 // expose util functions
1402 window.ChessBoard.fenToObj = fenToObj;
1403 window.ChessBoard.objToFen = objToFen;
1404
1405 })(); // end anonymous wrapper