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