]> git.sesse.net Git - remoteglot/blob - www/js/remoteglot.js
Fix some random type annotations.
[remoteglot] / www / js / remoteglot.js
1 (function() {
2 'use strict';
3
4 /**
5  * Version of this script. If the server returns a version larger than
6  * this, it is a sign we should reload to upgrade ourselves.
7  *
8  * @type {number}
9  * @const
10  * @private */
11 let SCRIPT_VERSION = 2023122700;
12
13 /**
14  * The current backend URL.
15  *
16  * @type {!string}
17  * @private
18  */
19 let backend_url = "/analysis.pl";
20 let backend_hash_url = "/hash";
21
22 /** @type {window.ChessBoard} @private */
23 let board = null;
24
25 /** @type {boolean} @private */
26 let board_is_animating = false;
27
28 /**
29  * The most recent analysis data we have from the server
30  * (about the most recent position).
31  *
32  * @type {?Object}
33  * @private */
34 let current_analysis_data = null;
35
36 /**
37  * If we are displaying previous analysis or from hash, this is non-null,
38  * and will override most of current_analysis_data.
39  *
40  * @type {?Object}
41  * @private
42  */
43 let displayed_analysis_data = null;
44
45 /**
46  * Games currently in progress, if any.
47  *
48  * @type {?Array.<{
49  *      name: string,
50  *      url: string,
51  *      hashurl: string,
52  *      id: string,
53  *      score: Object=,
54  *      result: string=,
55  * }>}
56  * @private
57  */
58 let current_games = null;
59
60 /** @type {Array.<{
61  *      from_col: number,
62  *      from_row: number,
63  *      to_col: number,
64  *      to_row: number,
65  *      line_width: number,
66  *      arrow_size: number,
67  *      fg_color: string
68  * }>}
69  * @private
70  */
71 let arrows = [];
72
73 /** @type {Array.<Array.<boolean>>} */
74 let occupied_by_arrows = [];
75
76 /** Currently displayed refutation lines (on-screen).
77  * Can either come from the current_analysis_data, displayed_analysis_data,
78  * or hash_refutation_lines.
79  *
80  * TODO: This is a mess, and we should probably just let update_refutation_lines()
81  * decide anew every time instead of storing the state here in multiple global
82  * variables.
83  *
84  * @type {Array.<{
85  *     score: Array,
86  *     depth: string,
87  *     pv: Array.<string>,
88  *     move: string
89  * }>}
90  * @private
91  */
92 let refutation_lines = [];
93
94 /** Refutation lines from current hash probe.
95  *
96  * If non-null, will override refutation lines from the base position.
97  * Note that these are relative to display_fen, not base_fen.
98  */
99 let hash_refutation_lines = null;
100
101 /**
102  * What FEN refutation_lines is relative to. Will usually be base_fen,
103  * but if another move gets loaded while we are looking, they can diverge.
104  */
105 let refutation_lines_base_fen = null;
106
107 /** @type {number} @private */
108 let ims = 0;
109
110 /** @type {boolean} @private */
111 let truncate_display_history = true;
112
113 /** @type {!string|undefined} @private */
114 let highlight_from = undefined;
115
116 /** @type {!string|undefined} @private */
117 let highlight_to = undefined;
118
119 /** The HTML object of the move currently being highlighted (in red).
120  * @type {?Element}
121  * @private */
122 let highlighted_move = null;
123
124 /** Currently suggested/recommended move when dragging.
125  * @type {?{from: !string, to: !string}}
126  * @private
127  */
128 let recommended_move = null;
129
130 /** If reverse-dragging (dragging from the destination square to the
131  * source square), the destination square.
132  * @type {?string}
133  * @private
134  */
135 let reverse_dragging_from = null;
136
137 /** @type {?number} @private */
138 let unique = null;
139
140 /** @type {?string} @private */
141 let admin_password = null;
142
143 /** @type {boolean} @private */
144 let enable_sound = false;
145
146 /** @type {!number} @private */
147 let delay_ms = 0;
148
149 /**
150  * Our best estimate of how many milliseconds we need to add to 
151  * new Date() to get the true UTC time. Calibrated against the
152  * server clock.
153  *
154  * @type {?number}
155  * @private
156  */
157 let client_clock_offset_ms = null;
158
159 let clock_timer = null;
160
161 /** The current position being analyzed, represented as a FEN string.
162  * Note that this is not necessarily the same as display_fen.
163  * @type {?string}
164  * @private
165  */
166 let base_fen = null;
167
168 /** The current position on the board, represented as a FEN string.
169  * Note that board.fen() does not contain e.g. who is to play.
170  * @type {?string}
171  * @private
172  */
173 let display_fen = null;
174
175 /** @typedef {{
176  *    start_fen: string,
177  *    pv: Array.<string>,
178  *    move_num: number,
179  *    toplay: string,
180  *    scores: Array<{first_move: number, score: Object}>,
181  *    start_display_move_num: number
182  * }}
183  *
184  * "start_display_move_num" is the (half-)move number to start displaying the PV at.
185  * "score" is also evaluated at this point.
186  */
187 var DisplayLine;
188
189 /** All PVs that we currently know of.
190  *
191  * Element 0 is history (or null if no history).
192  * Element 1 is current main PV, or explored line if nowhere else on the screen.
193  * All remaining elements are refutation lines (multi-PV).
194  *
195  * @type {Array.<DisplayLine>}
196  * @private
197  */
198 let display_lines = [];
199
200 /** @type {?DisplayLine} @private */
201 let current_display_line = null;
202
203 /** @type {boolean} @private */
204 let current_display_line_is_history = false;
205
206 /** @type {?number} @private */
207 let current_display_move = null;
208
209 /**
210  * The current backend request to get main analysis (not history), if any,
211  * so that we can abort it.
212  *
213  * @type {?AbortController}
214  * @private
215  */
216 let current_analysis_xhr = null;
217
218 /**
219  * The current timer to fire off a request to get main analysis (not history),
220  * if any, so that we can abort it.
221  *
222  * @type {?number}
223  * @private
224  */
225 let current_analysis_request_timer = null;
226
227 /**
228  * The current backend request to get historic data, if any.
229  *
230  * @type {?AbortController}
231  * @private
232  */
233 let current_historic_xhr = null;
234
235 /**
236  * The current backend request to get hash probes, if any, so that we can abort it.
237  *
238  * @type {?AbortController}
239  * @private
240  */
241 let current_hash_xhr = null;
242
243 /**
244  * The current timer to display hash probe information (it could be waiting on the
245  * board to stop animating), if any, so that we can abort it.
246  *
247  * @type {?number}
248  * @private
249  */
250 let current_hash_display_timer = null;
251
252 function supports_html5_storage() {
253         try {
254                 return 'localStorage' in window && window['localStorage'] !== null;
255         } catch (e) {
256                 return false;
257         }
258 }
259
260 // Make the unique token persistent so people refreshing the page won't count twice.
261 // Of course, you can never fully protect against people deliberately wanting to spam.
262 function get_unique() {
263         let use_local_storage = supports_html5_storage();
264         if (use_local_storage && window['localStorage']['unique']) {
265                 return window['localStorage']['unique'];
266         }
267         let unique = Math.random();
268         if (use_local_storage) {
269                 window['localStorage']['unique'] = unique;
270         }
271         return unique;
272 }
273
274 function request_update() {
275         current_analysis_request_timer = null;
276
277         let handle_err = () => {
278                 // Backend error or similar. Wait ten seconds, then try again.
279                 current_analysis_request_timer = setTimeout(function() { request_update(); }, 10000);
280         };
281
282         current_analysis_xhr = new AbortController();
283         const signal = current_analysis_xhr.signal;
284         fetch(backend_url + "?ims=" + ims + "&unique=" + unique, { signal })
285                 .then((response) => response.json().then(data => ({ok: response.ok, headers: response.headers, json: data})))  // ick
286                 .then((obj) => {
287                         if (!obj.ok) {
288                                 handle_err();
289                                 return;
290                         }
291
292                         if (delay_ms === 0) {
293                                 process_update_response(obj.json, obj.headers);
294                         } else {
295                                 setTimeout(function() { process_update_response(obj.json, obj.headers); }, delay_ms);
296                         }
297
298                         // Next update.
299                         if (!backend_url.match(/history/)) {
300                                 let timeout = 100;
301                                 current_analysis_request_timer = setTimeout(function() { request_update(); }, timeout);
302                         }
303                 })
304                 .catch((err) => {
305                         if (err.name === 'AbortError') {
306                                 // Aborted because we are switching backends. Abandon and don't retry,
307                                 // because another one is already started for us.
308                         } else {
309                                 console.log(err);
310                                 handle_err(err);
311                         }
312                 })
313                 .finally(() => {
314                         // Display.
315                         document.body.style.opacity = null;
316                 })
317
318 }
319
320 function process_update_response(data, headers) {
321         sync_server_clock(headers.get('Date'));
322         ims = headers.get('X-RGLM');
323         let num_viewers = headers.get('X-RGNV');
324         let new_data;
325         if (Array.isArray(data)) {
326                 new_data = JSON.parse(JSON.stringify(current_analysis_data));
327                 JSON_delta.patch(new_data, data);
328         } else {
329                 new_data = data;
330         }
331
332         let minimum_version = headers.get('X-RGMV');
333         if (minimum_version && minimum_version > SCRIPT_VERSION) {
334                 // Upgrade to latest version with a force-reload.
335                 location.reload(true);
336         }
337
338         // Verify that the PV makes sense.
339         let valid = true;
340         if (new_data['pv']) {
341                 let hiddenboard = new Chess(new_data['position']['fen']);
342                 for (let i = 0; i < new_data['pv'].length; ++i) {
343                         if (hiddenboard.move(new_data['pv'][i]) === null) {
344                                 valid = false;
345                                 break;
346                         }
347                 }
348         }
349
350         if (valid) {
351                 possibly_play_sound(current_analysis_data, new_data);
352                 current_analysis_data = new_data;
353                 update_board();
354                 update_num_viewers(num_viewers);
355         } else {
356                 console.log("Received invalid update, waiting five seconds and trying again.");
357                 setTimeout(function() { location.reload(true); }, 5000);
358         }
359 }
360
361 function possibly_play_sound(old_data, new_data) {
362         if (!enable_sound) {
363                 return;
364         }
365         if (old_data === null) {
366                 return;
367         }
368         let ding = document.getElementById('ding');
369         if (ding && ding.play) {
370                 if (old_data['position'] && old_data['position']['fen'] &&
371                     new_data['position'] && new_data['position']['fen'] &&
372                     old_data['position']['fen'] !== new_data['position']['fen']) {
373                         ding.play();
374                 }
375         }
376 }
377
378 /**
379  * @type {!string} server_date_string
380  */
381 function sync_server_clock(server_date_string) {
382         let server_time_ms = new Date(server_date_string).getTime();
383         let client_time_ms = new Date().getTime();
384         let estimated_offset_ms = server_time_ms - client_time_ms;
385
386         // In order not to let the noise move us too much back and forth
387         // (the server only has one-second resolution anyway), we only
388         // change an existing skew if we are at least five seconds off.
389         if (client_clock_offset_ms === null ||
390             Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
391                 client_clock_offset_ms = estimated_offset_ms;
392         }
393 }
394
395 function clear_arrows() {
396         for (let i = 0; i < arrows.length; ++i) {
397                 if (arrows[i].svg) {
398                         arrows[i].svg.remove();
399                         delete arrows[i].svg;
400                 }
401         }
402         arrows = [];
403
404         occupied_by_arrows = [];
405         for (let y = 0; y < 8; ++y) {
406                 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
407         }
408 }
409
410 function redraw_arrows() {
411         for (let i = 0; i < arrows.length; ++i) {
412                 position_arrow(arrows[i]);
413         }
414 }
415
416 /** @param {!string} fen
417  * @return {!string}
418  *
419  * Return whose side it is to play (w or b), given a FEN.
420  */
421 function find_toplay(fen) {
422         return fen.split(' ')[1];
423 }
424
425 /** @param {!string} fen
426  * @return {!number}
427  *
428  * Return the move clock, starting from 1. See also find_toplay().
429  */
430 function find_move_num(fen) {
431         return parseInt(fen.split(' ')[5]);
432 }
433
434 /** @param {!number} x
435  * @return {!number}
436  */
437 function sign(x) {
438         if (x > 0) {
439                 return 1;
440         } else if (x < 0) {
441                 return -1;
442         } else {
443                 return 0;
444         }
445 }
446
447 /** See if drawing this arrow on the board would cause unduly amount of confusion.
448  * @param {!string} from The square the arrow is from (e.g. e4).
449  * @param {!string} to The square the arrow is to (e.g. e4).
450  * @return {boolean}
451  */
452 function interfering_arrow(from, to) {
453         let from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
454         let from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
455         let to_col   = to.charCodeAt(0) - "a1".charCodeAt(0);
456         let to_row   = to.charCodeAt(1) - "a1".charCodeAt(1);
457
458         occupied_by_arrows[from_row][from_col] = true;
459
460         // Knight move: Just check that we haven't been at the destination before.
461         if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
462             (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
463                 return occupied_by_arrows[to_row][to_col];
464         }
465
466         // Sliding piece: Check if anything except the from-square is seen before.
467         let dx = sign(to_col - from_col);
468         let dy = sign(to_row - from_row);
469         let x = from_col;
470         let y = from_row;
471         do {
472                 x += dx;
473                 y += dy;
474                 if (occupied_by_arrows[y][x]) {
475                         return true;
476                 }
477                 occupied_by_arrows[y][x] = true;
478         } while (x != to_col || y != to_row);
479
480         return false;
481 }
482
483 /** Find a point along the coordinate system given by the given line,
484  * <t> units forward from the start of the line, <u> units to the right of it.
485  * @param {!number} x1
486  * @param {!number} x2
487  * @param {!number} y1
488  * @param {!number} y2
489  * @param {!number} t
490  * @param {!number} u
491  * @return {!string} The point in "x y" form, suitable for SVG paths.
492  */
493 function point_from_start(x1, y1, x2, y2, t, u) {
494         let dx = x2 - x1;
495         let dy = y2 - y1;
496
497         let norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
498         dx *= norm;
499         dy *= norm;
500
501         let x = x1 + dx * t + dy * u;
502         let y = y1 + dy * t - dx * u;
503         return x + " " + y;
504 }
505
506 /** Find a point along the coordinate system given by the given line,
507  * <t> units forward from the end of the line, <u> units to the right of it.
508  * @param {!number} x1
509  * @param {!number} x2
510  * @param {!number} y1
511  * @param {!number} y2
512  * @param {!number} t
513  * @param {!number} u
514  * @return {!string} The point in "x y" form, suitable for SVG paths.
515  */
516 function point_from_end(x1, y1, x2, y2, t, u) {
517         let dx = x2 - x1;
518         let dy = y2 - y1;
519
520         let norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
521         dx *= norm;
522         dy *= norm;
523
524         let x = x2 + dx * t + dy * u;
525         let y = y2 + dy * t - dx * u;
526         return x + " " + y;
527 }
528
529 function position_arrow(arrow) {
530         if (arrow.svg) {
531                 if (arrow.svg.parentElement) {
532                         arrow.svg.parentElement.removeChild(arrow.svg);
533                 }
534                 delete arrow.svg;
535         }
536         if (current_display_line !== null && !current_display_line_is_history) {
537                 return;
538         }
539
540         // We always draw as if the board is 400x400, the viewBox will adjust that for us
541         let line_width = arrow.line_width;
542         let arrow_size = arrow.arrow_size;
543
544         let square_width = 400 / 8;
545         let from_y, to_y, from_x, to_x;
546         if (board.orientation() === 'black') {
547                 from_y = (arrow.from_row + 0.5)*square_width;
548                 to_y = (arrow.to_row + 0.5)*square_width;
549                 from_x = (7 - arrow.from_col + 0.5)*square_width;
550                 to_x = (7 - arrow.to_col + 0.5)*square_width;
551         } else {
552                 from_y = (7 - arrow.from_row + 0.5)*square_width;
553                 to_y = (7 - arrow.to_row + 0.5)*square_width;
554                 from_x = (arrow.from_col + 0.5)*square_width;
555                 to_x = (arrow.to_col + 0.5)*square_width;
556         }
557
558         let SVG_NS = "http://www.w3.org/2000/svg";
559         let XHTML_NS = "http://www.w3.org/1999/xhtml";
560         let svg = document.createElementNS(SVG_NS, "svg");
561         svg.setAttribute("width", "100%");
562         svg.setAttribute("height", "100%");
563         svg.setAttribute("viewBox", "0 0 400 400");
564         svg.setAttribute("version", "1.1");
565         svg.setAttribute("class", "c1");
566         svg.setAttribute("xmlns", XHTML_NS);
567
568         let x1 = from_x;
569         let y1 = from_y;
570         let x2 = to_x;
571         let y2 = to_y;
572
573         // Draw the line.
574         let outline = document.createElementNS(SVG_NS, "path");
575         outline.setAttribute("d", "M " + point_from_start(x1, y1, x2, y2, arrow_size / 2, 0) + " L " + point_from_end(x1, y1, x2, y2, -arrow_size / 2, 0));
576         outline.setAttribute("xmlns", XHTML_NS);
577         outline.setAttribute("stroke", "#666");
578         outline.setAttribute("stroke-width", line_width + 2);
579         outline.setAttribute("fill", "none");
580         svg.appendChild(outline);
581
582         let path = document.createElementNS(SVG_NS, "path");
583         path.setAttribute("d", "M " + point_from_start(x1, y1, x2, y2, arrow_size / 2, 0) + " L " + point_from_end(x1, y1, x2, y2, -arrow_size / 2, 0));
584         path.setAttribute("xmlns", XHTML_NS);
585         path.setAttribute("stroke", arrow.fg_color);
586         path.setAttribute("stroke-width", line_width);
587         path.setAttribute("fill", "none");
588         svg.appendChild(path);
589
590         // Then the arrow head.
591         let head = document.createElementNS(SVG_NS, "path");
592         head.setAttribute("d",
593                 "M " +  point_from_end(x1, y1, x2, y2, 0, 0) +
594                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
595                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
596                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
597                 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
598         head.setAttribute("xmlns", XHTML_NS);
599         head.setAttribute("stroke", "#000");
600         head.setAttribute("stroke-width", "1");
601         head.setAttribute("fill", arrow.fg_color);
602         svg.appendChild(head);
603
604         svg.style.position = 'absolute';
605         svg.style.top = '0px';  /* Border for .board-b72b1. */
606         svg.style.left = '0px';
607         svg.style.pointerEvents = 'none';
608         document.getElementById('board').appendChild(svg);
609         arrow.svg = svg;
610 }
611
612 /**
613  * @param {!string} from_square
614  * @param {!string} to_square
615  * @param {!string} fg_color
616  * @param {number} line_width
617  * @param {number} arrow_size
618  */
619 function create_arrow(from_square, to_square, fg_color, line_width, arrow_size) {
620         let from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
621         let from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
622         let to_col   = to_square.charCodeAt(0) - "a1".charCodeAt(0);
623         let to_row   = to_square.charCodeAt(1) - "a1".charCodeAt(1);
624
625         // Create arrow.
626         let arrow = {
627                 from_col: from_col,
628                 from_row: from_row,
629                 to_col: to_col,
630                 to_row: to_row,
631                 line_width: line_width,
632                 arrow_size: arrow_size,
633                 fg_color: fg_color
634         };
635
636         position_arrow(arrow);
637         arrows.push(arrow);
638 }
639
640 function compare_by_score(refutation_lines, invert, a, b) {
641         let sa = compute_score_sort_key(refutation_lines[b]['score'], refutation_lines[b]['depth'], invert);
642         let sb = compute_score_sort_key(refutation_lines[a]['score'], refutation_lines[a]['depth'], invert);
643         return sa - sb;
644 }
645
646 /**
647  * Fake multi-PV using the refutation lines. Find all “relevant” moves,
648  * sorted by quality, descending.
649  *
650  * @param {!Object} data
651  * @param {number} margin The maximum number of centipawns worse than the
652  *     best move can be and still be included.
653  * @param {boolean} invert Whether black is to play.
654  * @return {Array.<string>} The FEN representation (e.g. Ne4) of all
655  *     moves, in score order.
656  */
657 function find_nonstupid_moves(data, margin, invert) {
658         // First of all, if there are any moves that are more than 0.5 ahead of
659         // the primary move, the refutation lines are probably bunk, so just
660         // kill them all. 
661         let best_score = undefined;
662         let pv_score = undefined;
663         for (let move in data['refutation_lines']) {
664                 let line = data['refutation_lines'][move];
665                 let score = compute_score_sort_key(line['score'], line['depth'], invert);
666                 if (move == data['pv'][0]) {
667                         pv_score = score;
668                 }
669                 if (best_score === undefined || score > best_score) {
670                         best_score = score;
671                 }
672                 if (line['depth'] < 8) {
673                         return [];
674                 }
675         }
676
677         if (best_score - pv_score > 50) {
678                 return [];
679         }
680
681         // Now find all moves that are within “margin” of the best score.
682         // The PV move will always be first.
683         let moves = [];
684         for (let move in data['refutation_lines']) {
685                 let line = data['refutation_lines'][move];
686                 let score = compute_score_sort_key(line['score'], line['depth'], invert);
687                 if (move != data['pv'][0] && best_score - score <= margin) {
688                         moves.push(move);
689                 }
690         }
691         let toplay = find_toplay(data['position']['fen']);
692         moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], toplay, a, b) });
693         moves.unshift(data['pv'][0]);
694
695         return moves;
696 }
697
698 /**
699  * @param {number} x
700  * @return {!string}
701  */
702 function thousands(x) {
703         return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
704 }
705
706 /**
707  * @param {!string} start_fen
708  * @param {Array.<string>} pv
709  * @param {Array<{ first_move: number, score: Object }>} scores
710  * @param {number} start_display_move_num
711  * @param {number=} opt_limit
712  * @param {boolean=} opt_showlast
713  */
714 function add_pv(start_fen, pv, scores, start_display_move_num, opt_limit, opt_showlast) {
715         display_lines.push({
716                 start_fen: start_fen,
717                 pv: pv,
718                 move_num: find_move_num(start_fen),
719                 toplay: find_toplay(start_fen),
720                 scores: scores,
721                 start_display_move_num: start_display_move_num
722         });
723         let splicepos = null;
724         if (scores !== null && scores.length >= 1 &&
725             scores[scores.length - 1].score !== undefined &&
726             scores[scores.length - 1].score !== null &&
727             (scores[scores.length - 1].score[0] === 'T' ||
728              scores[scores.length - 1].score[0] === 't')) {
729                 splicepos = scores[scores.length - 1].score[1];
730         }
731         return print_pv(display_lines.length - 1, splicepos, opt_limit, opt_showlast);
732 }
733
734 /**
735  * @param {number} line_num
736  * @param {?number} splicepos If non-null, where the tablebase-spliced portion of the TB starts.
737  * @param {number=} opt_limit If set, show at most this number of moves.
738  * @param {boolean=} opt_showlast If limit is set, show the last moves instead of the first ones.
739  */
740 function print_pv(line_num, splicepos, opt_limit, opt_showlast) {
741         let display_line = display_lines[line_num];
742         let pv = display_line.pv;
743         let move_num = display_line.move_num;
744         let toplay = display_line.toplay;
745
746         // Truncate PV at the start if needed.
747         let start_display_move_num = display_line.start_display_move_num;
748         if (start_display_move_num > 0) {
749                 pv = pv.slice(start_display_move_num);
750                 let to_add = start_display_move_num;
751                 if (toplay === 'b') {
752                         ++move_num;
753                         toplay = 'w';
754                         --to_add;
755                 }
756                 if (to_add % 2 == 1) {
757                         toplay = 'b';
758                         --to_add;
759                 }
760                 move_num += to_add / 2;
761                 if (splicepos !== null && splicepos > 0) {
762                         --splicepos;
763                 }
764         }
765
766         let ret = document.createDocumentFragment();
767         let in_tb = false;
768         let i = 0;
769         if (opt_limit && opt_showlast && pv.length > opt_limit) {
770                 // Truncate the PV at the beginning (instead of at the end).
771                 // We assume here that toplay is 'w'. We also assume that if
772                 // opt_showlast is set, then it is the history, and thus,
773                 // the UI should be to expand the history.
774                 ret.appendChild(document.createTextNode('('));
775                 let link = document.createElement('a');
776                 link.className = 'move';
777                 link.href = 'javascript:collapse_history(false)';
778                 link.textContent = '…';
779                 ret.appendChild(link);
780                 ret.appendChild(document.createTextNode(') '));
781                 i = pv.length - opt_limit;
782                 if (i % 2 == 1) {
783                         ++i;
784                 }
785                 move_num += i / 2;
786         } else if (toplay == 'b' && pv.length > 0) {
787                 ret.appendChild(document.createTextNode(move_num + '. … '));
788         }
789         for (; i < pv.length; ++i) {
790                 let prefix = '';
791                 if (splicepos === i) {
792                         prefix = '(TB: ';
793                         in_tb = true;
794                 }
795
796                 if (toplay == 'b' && i == 0) {
797                         ++move_num;
798                         toplay = 'w';
799                 } else if (toplay == 'w') {
800                         if (i > opt_limit && !opt_showlast) {
801                                 if (in_tb) {
802                                         prefix += ')';
803                                 }
804                                 ret.appendChild(document.createTextNode(prefix + ' (…)'));
805                                 return ret;
806                         }
807                         prefix += ' ' + move_num + '. ';
808                         ++move_num;
809                         toplay = 'b';
810                 } else {
811                         prefix += ' ';
812                         toplay = 'w';
813                 }
814                 ret.appendChild(document.createTextNode(prefix));
815
816                 let link = document.createElement('a');
817                 link.className = 'move';
818                 link.setAttribute('id', 'automove' + line_num + '-' + i);
819                 link.textContent = pv[i];
820                 link.href = 'javascript:show_line(' + line_num + ', ' + i + ');';
821                 ret.appendChild(link);
822         }
823         if (in_tb) {
824                 ret.appendChild(document.createTextNode(')'));
825         }
826         return ret;
827 }
828
829 /** Update the highlighted to/from squares on the board.
830  * Based on the global "highlight_from" and "highlight_to" letiables.
831  */
832 function update_board_highlight() {
833         document.getElementById("board").querySelectorAll('.square-55d63').forEach((square) => square.classList.remove('nonuglyhighlight'));
834         if ((current_display_line === null || current_display_line_is_history) &&
835             highlight_from !== undefined && highlight_to !== undefined) {
836                 document.getElementById("board").querySelector('.square-' + highlight_from).classList.add('nonuglyhighlight');
837                 document.getElementById("board").querySelector('.square-' + highlight_to).classList.add('nonuglyhighlight');
838         }
839 }
840
841 function update_history() {
842         let history = document.getElementById('history');
843         if (display_lines[0] === null || display_lines[0].pv.length == 0) {
844                 history.textContent = 'No history';
845         } else if (truncate_display_history) {
846                 history.replaceChildren(print_pv(0, null, 8, true));
847         } else {
848                 history.textContent = '(';
849                 let link = document.createElement('a');
850                 link.className = 'move';
851                 link.href = 'javascript:collapse_history(true)';
852                 link.textContent = 'collapse';
853                 history.appendChild(link);
854                 history.appendChild(document.createTextNode(') '));
855                 history.append(print_pv(0, null));
856         }
857 }
858
859 /**
860  * @param {!boolean} truncate_history
861  */
862 function collapse_history(truncate_history) {
863         truncate_display_history = truncate_history;
864         update_history();
865 }
866 window['collapse_history'] = collapse_history;
867
868 /** Update the HTML display of multi-PV from the global "refutation_lines".
869  *
870  * Also recreates the global "display_lines".
871  */
872 function update_refutation_lines() {
873         if (refutation_lines_base_fen === null) {
874                 return;
875         }
876         if (display_lines.length > 2) {
877                 // Truncate so that only the history and PV is left.
878                 display_lines = [ display_lines[0], display_lines[1] ];
879         }
880         let tbl = document.getElementById("refutationlines");
881         tbl.replaceChildren();
882
883         if (display_lines.length < 2) {
884                 // Update the move highlight, as we've rewritten all the HTML.
885                 update_move_highlight();
886                 return;
887         }
888
889         // Find out where the lines start from.
890         let base_line = [];
891         let base_scores = display_lines[1].scores;
892         let start_display_move_num = 0;
893         if (hash_refutation_lines) {
894                 base_line = current_display_line.pv.slice(0, current_display_move + 1);
895                 base_scores = current_display_line.scores;
896                 start_display_move_num = base_line.length;
897         }
898
899         let moves = [];
900         for (let move in refutation_lines) {
901                 moves.push(move);
902         }
903
904         let invert = (find_toplay(refutation_lines_base_fen) === 'b');
905         if (current_display_line && current_display_move % 2 == 0 && !current_display_line_is_history) {
906                 invert = !invert;
907         }
908         moves = moves.sort(function(a, b) { return compare_by_score(refutation_lines, invert, a, b) });
909         for (let i = 0; i < moves.length; ++i) {
910                 let line = refutation_lines[moves[i]];
911
912                 let tr = document.createElement("tr");
913
914                 let move_td = document.createElement("td");
915                 tr.appendChild(move_td);
916                 move_td.classList.add("move");
917
918                 let scores = base_scores.concat([{ first_move: start_display_move_num, score: line['score'] }]);
919
920                 if (line['pv'].length == 0) {
921                         // Not found, so just make a one-move PV.
922                         let link = document.createElement('a');
923                         link.className = 'move';
924                         link.href = 'javascript:show_line(' + display_lines.length + ', ' + 0 + ')';
925                         link.textContent = line['move'];
926                         move_td.replaceChildren(link);
927
928                         let score_td = document.createElement("td");
929                         score_td.classList.add("score");
930                         score_td.textContent = "—";
931                         tr.appendChild(score_td);
932
933                         let depth_td = document.createElement("td");
934                         tr.appendChild(depth_td);
935                         depth_td.classList.add("depth");
936                         depth_td.textContent = "—";
937
938                         let pv_td = document.createElement("td");
939                         tr.appendChild(pv_td);
940                         pv_td.classList.add("pv");
941                         pv_td.append(add_pv(refutation_lines_base_fen, base_line.concat([ line['move'] ]), scores, start_display_move_num));
942
943                         tbl.append(tr);
944                         continue;
945                 }
946
947                 let move_link = document.createElement("a");
948                 move_link.classList.add("move");
949                 move_link.setAttribute("href", "javascript:show_line(" + display_lines.length + ", 0)");
950                 move_link.textContent = line['move'];
951                 move_td.appendChild(move_link);
952
953                 let score_td = document.createElement("td");
954                 tr.appendChild(score_td);
955                 score_td.classList.add("score");
956                 score_td.textContent = format_short_score(line['score']);
957
958                 let depth_td = document.createElement("td");
959                 tr.appendChild(depth_td);
960                 depth_td.classList.add("depth");
961                 if (line['depth'] && line['depth'] >= 0) {
962                         depth_td.textContent = "d" + line['depth'];
963                 } else {
964                         depth_td.textContent = "—";
965                 }
966
967                 let pv_td = document.createElement("td");
968                 tr.appendChild(pv_td);
969                 pv_td.classList.add("pv");
970                 pv_td.append(add_pv(refutation_lines_base_fen, base_line.concat(line['pv']), scores, start_display_move_num, 10));
971
972                 tbl.append(tr);
973         }
974
975         // Update the move highlight, as we've rewritten all the HTML.
976         update_move_highlight();
977 }
978
979 /**
980  * Create a Chess.js board object, containing the given position plus the given moves,
981  * up to the given limit.
982  *
983  * @param {?string} fen
984  * @param {Array.<string>} moves
985  * @param {number} last_move
986  */
987 function chess_from(fen, moves, last_move) {
988         let hiddenboard = new Chess();
989         if (fen !== null && fen !== undefined) {
990                 hiddenboard.load(fen);
991         }
992         for (let i = 0; i <= last_move; ++i) {
993                 if (moves[i] === '0-0') {
994                         hiddenboard.move('O-O');
995                 } else if (moves[i] === '0-0-0') {
996                         hiddenboard.move('O-O-O');
997                 } else {
998                         hiddenboard.move(moves[i]);
999                 }
1000         }
1001         return hiddenboard;
1002 }
1003
1004 function update_game_list(games) {
1005         document.getElementById("games").textContent = "";
1006         if (games === null) {
1007                 return;
1008         }
1009
1010         let games_div = document.getElementById('games');
1011         for (let game_num = 0; game_num < games.length; ++game_num) {
1012                 let game = games[game_num];
1013                 let game_span = document.createElement("span");
1014                 game_span.setAttribute("class", "game");
1015
1016                 let game_name = document.createTextNode(game['name']);
1017                 if (game['url'] === backend_url) {
1018                         // This game.
1019                         game_span.appendChild(game_name);
1020
1021                         if (current_analysis_data && current_analysis_data['position']) {
1022                                 let score;
1023                                 if (current_analysis_data['position']['result']) {
1024                                         score = " (" + current_analysis_data['position']['result'] + ")";
1025                                 } else {
1026                                         score = " (" + format_short_score(current_analysis_data['score']) + ")";
1027                                 }
1028                                 game_span.appendChild(document.createTextNode(score));
1029                         }
1030                 } else {
1031                         // Some other game.
1032                         let game_a = document.createElement("a");
1033                         game_a.setAttribute("href", "#" + game['id']);
1034                         game_a.appendChild(game_name);
1035                         game_span.appendChild(game_a);
1036
1037                         let score;
1038                         if (game['result']) {
1039                                 score = " (" + game['result'] + ")";
1040                         } else {
1041                                 score = " (" + format_short_score(game['score']) + ")";
1042                         }
1043                         game_span.appendChild(document.createTextNode(score));
1044                 }
1045
1046                 games_div.appendChild(game_span);
1047         }
1048 }
1049
1050 /**
1051  * Try to find a running game that matches with the current hash,
1052  * and switch to it if we're not already displaying it.
1053  */
1054 function possibly_switch_game_from_hash() {
1055         let history_match = window.location.hash.match(/^#history=([a-zA-Z0-9_-]+)/);
1056         if (history_match !== null) {
1057                 let game_id = history_match[1];
1058                 let fake_game = {
1059                         url: '/history/' + game_id + '.json',
1060                         hashurl: '',
1061                         id: 'history=' + game_id
1062                 };
1063                 switch_backend(fake_game);
1064                 return;
1065         }
1066
1067         if (current_games === null) {
1068                 return;
1069         }
1070
1071         let hash = window.location.hash.replace(/^#/,'');
1072         for (let i = 0; i < current_games.length; ++i) {
1073                 if (current_games[i]['id'] === hash) {
1074                         if (backend_url !== current_games[i]['url']) {
1075                                 switch_backend(current_games[i]);
1076                         }
1077                         return;
1078                 }
1079         }
1080 }
1081
1082 /**
1083  * If this is a Chess960 castling which doesn't move the king,
1084  * move the rook instead.
1085 */
1086 function patch_move(move) {
1087         if (move === null) return null;
1088         if (move.from !== move.to) return move;
1089
1090         let f = move.rook_sq & 15;
1091         let r = move.rook_sq >> 4;
1092         let from = ('abcdefgh'.substring(f,f+1) + '87654321'.substring(r,r+1));
1093         let to = move.to;
1094
1095         if (move.to === 'g1') {
1096                 to = 'f1';
1097         } else if (move.to === 'g8') {
1098                 to = 'f8';
1099         } else if (move.to === 'b1') {
1100                 to = 'c1';
1101         } else if (move.to === 'b8') {
1102                 to = 'c8';
1103         }
1104
1105         return { from: from, to: to };
1106 }
1107
1108 /** Update all the HTML on the page, based on current global state.
1109  */
1110 function update_board() {
1111         document.body.style.opacity = null;
1112
1113         let data = displayed_analysis_data || current_analysis_data;
1114         let current_data = current_analysis_data;  // Convenience alias.
1115
1116         display_lines = [];
1117
1118         // Print the history. This is pretty much the only thing that's
1119         // unconditionally taken from current_data (we're not interested in
1120         // historic history).
1121         if (current_data['position']['history']) {
1122                 let start = (current_data['position'] && current_data['position']['start_fen']) ? current_data['position']['start_fen'] : 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';
1123                 add_pv(start, current_data['position']['history'], null, 0, 8, true);
1124         } else {
1125                 display_lines.push(null);
1126         }
1127         update_history();
1128
1129         // Games currently in progress, if any.
1130         if (current_data['games']) {
1131                 current_games = current_data['games'];
1132                 possibly_switch_game_from_hash();
1133         } else {
1134                 current_games = null;
1135         }
1136         update_game_list(current_games);
1137
1138         // The headline. Names are always fetched from current_data;
1139         // the rest can depend a bit.
1140         let headline;
1141         if (current_data &&
1142             current_data['position']['player_w'] && current_data['position']['player_b']) {
1143                 headline = current_data['position']['player_w'] + '–' +
1144                         current_data['position']['player_b'] + ', analysis';
1145         } else {
1146                 headline = 'Analysis';
1147         }
1148
1149         // Credits: The engine name/version.
1150         if (current_data['engine'] && current_data['engine']['name'] !== null) {
1151                 document.getElementById("engineid").textContent = current_data['engine']['name'];
1152         }
1153
1154         // Credits: The engine URL.
1155         if (current_data['engine'] && current_data['engine']['url']) {
1156                 document.getElementById("engineid").setAttribute("href", current_data['engine']['url']);
1157         } else {
1158                 document.getElementById("engineid").removeAttribute("href");
1159         }
1160
1161         // Credits: Engine details.
1162         if (current_data['engine'] && current_data['engine']['details']) {
1163                 document.getElementById("enginedetails").textContent = " (" + current_data['engine']['details'] + ")";
1164         } else {
1165                 document.getElementById("enginedetails").textContent = "";
1166         }
1167
1168         // Credits: Move source, possibly with URL.
1169         if (current_data['move_source'] && current_data['move_source_url']) {
1170                 document.getElementById("movesource").textContent = "Moves provided by ";
1171                 let movesource_a = document.createElement("a");
1172                 movesource_a.setAttribute("href", current_data['move_source_url']);
1173                 let movesource_text = document.createTextNode(current_data['move_source']);
1174                 movesource_a.appendChild(movesource_text);
1175                 let movesource_period = document.createTextNode(".");
1176                 document.getElementById("movesource").appendChild(movesource_a);
1177                 document.getElementById("movesource").appendChild(movesource_period);
1178         } else if (current_data['move_source']) {
1179                 document.getElementById("movesource").textContent = "Moves provided by " + current_data['move_source'] + ".";
1180         } else {
1181                 document.getElementById("movesource").textContent = "";
1182         }
1183
1184         let last_move;
1185         if (displayed_analysis_data) {
1186                 // Displaying some non-current position, pick out the last move
1187                 // from the history. This will work even if the fetch failed.
1188                 if (current_display_move !== -1) {
1189                         last_move = format_halfmove_with_number(
1190                                 current_display_line.pv[current_display_move],
1191                                 current_display_move);
1192                         headline += ' after ' + last_move;
1193                 }
1194         } else if (data['position']['last_move'] !== 'none') {
1195                 // Find the previous move.
1196                 let previous_move_num, previous_toplay;
1197                 let fen = data['position']['fen'];
1198                 if (find_toplay(fen) === 'b') {
1199                         previous_move_num = find_move_num(fen);
1200                         previous_toplay = 'w';
1201                 } else {
1202                         previous_move_num = find_move_num(fen) - 1;
1203                         previous_toplay = 'b';
1204                 }
1205
1206                 last_move = format_move_with_number(
1207                         data['position']['last_move'],
1208                         previous_move_num,
1209                         previous_toplay == 'w');
1210                 headline += ' after ' + last_move;
1211         } else {
1212                 last_move = null;
1213         }
1214         document.getElementById("headline").textContent = headline;
1215
1216         // The <title> contains a very brief headline.
1217         let title_elems = [];
1218         if (data['position'] && data['position']['result']) {
1219                 title_elems.push(data['position']['result']);
1220         } else if (data['score']) {
1221                 title_elems.push(format_short_score(data['score']));
1222         }
1223         if (last_move !== null) {
1224                 title_elems.push(last_move);
1225         }
1226
1227         if (title_elems.length != 0) {
1228                 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
1229         } else {
1230                 document.title = 'analysis.sesse.net';
1231         }
1232
1233         // The last move (shown by highlighting the from and to squares).
1234         if (data['position'] && data['position']['last_move_uci']) {
1235                 highlight_from = data['position']['last_move_uci'].substr(0, 2);
1236                 highlight_to = data['position']['last_move_uci'].substr(2, 2);
1237         } else if (current_display_line_is_history && current_display_line && current_display_move >= 0) {
1238                 // We don't have historic analysis for this position, but we
1239                 // can reconstruct what the last move was by just replaying
1240                 // from the start.
1241                 let position = (data['position'] && data['position']['start_fen']) ? data['position']['start_fen'] : null;
1242                 let hiddenboard = chess_from(position, current_display_line.pv, current_display_move);
1243                 let moves = hiddenboard.history({ verbose: true });
1244                 last_move = moves.pop();
1245                 highlight_from = last_move.from;
1246                 highlight_to = last_move.to;
1247         } else {
1248                 highlight_from = highlight_to = undefined;
1249         }
1250         update_board_highlight();
1251
1252         if (data['failed']) {
1253                 document.getElementById("score").textContent = "No analysis for this move";
1254                 document.getElementById("pvtitle").textContent = "PV:";
1255                 document.getElementById("pv").replaceChildren();
1256                 document.getElementById("searchstats").innerHTML = "&nbsp;";
1257                 document.getElementById("refutationlines").replaceChildren();
1258                 document.getElementById("whiteclock").replaceChildren();
1259                 document.getElementById("blackclock").replaceChildren();
1260                 refutation_lines = [];
1261                 refutation_lines_base_fen = null;
1262                 update_refutation_lines();
1263                 clear_arrows();
1264                 update_displayed_line();
1265                 update_move_highlight();
1266                 return;
1267         }
1268
1269         if (clock_timer !== null) {
1270                 clearTimeout(clock_timer);
1271         }
1272         update_clock();
1273
1274         // The score.
1275         if (current_display_line && !current_display_line_is_history) {
1276                 let score;
1277                 if (current_display_line.scores && current_display_line.scores.length > 0) {
1278                         for (let i = 0; i < current_display_line.scores.length; ++i) {
1279                                 if (current_display_move < current_display_line.scores[i].first_move) {
1280                                         break;
1281                                 }
1282                                 score = current_display_line.scores[i].score;
1283                         }
1284                 }
1285                 if (score) {
1286                         document.getElementById("score").textContent = format_long_score(score);
1287                 } else {
1288                         document.getElementById("score").textContent = "No score for this line";
1289                 }
1290         } else if (data['score']) {
1291                 document.getElementById("score").textContent = format_long_score(data['score']);
1292         }
1293
1294         // The search stats.
1295         if (data['searchstats']) {
1296                 document.getElementById("searchstats").textContent = data['searchstats'];
1297         } else if (data['nodes'] && data['nps'] && data['depth']) {
1298                 let stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
1299                 if (data['seldepth']) {
1300                         stats += ' (' + data['seldepth'] + ' selective)';
1301                 }
1302                 if (data['tbhits'] && data['tbhits'] > 0) {
1303                         if (data['tbhits'] == 1) {
1304                                 stats += ', one Syzygy hit';
1305                         } else {
1306                                 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
1307                         }
1308                 }
1309
1310                 document.getElementById("searchstats").textContent = stats;
1311         } else {
1312                 document.getElementById("searchstats").textContent = "";
1313         }
1314         if (admin_password !== null) {
1315                 document.getElementById("searchstats").innerHTML += " | <span style=\"color: red;\">ADMIN MODE (if password is right)</span>";
1316         }
1317
1318         // Update the board itself.
1319         base_fen = data['position']['fen'];
1320         update_displayed_line();
1321
1322         // Print the PV.
1323         document.getElementById("pvtitle").textContent = "PV:";
1324
1325         let scores = [{ first_move: -1, score: data['score'] }];
1326         document.getElementById("pv").replaceChildren(add_pv(data['position']['fen'], data['pv'], scores, 0));
1327
1328         // Update the PV arrow.
1329         clear_arrows();
1330         let toplay = find_toplay(data['position']['fen']);
1331         if (data['pv'].length >= 1) {
1332                 let hiddenboard = new Chess(base_fen);
1333
1334                 // draw a continuation arrow as long as it's the same piece
1335                 let last_to;
1336                 for (let i = 0; i < data['pv'].length; i += 2) {
1337                         let move = patch_move(hiddenboard.move(data['pv'][i]));
1338
1339                         if ((i >= 2 && move.from != last_to) ||
1340                              interfering_arrow(move.from, move.to)) {
1341                                 break;
1342                         }
1343                         create_arrow(move.from, move.to, '#f66', 6, 20);
1344                         last_to = move.to;
1345                         hiddenboard.move(data['pv'][i + 1]);  // To keep continuity.
1346                 }
1347
1348                 let alt_moves = find_nonstupid_moves(data, 30, toplay === 'b');
1349                 for (let i = 1; i < alt_moves.length && i < 3; ++i) {
1350                         hiddenboard = new Chess(base_fen);
1351                         let move = patch_move(hiddenboard.move(alt_moves[i]));
1352                         if (move !== null) {
1353                                 create_arrow(move.from, move.to, '#f66', 1, 10);
1354                         }
1355                 }
1356         }
1357
1358         // See if all semi-reasonable moves have only one possible response.
1359         if (data['pv'].length >= 2) {
1360                 let nonstupid_moves = find_nonstupid_moves(data, 300, toplay === 'b');
1361                 let hiddenboard = new Chess(base_fen);
1362                 hiddenboard.move(data['pv'][0]);
1363                 let response = hiddenboard.move(data['pv'][1]);
1364                 for (let i = 0; i < nonstupid_moves.length; ++i) {
1365                         if (nonstupid_moves[i] == data['pv'][0]) {
1366                                 // ignore the PV move for refutation lines.
1367                                 continue;
1368                         }
1369                         if (!data['refutation_lines'] ||
1370                             !data['refutation_lines'][nonstupid_moves[i]] ||
1371                             !data['refutation_lines'][nonstupid_moves[i]]['pv'] ||
1372                             data['refutation_lines'][nonstupid_moves[i]]['pv'].length < 2) {
1373                                 // Incomplete PV, abort.
1374                                 response = undefined;
1375                                 break;
1376                         }
1377                         let line = data['refutation_lines'][nonstupid_moves[i]];
1378                         hiddenboard = new Chess(base_fen);
1379                         hiddenboard.move(line['pv'][0]);
1380                         let this_response = hiddenboard.move(line['pv'][1]);
1381                         if (this_response === null) {
1382                                 console.log("BUG: ", i);
1383                                 console.log(data);
1384                                 console.log(line['pv']);
1385                         }
1386                         if (response.from !== this_response.from || response.to !== this_response.to) {
1387                                 // Different response depending on lines, abort.
1388                                 response = undefined;
1389                                 break;
1390                         }
1391                 }
1392
1393                 if (nonstupid_moves.length > 0 && response !== undefined) {
1394                         create_arrow(response.from, response.to, '#66f', 6, 20);
1395                 }
1396         }
1397
1398         // Update the refutation lines.
1399         base_fen = data['position']['fen'];
1400         if (hash_refutation_lines === null) {
1401                 refutation_lines = data['refutation_lines'];
1402                 refutation_lines_base_fen = base_fen;
1403         }
1404         update_refutation_lines();
1405
1406         // Update the sparkline last, since its size depends on how everything else reflowed.
1407         update_sparkline(data);
1408 }
1409
1410 function update_sparkline(data) {
1411         let scorespark = document.getElementById('scoresparkcontainer');
1412         scorespark.textContent = '';
1413         if (data && data['score_history']) {
1414                 let first_move_num = undefined;
1415                 for (let halfmove_num in data['score_history']) {
1416                         halfmove_num = parseInt(halfmove_num);
1417                         if (first_move_num === undefined || halfmove_num < first_move_num) {
1418                                 first_move_num = halfmove_num;
1419                         }
1420                 }
1421                 if (first_move_num !== undefined) {
1422                         let fen = data['position']['fen'];
1423                         let last_move_num = find_move_num(fen) * 2 - 3;
1424                         if (find_toplay(fen) === 'b') {
1425                                 ++last_move_num;
1426                         }
1427
1428                         // Possibly truncate some moves if we don't have enough width.
1429                         let max_moves = Math.floor(scorespark.getBoundingClientRect().width / 5) - 3;
1430                         if (last_move_num - first_move_num > max_moves) {
1431                                 first_move_num = last_move_num - max_moves;
1432                         }
1433
1434                         let min_score = -1;
1435                         let max_score = 1;
1436                         let last_score = null;
1437                         let scores = [];
1438                         for (let halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1439                                 if (data['score_history'][halfmove_num]) {
1440                                         let score = compute_plot_score(data['score_history'][halfmove_num]);
1441                                         last_score = score;
1442                                         if (score < min_score) min_score = score;
1443                                         if (score > max_score) max_score = score;
1444                                 }
1445                                 scores.push(last_score);
1446                         }
1447                         if (data['score']) {
1448                                 let score = compute_plot_score(data['score']);
1449                                 scores.push(score);
1450                                 if (score < min_score) min_score = score;
1451                                 if (score > max_score) max_score = score;
1452                         }
1453                         if (max_score - min_score < 100) {
1454                                 if (Math.abs(max_score) >= Math.abs(min_score)) {
1455                                         max_score = min_score + 100;
1456                                 } else {
1457                                         min_score = max_score - 100;
1458                                 }
1459                         }
1460
1461                         const h = scorespark.getBoundingClientRect().height;
1462
1463                         let base_y = h - h * min_score / (min_score - max_score);
1464                         for (let i = 0; i < scores.length; ++i) {
1465                                 let rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
1466                                 //rect.setAttributeNS(null, 'stroke', "#000000");
1467                                 rect.setAttributeNS(null, 'x', i * 5)
1468                                 rect.setAttributeNS(null, 'width', 4);
1469                                 let extent = scores[i] * h / (max_score - min_score);
1470                                 if (extent > 0 && extent < 1) {
1471                                         extent = 1;
1472                                 } else if (extent < 0 && extent > -1) {
1473                                         extent = -1;
1474                                 }
1475
1476                                 let color;
1477                                 if (scores[i] === 0) {
1478                                         color = [0.5, 0.5, 0.5];
1479                                         rect.setAttributeNS(null, 'y', base_y);
1480                                         rect.setAttributeNS(null, 'height', 1);
1481                                 } else if (scores[i] > 0) {
1482                                         color = [0.2, 0.4, 0.8];
1483                                         rect.setAttributeNS(null, 'y', base_y - extent);
1484                                         rect.setAttributeNS(null, 'height', extent + 1);
1485                                 } else {
1486                                         color = [1.0, 0.267, 0.267];
1487                                         rect.setAttributeNS(null, 'y', base_y);
1488                                         rect.setAttributeNS(null, 'height', -extent + 1);
1489                                 }
1490                                 let hlcolor = [color[0], color[1], color[2]];
1491                                 if (scores[i] !== 0) { 
1492                                         hlcolor[0] = Math.min(hlcolor[0] * 1.4, 1.0);
1493                                         hlcolor[1] = Math.min(hlcolor[1] * 1.4, 1.0);
1494                                         hlcolor[2] = Math.min(hlcolor[2] * 1.4, 1.0);
1495                                 }
1496                                 rect.style.fill = 'rgb(' + color[0]*100.0 + '%, ' + color[1]*100.0 + '%, ' + color[2]*100.0 + '%)';
1497
1498                                 // score_history contains the Nth _position_, but format_tooltip
1499                                 // wants to format the Nth _move_; thus the -1.
1500                                 const tooltip = format_tooltip(data, i + first_move_num - 1);
1501                                 rect.addEventListener('mouseenter', (e) => draw_hover(e, hlcolor, tooltip));
1502                                 rect.addEventListener('mousemove', (e) => draw_hover(e, hlcolor, tooltip));
1503                                 rect.addEventListener('mouseleave', (e) => hide_hover(e, color));
1504                                 rect.addEventListener('click', (e) => { hide_hover(e, color); show_line(0, i + first_move_num - 1) });
1505                                 scorespark.appendChild(rect);
1506                         }
1507                 }
1508         }
1509 }
1510
1511 function draw_hover(e, color, tooltip) {
1512         e.target.style.fill = 'rgb(' + color[0]*100.0 + '%, ' + color[1]*100.0 + '%, ' + color[2]*100.0 + '%)';
1513
1514         let hover = document.getElementById('sparklinehover');
1515         hover.textContent = tooltip;
1516         hover.style.display = 'initial';
1517
1518         let left = Math.max(e.pageX + 10, window.pageXOffset);
1519         let top = Math.max(e.pageY - hover.getBoundingClientRect().height, window.pageYOffset);
1520         left = Math.min(left, window.pageXOffset + document.documentElement.clientWidth - hover.getBoundingClientRect().width);
1521
1522         hover.style.left = left + 'px';
1523         hover.style.top = top + 'px';
1524
1525 }
1526 function hide_hover(e, color) {
1527         e.target.style.fill = 'rgb(' + color[0]*100.0 + '%, ' + color[1]*100.0 + '%, ' + color[2]*100.0 + '%)';
1528         document.getElementById('sparklinehover').style.display = 'none';
1529 }
1530
1531 /**
1532  * @param {number} num_viewers
1533  */
1534 function update_num_viewers(num_viewers) {
1535         let text = "";
1536         if (num_viewers === null) {
1537                 text = "";
1538         } else if (num_viewers == 1) {
1539                 text = "You are the only current viewer";
1540         } else {
1541                 text = num_viewers + " current viewers";
1542         }
1543         if (display_fen !== null) {
1544                 let counter = Math.floor(display_fen.split(" ")[4] / 2);
1545                 if (counter >= 20) {
1546                         text = text.replace("current ", "");
1547                         text += " | 50-move rule: " + counter;
1548                 }
1549         }
1550         document.getElementById("numviewers").textContent = text;
1551 }
1552
1553 function update_clock() {
1554         clock_timer = null;
1555
1556         let data = displayed_analysis_data || current_analysis_data;
1557         if (!data) return;
1558
1559         if (data['position']) {
1560                 let result = data['position']['result'];
1561                 if (result === '1-0') {
1562                         document.getElementById("whiteclock").textContent = "1";
1563                         document.getElementById("blackclock").textContent = "0";
1564                         document.getElementById("whiteclock").classList.remove("running-clock");
1565                         document.getElementById("blackclock").classList.remove("running-clock");
1566                         return;
1567                 }
1568                 if (result === '1/2-1/2') {
1569                         document.getElementById("whiteclock").textContent = "1/2";
1570                         document.getElementById("blackclock").textContent = "1/2";
1571                         document.getElementById("whiteclock").classList.remove("running-clock");
1572                         document.getElementById("blackclock").classList.remove("running-clock");
1573                         return;
1574                 }       
1575                 if (result === '0-1') {
1576                         document.getElementById("whiteclock").textContent = "0";
1577                         document.getElementById("blackclock").textContent = "1";
1578                         document.getElementById("whiteclock").classList.remove("running-clock");
1579                         document.getElementById("blackclock").classList.remove("running-clock");
1580                         return;
1581                 }
1582         }
1583
1584         let white_clock_ms = null;
1585         let black_clock_ms = null;
1586
1587         // Static clocks.
1588         if (data['position'] &&
1589             data['position']['white_clock'] &&
1590             data['position']['black_clock']) {
1591                 white_clock_ms = data['position']['white_clock'] * 1000;
1592                 black_clock_ms = data['position']['black_clock'] * 1000;
1593         }
1594
1595         // Dynamic clock (only one, obviously).
1596         let color;
1597         if (data['position']['white_clock_target']) {
1598                 color = "white";
1599                 document.getElementById("whiteclock").classList.add("running-clock");
1600                 document.getElementById("blackclock").classList.remove("running-clock");
1601         } else if (data['position']['black_clock_target']) {
1602                 color = "black";
1603                 document.getElementById("whiteclock").classList.remove("running-clock");
1604                 document.getElementById("blackclock").classList.add("running-clock");
1605         } else {
1606                 document.getElementById("whiteclock").classList.remove("running-clock");
1607                 document.getElementById("blackclock").classList.remove("running-clock");
1608         }
1609         let remaining_ms;
1610         if (color) {
1611                 let now = new Date().getTime() + client_clock_offset_ms;
1612                 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1613                 if (color === "white") {
1614                         white_clock_ms = remaining_ms;
1615                 } else {
1616                         black_clock_ms = remaining_ms;
1617                 }
1618         }
1619
1620         if (white_clock_ms === null || black_clock_ms === null) {
1621                 document.getElementById("whiteclock").replaceChildren();
1622                 document.getElementById("blackclock").replaceChildren();
1623                 return;
1624         }
1625
1626         // If either player has twenty minutes or less left, add the second counters.
1627         // This matches what DGT clocks do.
1628         let show_seconds = (white_clock_ms < 60 * 20 * 1000 || black_clock_ms < 60 * 20 * 1000);
1629
1630         if (color && remaining_ms > 0) {
1631                 // See when the clock will change next, and update right after that.
1632                 let next_update_ms;
1633                 if (show_seconds) {
1634                         next_update_ms = remaining_ms % 1000 + 100;
1635                 } else {
1636                         next_update_ms = remaining_ms % 60000 + 100;
1637                 }
1638                 clock_timer = setTimeout(update_clock, next_update_ms);
1639         }
1640
1641         document.getElementById("whiteclock").textContent = format_clock(white_clock_ms, show_seconds);
1642         document.getElementById("blackclock").textContent = format_clock(black_clock_ms, show_seconds);
1643 }
1644
1645 /**
1646  * @param {number} remaining_ms
1647  * @param {boolean} show_seconds
1648  */
1649 function format_clock(remaining_ms, show_seconds) {
1650         if (remaining_ms <= 0) {
1651                 if (show_seconds) {
1652                         return "00:00:00";
1653                 } else {
1654                         return "00:00";
1655                 }
1656         }
1657
1658         let remaining = Math.floor(remaining_ms / 1000);
1659         let seconds = remaining % 60;
1660         remaining = (remaining - seconds) / 60;
1661         let minutes = remaining % 60;
1662         remaining = (remaining - minutes) / 60;
1663         let hours = remaining;
1664         if (show_seconds) {
1665                 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1666         } else {
1667                 return format_2d(hours) + ":" + format_2d(minutes);
1668         }
1669 }
1670
1671 /**
1672  * @param {number} x
1673  */
1674 function format_2d(x) {
1675         if (x >= 10) {
1676                 return x;
1677         } else {
1678                 return "0" + x;
1679         }
1680 }
1681
1682 /**
1683  * @param {string} move
1684  * @param {number} move_num Move number of this move.
1685  * @param {boolean} white_to_play Whether white is to play this move.
1686  */
1687 function format_move_with_number(move, move_num, white_to_play) {
1688         let ret;
1689         if (white_to_play) {
1690                 ret = move_num + '. ';
1691         } else {
1692                 ret = move_num + '… ';
1693         }
1694         ret += move;
1695         return ret;
1696 }
1697
1698 /**
1699  * @param {string} move
1700  * @param {number} halfmove_num Half-move number that is to be played,
1701  *   starting from 0.
1702  */
1703 function format_halfmove_with_number(move, halfmove_num) {
1704         return format_move_with_number(
1705                 move,
1706                 Math.floor(halfmove_num / 2) + 1,
1707                 halfmove_num % 2 == 0);
1708 }
1709
1710 /**
1711  * @param {Object} data
1712  * @param {number} halfmove_num
1713  */
1714 function format_tooltip(data, halfmove_num) {
1715         if (data['score_history'][halfmove_num + 1] ||
1716             (halfmove_num + 1) === data['position']['history'].length) {
1717                 // Position is in the history, or it is the current position
1718                 // (which is implicitly tacked onto the history).
1719                 let move;
1720                 let short_score;
1721                 if ((halfmove_num + 1) === data['position']['history'].length) {
1722                         move = data['position']['last_move'];
1723                         short_score = format_short_score(data['score']);
1724                 } else {
1725                         move = data['position']['history'][halfmove_num];
1726                         short_score = format_short_score(data['score_history'][halfmove_num + 1]);
1727                 }
1728                 if (halfmove_num === -1) {
1729                         return "Start position: " + short_score;
1730                 } else {
1731                         let move_with_number = format_halfmove_with_number(move, halfmove_num);
1732                         return "After " + move_with_number + ": " + short_score;
1733                 }
1734         } else {
1735                 for (let i = halfmove_num; i --> -1; ) {
1736                         if (data['score_history'][i]) {
1737                                 let move = data['position']['history'][i];
1738                                 if (i === -1) {
1739                                         return "[Analysis kept from start position]";
1740                                 } else {
1741                                         return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1742                                 }
1743                         }
1744                 }
1745         }
1746 }
1747
1748 /**
1749  * @param {boolean} truncate_history
1750  */
1751 function set_truncate_history(truncate_history) {
1752         truncate_display_history = truncate_history;
1753         update_refutation_lines();
1754 }
1755 window['set_truncate_history'] = set_truncate_history;
1756
1757 /**
1758  * @param {number} line_num
1759  * @param {number} move_num
1760  */
1761 function show_line(line_num, move_num) {
1762         if (line_num == -1) {
1763                 current_display_line = null;
1764                 current_display_move = null;
1765                 hash_refutation_lines = null;
1766                 refutation_lines_base_fen = base_fen;
1767                 if (displayed_analysis_data) {
1768                         // TODO: Support exiting to history position if we are in an
1769                         // analysis line of a history position.
1770                         displayed_analysis_data = null;
1771                 }
1772                 update_board();
1773                 return;
1774         } else {
1775                 current_display_line = {...display_lines[line_num]};  // Shallow clone.
1776                 current_display_move = move_num + current_display_line.start_display_move_num;
1777         }
1778         current_display_line_is_history = (line_num == 0);
1779
1780         update_historic_analysis();
1781         update_displayed_line();
1782         update_board_highlight();
1783         update_move_highlight();
1784         redraw_arrows();
1785 }
1786 window['show_line'] = show_line;
1787
1788 function prev_move() {
1789         if (current_display_line &&
1790             current_display_move >= current_display_line.start_display_move_num) {
1791                 --current_display_move;
1792         }
1793         update_historic_analysis();
1794         update_displayed_line();
1795         update_move_highlight();
1796 }
1797 window['prev_move'] = prev_move;
1798
1799 function next_move() {
1800         if (current_display_line &&
1801             current_display_move < current_display_line.pv.length - 1) {
1802                 ++current_display_move;
1803         }
1804         update_historic_analysis();
1805         update_displayed_line();
1806         update_move_highlight();
1807 }
1808 window['next_move'] = next_move;
1809
1810 function next_game() {
1811         if (current_games === null) {
1812                 return;
1813         }
1814
1815         // Try to find the game we are currently looking at.
1816         for (let game_num = 0; game_num < current_games.length; ++game_num) {
1817                 let game = current_games[game_num];
1818                 if (game['url'] === backend_url) {
1819                         let next_game_num = (game_num + 1) % current_games.length;
1820                         switch_backend(current_games[next_game_num]);
1821                         return;
1822                 }
1823         }
1824
1825         // Couldn't find it; give up.
1826 }
1827
1828 function update_historic_analysis() {
1829         if (!current_display_line_is_history) {
1830                 return;
1831         }
1832         if (current_display_move == current_display_line.pv.length - 1) {
1833                 displayed_analysis_data = null;
1834                 update_board();
1835         }
1836
1837         // Fetch old analysis for this line if it exists.
1838         let hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pv, current_display_move);
1839         let filename = "/history/move" + (current_display_move + 1) + "-" +
1840                 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1841
1842         let handle_err = () => {
1843                 displayed_analysis_data = {'failed': true};
1844                 update_board();
1845         };
1846
1847         current_historic_xhr = new AbortController();
1848         const signal = current_analysis_xhr.signal;
1849         fetch(filename, { signal })
1850                 .then((response) => response.json().then(data => ({ok: response.ok, json: data})))  // ick
1851                 .then((obj) => {
1852                         if (!obj.ok) {
1853                                 handle_err();
1854                                 return;
1855                         }
1856                         displayed_analysis_data = obj.json;
1857                         update_board();
1858                 })
1859                 .catch((err) => {
1860                         if (err.name === 'AbortError') {
1861                                 // Aborted because we are switching backends. Abandon and don't retry,
1862                                 // because another one is already started for us.
1863                         } else {
1864                                 console.log(err);
1865                                 handle_err();
1866                         }
1867                 });
1868 }
1869
1870 /**
1871  * @param {string} fen
1872  */
1873 function update_imbalance(fen) {
1874         let imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1875         for (const c of fen) {
1876                 if (c === ' ') {
1877                         // End of board
1878                         break;
1879                 }
1880                 if (c != c.toUpperCase()) {
1881                         --imbalance[c];
1882                 } else if (c != c.toLowerCase()) {
1883                         ++imbalance[c.toLowerCase()];
1884                 }
1885         }
1886
1887         let white_imbalance = document.getElementById('whiteimbalance');
1888         let black_imbalance = document.getElementById('blackimbalance');
1889         white_imbalance.textContent = '';
1890         black_imbalance.textContent = '';
1891         for (let piece in imbalance) {
1892                 for (let i = 0; i < imbalance[piece]; ++i) {
1893                         let i1 = document.createElement('img');
1894                         i1.src = svg_pieces['w' + piece.toUpperCase()];
1895                         i1.setAttribute('alt', piece.toUpperCase());
1896                         i1.classList.add('imbalance-piece');
1897                         white_imbalance.appendChild(i1);
1898
1899                         let i2 = document.createElement('img');
1900                         i2.src = svg_pieces['b' + piece.toUpperCase()];
1901                         i2.setAttribute('alt', piece.toUpperCase());
1902                         i2.classList.add('imbalance-inverted-piece');
1903                         white_imbalance.appendChild(i2);
1904                 }
1905                 for (let i = 0; i < -imbalance[piece]; ++i) {
1906                         let i1 = document.createElement('img');
1907                         i1.src = svg_pieces['b' + piece.toUpperCase()];
1908                         i1.setAttribute('alt', piece.toUpperCase());
1909                         i1.classList.add('imbalance-piece');
1910                         black_imbalance.appendChild(i1);
1911
1912                         let i2 = document.createElement('img');
1913                         i2.src = svg_pieces['w' + piece.toUpperCase()];
1914                         i2.setAttribute('alt', piece.toUpperCase());
1915                         i2.classList.add('imbalance-inverted-piece');
1916                         black_imbalance.appendChild(i2);
1917                 }
1918         }
1919 }
1920
1921 /** Mark the currently selected move in red.
1922  * Also replaces the PV with the current displayed line if it's not shown
1923  * anywhere else on the screen.
1924  */
1925 function update_move_highlight() {
1926         if (highlighted_move !== null) {
1927                 highlighted_move.classList.remove('highlight'); 
1928         }
1929         if (current_display_line) {
1930                 let display_line_num = find_display_line_matching_num();
1931                 if (display_line_num === null) {
1932                         // Replace the PV with the (complete) line.
1933                         document.getElementById("pvtitle").textContent = "Exploring:";
1934                         current_display_line.start_display_move_num = 0;
1935                         display_lines.push(current_display_line);
1936                         document.getElementById("pv").replaceChildren(print_pv(display_lines.length - 1, null));  // FIXME
1937                         display_line_num = display_lines.length - 1;
1938
1939                         // Clear out the PV, so it's not selected by anything later.
1940                         display_lines[1].pv = [];
1941                 }
1942
1943                 highlighted_move = document.getElementById("automove" + display_line_num + "-" + (current_display_move - current_display_line.start_display_move_num));
1944                 if (highlighted_move !== null) {
1945                         highlighted_move.classList.add('highlight');
1946                 }
1947         }
1948 }
1949
1950 /**
1951  * See if the current displayed line is identical to any of the ones
1952  * we have on screen. (It might not be if e.g. the analysis reloaded
1953  * since we started looking.)
1954  *
1955  * @return {?number}
1956  */
1957 function find_display_line_matching_num() {
1958         for (let i = 0; i < display_lines.length; ++i) {
1959                 let line = display_lines[i];
1960                 if (line.start_display_move_num > 0) continue;
1961                 if (current_display_line.start_fen !== line.start_fen) continue;
1962                 if (current_display_line.pv.length !== line.pv.length) continue;
1963                 let ok = true;
1964                 for (let j = 0; j < line.pv.length; ++j) {
1965                         if (current_display_line.pv[j] !== line.pv[j]) {
1966                                 ok = false;
1967                                 break;
1968                         }
1969                 }
1970                 if (ok) {
1971                         return i;
1972                 }
1973         }
1974         return null;
1975 }
1976
1977 /** Update the board based on the currently displayed line.
1978  * 
1979  * TODO: This should really be called only whenever something changes,
1980  * instead of all the time.
1981  */
1982 function update_displayed_line() {
1983         if (current_display_line === null) {
1984                 document.getElementById("linenav").style.display = 'none';
1985                 document.getElementById("linemsg").style.display = 'revert';
1986                 display_fen = base_fen;
1987                 set_board_position(base_fen);
1988                 update_imbalance(base_fen);
1989                 return;
1990         }
1991
1992         document.getElementById("linenav").style.display = 'revert';
1993         document.getElementById("linemsg").style.display = 'none';
1994
1995         if (current_display_move <= 0) {
1996                 document.getElementById("prevmove").textContent = "Previous";
1997         } else {
1998                 document.getElementById("prevmove").innerHTML = "<a href=\"javascript:prev_move();\">Previous</a></span>";
1999         }
2000         if (current_display_move == current_display_line.pv.length - 1) {
2001                 document.getElementById("nextmove").textContent = "Next";
2002         } else {
2003                 document.getElementById("nextmove").innerHTML = "<a href=\"javascript:next_move();\">Next</a></span>";
2004         }
2005
2006         let hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pv, current_display_move);
2007         set_board_position(hiddenboard.fen());
2008         if (display_fen !== hiddenboard.fen() && !current_display_line_is_history) {
2009                 // Fire off a hash request, since we're now off the main position
2010                 // and it just changed.
2011                 explore_hash(hiddenboard.fen());
2012         }
2013         display_fen = hiddenboard.fen();
2014         update_imbalance(hiddenboard.fen());
2015 }
2016
2017 function set_board_position(new_fen) {
2018         board_is_animating = true;
2019         let old_fen = board.fen();
2020         let animate = old_fen !== '8/8/8/8/8/8/8/';
2021         board.position(new_fen, animate);
2022         if (board.fen() === old_fen) {
2023                 board_is_animating = false;
2024         }
2025 }
2026
2027 /**
2028  * @param {boolean} param_enable_sound
2029  */
2030 function set_sound(param_enable_sound) {
2031         enable_sound = param_enable_sound;
2032         if (enable_sound) {
2033                 document.getElementById("soundon").innerHTML = "<strong>On</strong>";
2034                 document.getElementById("soundoff").innerHTML = "<a href=\"javascript:set_sound(false)\">Off</a>";
2035
2036                 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
2037                 // and also preload the file since the user has selected audio.
2038                 let ding = document.getElementById('ding');
2039                 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
2040                         ding.src = 'ding.opus';
2041                         ding.load();
2042                 }
2043         } else {
2044                 document.getElementById("soundon").innerHTML = "<a href=\"javascript:set_sound(true)\">On</a>";
2045                 document.getElementById("soundoff").innerHTML = "<strong>Off</strong>";
2046         }
2047         if (supports_html5_storage()) {
2048                 window['localStorage']['enable_sound'] = enable_sound ? 1 : 0;
2049         }
2050 }
2051 window['set_sound'] = set_sound;
2052
2053 /** Send off a hash probe request to the backend.
2054  * @param {string} fen
2055  */
2056 function explore_hash(fen) {
2057         // If we already have a backend response going, abort it.
2058         if (current_hash_xhr) {
2059                 current_hash_xhr.abort();
2060         }
2061         if (current_hash_display_timer) {
2062                 clearTimeout(current_hash_display_timer);
2063                 current_hash_display_timer = null;
2064         }
2065         document.getElementById("refutationlines").replaceChildren();
2066
2067         current_hash_xhr = new AbortController();
2068         const signal = current_analysis_xhr.signal;
2069         fetch(backend_hash_url + "?fen=" + fen, { signal })
2070                 .then((response) => response.json())
2071                 .then((data) => { show_explore_hash_results(data, fen); })
2072                 .catch((err) => {
2073                         // Truncate the lines, since we already cleared the display.
2074                         display_lines = [ display_lines[0], display_lines[1] ];
2075                         update_move_highlight();
2076                 });
2077 }
2078
2079 /** Process the JSON response from a hash probe request.
2080  * @param {!Object} data
2081  * @param {string} fen
2082  */
2083 function show_explore_hash_results(data, fen) {
2084         if (board_is_animating) {
2085                 // Updating while the animation is still going causes
2086                 // the animation to jerk. This is pretty crude, but it will do.
2087                 current_hash_display_timer = setTimeout(function() { show_explore_hash_results(data, fen); }, 100);
2088                 return;
2089         }
2090         current_hash_display_timer = null;
2091         hash_refutation_lines = data['lines'];
2092         refutation_lines_base_fen = fen;
2093         update_board();
2094 }
2095
2096 // almost all of this stuff comes from the chessboard.js example page
2097 function onDragStart(source, piece, position, orientation) {
2098         let pseudogame = new Chess(display_fen);
2099         if (pseudogame.game_over() === true ||
2100             (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
2101             (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
2102                 return false;
2103         }
2104
2105         recommended_move = get_best_move(pseudogame, source, null, pseudogame.turn() === 'b');
2106         if (recommended_move) {
2107                 let squareEl = document.querySelector('#board .square-' + recommended_move.to);
2108                 squareEl.classList.add('highlight1-32417');
2109         }
2110         return true;
2111 }
2112
2113 function mousedownSquare(e) {
2114         if (!e.target || !e.target.getAttribute('data-square')) {
2115                 return;
2116         }
2117
2118         reverse_dragging_from = null;
2119         let square = e.target.getAttribute('data-square');
2120
2121         let pseudogame = new Chess(display_fen);
2122         if (pseudogame.game_over() === true) {
2123                 return;
2124         }
2125
2126         // If the square is empty, or has a piece of the side not to move,
2127         // we handle it. If not, normal piece dragging will take it.
2128         let position = board.position();
2129         if (!position.hasOwnProperty(square) ||
2130             (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
2131             (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
2132                 reverse_dragging_from = square;
2133                 recommended_move = get_best_move(pseudogame, null, square, pseudogame.turn() === 'b');
2134                 if (recommended_move) {
2135                         let squareEl = document.querySelector('#board .square-' + recommended_move.from);
2136                         squareEl.classList.add('highlight1-32417');
2137                         squareEl = document.querySelector('#board .square-' + recommended_move.to);
2138                         squareEl.classList.add('highlight1-32417');
2139                 }
2140         }
2141 }
2142
2143 function mouseupSquare(e) {
2144         if (!e.target || !e.target.getAttribute('data-square')) {
2145                 return;
2146         }
2147         if (reverse_dragging_from === null) {
2148                 return;
2149         }
2150         let source = e.target.getAttribute('data-square');
2151         let target = reverse_dragging_from;
2152         reverse_dragging_from = null;
2153         if (onDrop(source, target) !== 'snapback') {
2154                 onSnapEnd(source, target);
2155         }
2156         document.getElementById("board").querySelectorAll('.square-55d63.highlight1-32417').forEach((square) => {
2157                 square.classList.remove('highlight1-32417');
2158         });
2159 }
2160
2161 function get_best_move(game, source, target, invert) {
2162         let moves = game.moves({ verbose: true });
2163         if (source !== null) {
2164                 moves = moves.filter(function(move) { return move.from == source; });
2165         }
2166         if (target !== null) {
2167                 moves = moves.filter(function(move) { return move.to == target; });
2168         }
2169         if (moves.length == 0) {
2170                 return null;
2171         }
2172         if (moves.length == 1) {
2173                 return moves[0];
2174         }
2175
2176         // More than one move. Use the display lines (if we have them)
2177         // to disambiguate; otherwise, we have no information.
2178         let move_hash = {};
2179         for (let i = 0; i < moves.length; ++i) {
2180                 move_hash[moves[i].san] = moves[i];
2181         }
2182
2183         // See if we're already exploring some line.
2184         if (current_display_line &&
2185             current_display_move < current_display_line.pv.length - 1) {
2186                 let first_move = current_display_line.pv[current_display_move + 1];
2187                 if (move_hash[first_move]) {
2188                         return move_hash[first_move];
2189                 }
2190         }
2191
2192         // History and PV take priority over the display lines.
2193         for (let i = 0; i < 2; ++i) {
2194                 let line = display_lines[i];
2195                 let first_move = line.pv[line.start_display_move_num];
2196                 if (move_hash[first_move]) {
2197                         return move_hash[first_move];
2198                 }
2199         }
2200
2201         let best_move = null;
2202         let best_move_score = null;
2203
2204         for (let move in refutation_lines) {
2205                 let line = refutation_lines[move];
2206                 if (!line['score']) {
2207                         continue;
2208                 }
2209                 let first_move = line['pv'][0];
2210                 if (move_hash[first_move]) {
2211                         let score = compute_score_sort_key(line['score'], line['depth'], invert);
2212                         if (best_move_score === null || score > best_move_score) {
2213                                 best_move = move_hash[first_move];
2214                                 best_move_score = score;
2215                         }
2216                 }
2217         }
2218         return best_move;
2219 }
2220
2221 function onDrop(source, target) {
2222         if (source === target) {
2223                 if (recommended_move === null) {
2224                         return 'snapback';
2225                 } else {
2226                         // Accept the move. It will be changed in onSnapEnd.
2227                         return;
2228                 }
2229         } else {
2230                 // Suggestion not asked for.
2231                 recommended_move = null;
2232         }
2233
2234         // see if the move is legal
2235         let pseudogame = new Chess(display_fen);
2236         let move = pseudogame.move({
2237                 from: source,
2238                 to: target,
2239                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
2240         });
2241
2242         // illegal move
2243         if (move === null) return 'snapback';
2244 }
2245
2246 /**
2247  * If we are in admin mode, send this move to the backend.
2248  *
2249  * @param {string} fen
2250  * @param {string} move
2251  */
2252 function send_chosen_move(fen, move) {
2253         if (admin_password !== null) {
2254                 let history = current_analysis_data['position']['history'];
2255                 let url = '/manual-override.pl';
2256                 url += '?fen=' + encodeURIComponent(fen);
2257                 url += '&history=' + encodeURIComponent(JSON.stringify(history));
2258                 url += '&move=' + encodeURIComponent(move);
2259                 url += '&player_w=' + encodeURIComponent(current_analysis_data['position']['player_w']);
2260                 url += '&player_b=' + encodeURIComponent(current_analysis_data['position']['player_b']);
2261                 url += '&password=' + encodeURIComponent(admin_password);
2262
2263                 console.log(fen, history);
2264                 fetch(url);  // Ignore the result.
2265         }
2266 }
2267
2268 function onSnapEnd(source, target) {
2269         if (source === target && recommended_move !== null) {
2270                 source = recommended_move.from;
2271                 target = recommended_move.to;
2272         }
2273         recommended_move = null;
2274         let pseudogame = new Chess(display_fen);
2275         let move = pseudogame.move({
2276                 from: source,
2277                 to: target,
2278                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
2279         });
2280
2281         if (admin_password !== null) {
2282                 send_chosen_move(display_fen, move.san);
2283                 return;
2284         }
2285
2286         // Move ahead on the line we're on -- this includes history if we've
2287         // gone backwards.
2288         if (current_display_line &&
2289             current_display_move < current_display_line.pv.length - 1 &&
2290             current_display_line.pv[current_display_move + 1] === move.san) {
2291                 next_move();
2292                 return;
2293         }
2294
2295         // Walk down the displayed lines until we find one that starts with
2296         // this move, then select that. Note that this gives us a good priority
2297         // order (PV, then multi-PV lines; history was already dealt with above,
2298         // as it's the only line that originates backwards).
2299         for (let i = 1; i < display_lines.length; ++i) {
2300                 if (i == 1 && current_display_line) {
2301                         // Do not choose PV if not on it.
2302                         continue;
2303                 }
2304                 let line = display_lines[i];
2305                 if (line.pv[line.start_display_move_num] === move.san) {
2306                         show_line(i, 0);
2307                         return;
2308                 }
2309         }
2310
2311         // Shouldn't really be here if we have hash probes, but there's really
2312         // nothing we can do.
2313         // FIXME: Just make a new line, probably (even if we don't have hash moves).
2314         // As it is, we can actually drag (but not click) such a move in the UI,
2315         // but it has no effect on what we're probing.
2316 }
2317 // End of dragging-related code.
2318
2319 function fmt_cp(v) {
2320         if (v === 0) {
2321                 return "0.00";
2322         } else if (v > 0) {
2323                 return "+" + (v / 100).toFixed(2);
2324         } else {
2325                 v = -v;
2326                 return "-" + (v / 100).toFixed(2);
2327         }
2328 }
2329
2330 function format_short_score(score) {
2331         if (!score) {
2332                 return "???";
2333         }
2334         if (score[0] === 'T' || score[0] === 't') {
2335                 let ret = "TB\u00a0";
2336                 if (score[2]) {  // Is a bound.
2337                         ret = score[2] + "\u00a0TB\u00a0";
2338                 }
2339                 if (score[0] === 'T') {
2340                         return ret + Math.ceil(score[1] / 2);
2341                 } else {
2342                         return ret + "-" + Math.ceil(score[1] / 2);
2343                 }
2344         } else if (score[0] === 'M' || score[0] === 'm') {
2345                 let sign = (score[0] === 'm') ? '-' : '';
2346                 if (score[2]) {  // Is a bound.
2347                         return score[2] + "\u00a0M " + sign + score[1];
2348                 } else {
2349                         return "M " + sign + score[1];
2350                 }
2351         } else if (score[0] === 'd') {
2352                 return "TB =0";
2353         } else if (score[0] === 'cp') {
2354                 if (score[2]) {  // Is a bound.
2355                         return score[2] + "\u00a0" + fmt_cp(score[1]);
2356                 } else {
2357                         return fmt_cp(score[1]);
2358                 }
2359         }
2360         return null;
2361 }
2362
2363 function format_long_score(score) {
2364         if (!score) {
2365                 return "???";
2366         }
2367         if (score[0] === 'T') {
2368                 if (score[1] == 0) {
2369                         return "Won for white (tablebase)";
2370                 } else {
2371                         return "White wins in " + Math.ceil(score[1] / 2);
2372                 }
2373         } else if (score[0] === 't') {
2374                 if (score[1] == -1) {
2375                         return "Won for black (tablebase)";
2376                 } else {
2377                         return "Black wins in " + Math.ceil(score[1] / 2);
2378                 }
2379         } else if (score[0] === 'M') {
2380                 if (score[1] == 0) {
2381                         return "White wins by checkmate";
2382                 } else {
2383                         return "White mates in " + score[1];
2384                 }
2385         } else if (score[0] === 'm') {
2386                 if (score[1] == 0) {
2387                         return "Black wins by checkmate";
2388                 } else {
2389                         return "Black mates in " + score[1];
2390                 }
2391         } else if (score[0] === 'd') {
2392                 return "Theoretical draw";
2393         } else if (score[0] === 'cp') {
2394                 return "Score: " + format_short_score(score);
2395         }
2396         return null;
2397 }
2398
2399 function compute_plot_score(score) {
2400         if (score[0] === 'M' || score[0] === 'T') {
2401                 return 500;
2402         } else if (score[0] === 'm' || score[0] === 't') {
2403                 return -500;
2404         } else if (score[0] === 'd') {
2405                 return 0;
2406         } else if (score[0] === 'cp') {
2407                 if (score[1] > 500) {
2408                         return 500;
2409                 } else if (score[1] < -500) {
2410                         return -500;
2411                 } else {
2412                         return score[1];
2413                 }
2414         }
2415         return null;
2416 }
2417
2418 /**
2419  * @param score The score digest tuple.
2420  * @param {?number} depth Depth the move has been computed to, or null.
2421  * @param {boolean} invert Whether black is to play.
2422  * @return {number}
2423  */
2424 function compute_score_sort_key(score, depth, invert) {
2425         let s;
2426         if (!score) {
2427                 return -10000000;
2428         }
2429         if (score[0] === 'T') {
2430                 // White reaches TB win.
2431                 s = 89999 - score[1];
2432         } else if (score[0] === 't') {
2433                 // Black reaches TB win.
2434                 s = -(89999 - score[1]);
2435         } else if (score[0] === 'M') {
2436                 // White mates.
2437                 s = 99999 - score[1];
2438         } else if (score[0] === 'm') {
2439                 // Black mates.
2440                 s = -(99999 - score[1]);
2441         } else if (score[0] === 'd') {
2442                 s = 0;
2443         } else if (score[0] === 'cp') {
2444                 s = score[1];
2445         }
2446         if (s) {
2447                 if (invert) s = -s;
2448                 return s;
2449         } else {
2450                 return null;
2451         }
2452 }
2453
2454 /**
2455  * @param {Object} game
2456  */
2457 function switch_backend(game) {
2458         // Stop looking at historic data.
2459         current_display_line = null;
2460         current_display_move = null;
2461         displayed_analysis_data = null;
2462         if (current_historic_xhr) {
2463                 current_historic_xhr.abort();
2464         }
2465
2466         // If we already have a backend response going, abort it.
2467         if (current_analysis_xhr) {
2468                 current_analysis_xhr.abort();
2469         }
2470         if (current_hash_xhr) {
2471                 current_hash_xhr.abort();
2472         }
2473
2474         // Otherwise, we should have a timer going to start a new one.
2475         // Kill that, too.
2476         if (current_analysis_request_timer) {
2477                 clearTimeout(current_analysis_request_timer);
2478                 current_analysis_request_timer = null;
2479         }
2480         if (current_hash_display_timer) {
2481                 clearTimeout(current_hash_display_timer);
2482                 current_hash_display_timer = null;
2483         }
2484
2485         // Request an immediate fetch with the new backend.
2486         backend_url = game['url'];
2487         backend_hash_url = game['hashurl'];
2488         window.location.hash = '#' + game['id'];
2489         current_analysis_data = null;
2490         ims = 0;
2491         request_update();
2492 }
2493 window['switch_backend'] = switch_backend;
2494
2495 window['flip'] = function() { board.flip(); redraw_arrows(); };
2496 window['set_delay_ms'] = function(ms) { delay_ms = ms; console.log('Delay is now ' + ms + ' ms.'); };
2497
2498 // Mostly from Wikipedia's chess set as of October 2022, but some pieces are from
2499 // the 2013 version, as I like those better (and it matches the 2014 PNGs; nobody
2500 // really likes change, do they?). That is wK, bK, bQ. wQ is also slightly different,
2501 // but not enough to notice.
2502 const svg_pieces = {
2503         'wK': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><g style=%22fill:none;fill-opacity:1;fill-rule:evenodd;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22><path d=%22M 22.5,11.63 L 22.5,6%22 style=%22fill:none;stroke:%23000000;stroke-linejoin:miter%22/><path d=%22M 20,8 L 25,8%22 style=%22fill:none;stroke:%23000000;stroke-linejoin:miter%22/><path d=%22M 22.5,25 C 22.5,25 27,17.5 25.5,14.5 C 25.5,14.5 24.5,12 22.5,12 C 20.5,12 19.5,14.5 19.5,14.5 C 18,17.5 22.5,25 22.5,25%22 style=%22fill:%23ffffff;stroke:%23000000;stroke-linecap:butt;stroke-linejoin:miter%22/><path d=%22M 11.5,37 C 17,40.5 27,40.5 32.5,37 L 32.5,30 C 32.5,30 41.5,25.5 38.5,19.5 C 34.5,13 25,16 22.5,23.5 L 22.5,27 L 22.5,23.5 C 19,16 9.5,13 6.5,19.5 C 3.5,25.5 11.5,29.5 11.5,29.5 L 11.5,37 z %22 style=%22fill:%23ffffff;stroke:%23000000%22/><path d=%22M 11.5,30 C 17,27 27,27 32.5,30%22 style=%22fill:none;stroke:%23000000%22/><path d=%22M 11.5,33.5 C 17,30.5 27,30.5 32.5,33.5%22 style=%22fill:none;stroke:%23000000%22/><path d=%22M 11.5,37 C 17,34 27,34 32.5,37%22 style=%22fill:none;stroke:%23000000%22/></g></svg>',
2504         'wQ': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><g style=%22fill:%23ffffff;stroke:%23000000;stroke-width:1.5;stroke-linejoin:round%22><path d=%22M 9,26 C 17.5,24.5 30,24.5 36,26 L 38.5,13.5 L 31,25 L 30.7,10.9 L 25.5,24.5 L 22.5,10 L 19.5,24.5 L 14.3,10.9 L 14,25 L 6.5,13.5 L 9,26 z%22/><path d=%22M 9,26 C 9,28 10.5,28 11.5,30 C 12.5,31.5 12.5,31 12,33.5 C 10.5,34.5 11,36 11,36 C 9.5,37.5 11,38.5 11,38.5 C 17.5,39.5 27.5,39.5 34,38.5 C 34,38.5 35.5,37.5 34,36 C 34,36 34.5,34.5 33,33.5 C 32.5,31 32.5,31.5 33.5,30 C 34.5,28 36,28 36,26 C 27.5,24.5 17.5,24.5 9,26 z%22/><path d=%22M 11.5,30 C 15,29 30,29 33.5,30%22 style=%22fill:none%22/><path d=%22M 12,33.5 C 18,32.5 27,32.5 33,33.5%22 style=%22fill:none%22/><circle cx=%226%22 cy=%2212%22 r=%222%22/><circle cx=%2214%22 cy=%229%22 r=%222%22/><circle cx=%2222.5%22 cy=%228%22 r=%222%22/><circle cx=%2231%22 cy=%229%22 r=%222%22/><circle cx=%2239%22 cy=%2212%22 r=%222%22/></g></svg>',
2505         'wR': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><g style=%22opacity:1;fill:%23ffffff;fill-opacity:1;fill-rule:evenodd;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 transform=%22translate(0,0.3)%22><path d=%22M 9,39 L 36,39 L 36,36 L 9,36 L 9,39 z %22 style=%22stroke-linecap:butt%22/><path d=%22M 12,36 L 12,32 L 33,32 L 33,36 L 12,36 z %22 style=%22stroke-linecap:butt%22/><path d=%22M 11,14 L 11,9 L 15,9 L 15,11 L 20,11 L 20,9 L 25,9 L 25,11 L 30,11 L 30,9 L 34,9 L 34,14%22 style=%22stroke-linecap:butt%22/><path d=%22M 34,14 L 31,17 L 14,17 L 11,14%22/><path d=%22M 31,17 L 31,29.5 L 14,29.5 L 14,17%22 style=%22stroke-linecap:butt;stroke-linejoin:miter%22/><path d=%22M 31,29.5 L 32.5,32 L 12.5,32 L 14,29.5%22/><path d=%22M 11,14 L 34,14%22 style=%22fill:none;stroke:%23000000;stroke-linejoin:miter%22/></g></svg>',
2506         'wB': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><g style=%22opacity:1;fill:none;fill-rule:evenodd;fill-opacity:1;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 transform=%22translate(0,0.6)%22><g style=%22fill:%23ffffff;stroke:%23000000;stroke-linecap:butt%22><path d=%22M 9,36 C 12.39,35.03 19.11,36.43 22.5,34 C 25.89,36.43 32.61,35.03 36,36 C 36,36 37.65,36.54 39,38 C 38.32,38.97 37.35,38.99 36,38.5 C 32.61,37.53 25.89,38.96 22.5,37.5 C 19.11,38.96 12.39,37.53 9,38.5 C 7.65,38.99 6.68,38.97 6,38 C 7.35,36.54 9,36 9,36 z%22/><path d=%22M 15,32 C 17.5,34.5 27.5,34.5 30,32 C 30.5,30.5 30,30 30,30 C 30,27.5 27.5,26 27.5,26 C 33,24.5 33.5,14.5 22.5,10.5 C 11.5,14.5 12,24.5 17.5,26 C 17.5,26 15,27.5 15,30 C 15,30 14.5,30.5 15,32 z%22/><path d=%22M 25 8 A 2.5 2.5 0 1 1 20,8 A 2.5 2.5 0 1 1 25 8 z%22/></g><path d=%22M 17.5,26 L 27.5,26 M 15,30 L 30,30 M 22.5,15.5 L 22.5,20.5 M 20,18 L 25,18%22 style=%22fill:none;stroke:%23000000;stroke-linejoin:miter%22/></g></svg>',
2507         'wN': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><g style=%22opacity:1;fill:none;fill-opacity:1;fill-rule:evenodd;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 transform=%22translate(0,0.3)%22><path d=%22M 22,10 C 32.5,11 38.5,18 38,39 L 15,39 C 15,30 25,32.5 23,18%22 style=%22fill:%23ffffff;stroke:%23000000%22/><path d=%22M 24,18 C 24.38,20.91 18.45,25.37 16,27 C 13,29 13.18,31.34 11,31 C 9.958,30.06 12.41,27.96 11,28 C 10,28 11.19,29.23 10,30 C 9,30 5.997,31 6,26 C 6,24 12,14 12,14 C 12,14 13.89,12.1 14,10.5 C 13.27,9.506 13.5,8.5 13.5,7.5 C 14.5,6.5 16.5,10 16.5,10 L 18.5,10 C 18.5,10 19.28,8.008 21,7 C 22,7 22,10 22,10%22 style=%22fill:%23ffffff;stroke:%23000000%22/><path d=%22M 9.5 25.5 A 0.5 0.5 0 1 1 8.5,25.5 A 0.5 0.5 0 1 1 9.5 25.5 z%22 style=%22fill:%23000000;stroke:%23000000%22/><path d=%22M 15 15.5 A 0.5 1.5 0 1 1 14,15.5 A 0.5 1.5 0 1 1 15 15.5 z%22 transform=%22matrix(0.866,0.5,-0.5,0.866,9.693,-5.173)%22 style=%22fill:%23000000;stroke:%23000000%22/></g></svg>',
2508         'wP': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><path d=%22m 22.5,9 c -2.21,0 -4,1.79 -4,4 0,0.89 0.29,1.71 0.78,2.38 C 17.33,16.5 16,18.59 16,21 c 0,2.03 0.94,3.84 2.41,5.03 C 15.41,27.09 11,31.58 11,39.5 H 34 C 34,31.58 29.59,27.09 26.59,26.03 28.06,24.84 29,23.03 29,21 29,18.59 27.67,16.5 25.72,15.38 26.21,14.71 26.5,13.89 26.5,13 c 0,-2.21 -1.79,-4 -4,-4 z%22 style=%22opacity:1;fill:%23ffffff;fill-opacity:1;fill-rule:nonzero;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22/></svg>',
2509        'bK': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><g style=%22fill:none;fill-opacity:1;fill-rule:evenodd;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22><path d=%22M 22.5,11.63 L 22.5,6%22 style=%22fill:none;stroke:%23000000;stroke-linejoin:miter%22 id=%22path6570%22/><path d=%22M 22.5,25 C 22.5,25 27,17.5 25.5,14.5 C 25.5,14.5 24.5,12 22.5,12 C 20.5,12 19.5,14.5 19.5,14.5 C 18,17.5 22.5,25 22.5,25%22 style=%22fill:%23000000;fill-opacity:1;stroke-linecap:butt;stroke-linejoin:miter%22/><path d=%22M 11.5,37 C 17,40.5 27,40.5 32.5,37 L 32.5,30 C 32.5,30 41.5,25.5 38.5,19.5 C 34.5,13 25,16 22.5,23.5 L 22.5,27 L 22.5,23.5 C 19,16 9.5,13 6.5,19.5 C 3.5,25.5 11.5,29.5 11.5,29.5 L 11.5,37 z %22 style=%22fill:%23000000;stroke:%23000000%22/><path d=%22M 20,8 L 25,8%22 style=%22fill:none;stroke:%23000000;stroke-linejoin:miter%22/><path d=%22M 32,29.5 C 32,29.5 40.5,25.5 38.03,19.85 C 34.15,14 25,18 22.5,24.5 L 22.51,26.6 L 22.5,24.5 C 20,18 9.906,14 6.997,19.85 C 4.5,25.5 11.85,28.85 11.85,28.85%22 style=%22fill:none;stroke:%23ffffff%22/><path d=%22M 11.5,30 C 17,27 27,27 32.5,30 M 11.5,33.5 C 17,30.5 27,30.5 32.5,33.5 M 11.5,37 C 17,34 27,34 32.5,37%22 style=%22fill:none;stroke:%23ffffff%22/></g></svg>',
2510         'bQ': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns:svg=%22http://www.w3.org/2000/svg%22 xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22 id=%22svg3128%22><defs/><g id=%22layer1%22><path d=%22M 8 12 A 2 2 0 1 1 4,12 A 2 2 0 1 1 8 12 z%22 style=%22opacity:1;fill:%23000000;fill-opacity:1;stroke:%23000000;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 id=%22path5571%22/><path d=%22M 9 13 A 2 2 0 1 1 5,13 A 2 2 0 1 1 9 13 z%22 transform=%22translate(15.5,-5.5)%22 style=%22opacity:1;fill:%23000000;fill-opacity:1;stroke:%23000000;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 id=%22path5573%22/><path d=%22M 9 13 A 2 2 0 1 1 5,13 A 2 2 0 1 1 9 13 z%22 transform=%22translate(32,-1)%22 style=%22opacity:1;fill:%23000000;fill-opacity:1;stroke:%23000000;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 id=%22path5575%22/><path d=%22M 9 13 A 2 2 0 1 1 5,13 A 2 2 0 1 1 9 13 z%22 transform=%22translate(7,-4.5)%22 style=%22opacity:1;fill:%23000000;fill-opacity:1;stroke:%23000000;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 id=%22path5577%22/><path d=%22M 9 13 A 2 2 0 1 1 5,13 A 2 2 0 1 1 9 13 z%22 transform=%22translate(24,-4)%22 style=%22opacity:1;fill:%23000000;fill-opacity:1;stroke:%23000000;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 id=%22path5579%22/><path d=%22M 9,26 C 17.5,24.5 30,24.5 36,26 L 38,14 L 31,25 L 31,11 L 25.5,24.5 L 22.5,9.5 L 19.5,24.5 L 14,10.5 L 14,25 L 7,14 L 9,26 z %22 style=%22fill:%23000000;fill-opacity:1;fill-rule:evenodd;stroke:%23000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:round;stroke-opacity:1%22 id=%22path5581%22/><path d=%22M 9,26 C 9,28 10.5,28 11.5,30 C 12.5,31.5 12.5,31 12,33.5 C 10.5,34.5 10.5,36 10.5,36 C 9,37.5 11,38.5 11,38.5 C 17.5,39.5 27.5,39.5 34,38.5 C 34,38.5 35.5,37.5 34,36 C 34,36 34.5,34.5 33,33.5 C 32.5,31 32.5,31.5 33.5,30 C 34.5,28 36,28 36,26 C 27.5,24.5 17.5,24.5 9,26 z %22 style=%22fill:%23000000;fill-opacity:1;fill-rule:evenodd;stroke:%23000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:round;stroke-opacity:1%22 id=%22path5583%22/><path d=%22M 11.5,30 C 15,29 30,29 33.5,30%22 style=%22fill:none;fill-opacity:0.75;fill-rule:evenodd;stroke:%23ffffff;stroke-width:1px;stroke-linecap:round;stroke-linejoin:round;stroke-opacity:1%22 id=%22path5585%22/><path d=%22M 12,33.5 C 18,32.5 27,32.5 33,33.5%22 style=%22fill:none;fill-opacity:0.75;fill-rule:evenodd;stroke:%23ffffff;stroke-width:1px;stroke-linecap:round;stroke-linejoin:round;stroke-opacity:1%22 id=%22path5587%22/><path d=%22M 10.5,36 C 15.5,35 29,35 34,36%22 style=%22fill:none;fill-opacity:0.75;fill-rule:evenodd;stroke:%23ffffff;stroke-width:1px;stroke-linecap:round;stroke-linejoin:round;stroke-opacity:1%22 id=%22path5589%22/></g></svg>',
2511         'bR': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><g style=%22opacity:1;fill:%23000000;fill-opacity:1;fill-rule:evenodd;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 transform=%22translate(0,0.3)%22><path d=%22M 9,39 L 36,39 L 36,36 L 9,36 L 9,39 z %22 style=%22stroke-linecap:butt%22/><path d=%22M 12.5,32 L 14,29.5 L 31,29.5 L 32.5,32 L 12.5,32 z %22 style=%22stroke-linecap:butt%22/><path d=%22M 12,36 L 12,32 L 33,32 L 33,36 L 12,36 z %22 style=%22stroke-linecap:butt%22/><path d=%22M 14,29.5 L 14,16.5 L 31,16.5 L 31,29.5 L 14,29.5 z %22 style=%22stroke-linecap:butt;stroke-linejoin:miter%22/><path d=%22M 14,16.5 L 11,14 L 34,14 L 31,16.5 L 14,16.5 z %22 style=%22stroke-linecap:butt%22/><path d=%22M 11,14 L 11,9 L 15,9 L 15,11 L 20,11 L 20,9 L 25,9 L 25,11 L 30,11 L 30,9 L 34,9 L 34,14 L 11,14 z %22 style=%22stroke-linecap:butt%22/><path d=%22M 12,35.5 L 33,35.5 L 33,35.5%22 style=%22fill:none;stroke:%23ffffff;stroke-width:1;stroke-linejoin:miter%22/><path d=%22M 13,31.5 L 32,31.5%22 style=%22fill:none;stroke:%23ffffff;stroke-width:1;stroke-linejoin:miter%22/><path d=%22M 14,29.5 L 31,29.5%22 style=%22fill:none;stroke:%23ffffff;stroke-width:1;stroke-linejoin:miter%22/><path d=%22M 14,16.5 L 31,16.5%22 style=%22fill:none;stroke:%23ffffff;stroke-width:1;stroke-linejoin:miter%22/><path d=%22M 11,14 L 34,14%22 style=%22fill:none;stroke:%23ffffff;stroke-width:1;stroke-linejoin:miter%22/></g></svg>',
2512         'bB': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><g style=%22opacity:1;fill:none;fill-rule:evenodd;fill-opacity:1;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 transform=%22translate(0,0.6)%22><g style=%22fill:%23000000;stroke:%23000000;stroke-linecap:butt%22><path d=%22M 9,36 C 12.39,35.03 19.11,36.43 22.5,34 C 25.89,36.43 32.61,35.03 36,36 C 36,36 37.65,36.54 39,38 C 38.32,38.97 37.35,38.99 36,38.5 C 32.61,37.53 25.89,38.96 22.5,37.5 C 19.11,38.96 12.39,37.53 9,38.5 C 7.65,38.99 6.68,38.97 6,38 C 7.35,36.54 9,36 9,36 z%22/><path d=%22M 15,32 C 17.5,34.5 27.5,34.5 30,32 C 30.5,30.5 30,30 30,30 C 30,27.5 27.5,26 27.5,26 C 33,24.5 33.5,14.5 22.5,10.5 C 11.5,14.5 12,24.5 17.5,26 C 17.5,26 15,27.5 15,30 C 15,30 14.5,30.5 15,32 z%22/><path d=%22M 25 8 A 2.5 2.5 0 1 1 20,8 A 2.5 2.5 0 1 1 25 8 z%22/></g><path d=%22M 17.5,26 L 27.5,26 M 15,30 L 30,30 M 22.5,15.5 L 22.5,20.5 M 20,18 L 25,18%22 style=%22fill:none;stroke:%23ffffff;stroke-linejoin:miter%22/></g></svg>',
2513         'bN': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><g style=%22opacity:1;fill:none;fill-opacity:1;fill-rule:evenodd;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 transform=%22translate(0,0.3)%22><path d=%22M 22,10 C 32.5,11 38.5,18 38,39 L 15,39 C 15,30 25,32.5 23,18%22 style=%22fill:%23000000;stroke:%23000000%22/><path d=%22M 24,18 C 24.38,20.91 18.45,25.37 16,27 C 13,29 13.18,31.34 11,31 C 9.958,30.06 12.41,27.96 11,28 C 10,28 11.19,29.23 10,30 C 9,30 5.997,31 6,26 C 6,24 12,14 12,14 C 12,14 13.89,12.1 14,10.5 C 13.27,9.506 13.5,8.5 13.5,7.5 C 14.5,6.5 16.5,10 16.5,10 L 18.5,10 C 18.5,10 19.28,8.008 21,7 C 22,7 22,10 22,10%22 style=%22fill:%23000000;stroke:%23000000%22/><path d=%22M 9.5 25.5 A 0.5 0.5 0 1 1 8.5,25.5 A 0.5 0.5 0 1 1 9.5 25.5 z%22 style=%22fill:%23ffffff;stroke:%23ffffff%22/><path d=%22M 15 15.5 A 0.5 1.5 0 1 1 14,15.5 A 0.5 1.5 0 1 1 15 15.5 z%22 transform=%22matrix(0.866,0.5,-0.5,0.866,9.693,-5.173)%22 style=%22fill:%23ffffff;stroke:%23ffffff%22/><path d=%22M 24.55,10.4 L 24.1,11.85 L 24.6,12 C 27.75,13 30.25,14.49 32.5,18.75 C 34.75,23.01 35.75,29.06 35.25,39 L 35.2,39.5 L 37.45,39.5 L 37.5,39 C 38,28.94 36.62,22.15 34.25,17.66 C 31.88,13.17 28.46,11.02 25.06,10.5 L 24.55,10.4 z %22 style=%22fill:%23ffffff;stroke:none%22/></g></svg>',
2514         'bP': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><path d=%22m 22.5,9 c -2.21,0 -4,1.79 -4,4 0,0.89 0.29,1.71 0.78,2.38 C 17.33,16.5 16,18.59 16,21 c 0,2.03 0.94,3.84 2.41,5.03 C 15.41,27.09 11,31.58 11,39.5 H 34 C 34,31.58 29.59,27.09 26.59,26.03 28.06,24.84 29,23.03 29,21 29,18.59 27.67,16.5 25.72,15.38 26.21,14.71 26.5,13.89 26.5,13 c 0,-2.21 -1.79,-4 -4,-4 z%22 style=%22opacity:1;fill:%23000000;fill-opacity:1;fill-rule:nonzero;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22/></svg>',
2515 };
2516
2517 function svg_piece_theme(piece) {
2518         return svg_pieces[piece];
2519 }
2520
2521 function init() {
2522         unique = get_unique();
2523
2524         // Load settings from HTML5 local storage if available.
2525         if (supports_html5_storage() && window['localStorage']['enable_sound']) {
2526                 set_sound(parseInt(window['localStorage']['enable_sound']));
2527         } else {
2528                 set_sound(false);
2529         }
2530
2531         let admin_match = window.location.href.match(/\?password=([a-zA-Z0-9_-]+)/);
2532         if (admin_match !== null) {
2533                 admin_password = admin_match[1];
2534         }
2535
2536         // Create board.
2537         board = new window.ChessBoard('board', {
2538                 onMoveEnd: function() { board_is_animating = false; },
2539
2540                 draggable: true,
2541                 pieceTheme: svg_piece_theme,
2542                 onDragStart: onDragStart,
2543                 onDrop: onDrop,
2544                 onSnapEnd: onSnapEnd
2545         });
2546         document.getElementById("board").addEventListener('mousedown', mousedownSquare);
2547         document.getElementById("board").addEventListener('mouseup', mouseupSquare);
2548
2549         if (window['inline_json']) {
2550                 let j = window['inline_json'];
2551                 process_update_response(j['data'], { 'get': (h) => j['headers'][h] });
2552                 delete window['inline_json'];
2553         }
2554         request_update();
2555         window.addEventListener('resize', function() {
2556                 board.resize();
2557                 update_sparkline(displayed_analysis_data || current_analysis_data);
2558                 update_board_highlight();
2559                 redraw_arrows();
2560         });
2561         new ResizeObserver(() => update_sparkline(displayed_analysis_data || current_analysis_data)).observe(document.getElementById('scoresparkcontainer'));
2562         window.addEventListener('keyup', function(event) {
2563                 if (event.which == 39) {  // Left arrow.
2564                         next_move();
2565                 } else if (event.which == 37) {  // Right arrow.
2566                         prev_move();
2567                 } else if (event.which >= 49 && event.which <= 57) {  // 1-9.
2568                         let num = event.which - 49;
2569                         if (current_games && current_games.length >= num) {
2570                                 switch_backend(current_games[num]);
2571                         }
2572                 } else if (event.which == 78) {  // N.
2573                         next_game();
2574                 }
2575         });
2576         window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
2577         possibly_switch_game_from_hash();
2578 };
2579 document.addEventListener('DOMContentLoaded', init);
2580
2581 })();