X-Git-Url: https://git.sesse.net/?p=remoteglot;a=blobdiff_plain;f=www%2Fjs%2Fremoteglot.js;h=d6a08a875b8642332f76f6bf60222797eec36f6e;hp=27ded16052cb45076f37b00534f1f448f20bfdfc;hb=HEAD;hpb=a8f854462950e88d74aa73102ff3d431caa52b0e diff --git a/www/js/remoteglot.js b/www/js/remoteglot.js index 27ded16..d36bf9e 100644 --- a/www/js/remoteglot.js +++ b/www/js/remoteglot.js @@ -5,10 +5,10 @@ * Version of this script. If the server returns a version larger than * this, it is a sign we should reload to upgrade ourselves. * - * @type {Number} + * @type {number} * @const * @private */ -let SCRIPT_VERSION = 2021021300; +let SCRIPT_VERSION = 2023122700; /** * The current backend URL. @@ -75,22 +75,29 @@ let occupied_by_arrows = []; /** Currently displayed refutation lines (on-screen). * Can either come from the current_analysis_data, displayed_analysis_data, - * or hash_refutation_lines. + * or hash_refutation_lines (choose_displayed_refutation_lines() chooses which one). + * + * @typedef {{ + * score: Array, + * depth: string, + * pv: Array., + * move: string + * }} + * @private */ -let refutation_lines = []; +var RefutationLine; /** Refutation lines from current hash probe. - * * If non-null, will override refutation lines from the base position. - * Note that these are relative to display_fen, not base_fen. + * + * @type {Array.} */ let hash_refutation_lines = null; -/** @type {!number} @private */ -let move_num = 1; - -/** @type {!string} @private */ -let toplay = 'W'; +/** + * What FEN hash_refutation_lines is relative to. + */ +let hash_refutation_lines_base_fen = null; /** @type {number} @private */ let ims = 0; @@ -125,6 +132,9 @@ let reverse_dragging_from = null; /** @type {?number} @private */ let unique = null; +/** @type {?string} @private */ +let admin_password = null; + /** @type {boolean} @private */ let enable_sound = false; @@ -160,15 +170,19 @@ let display_fen = null; /** @typedef {{ * start_fen: string, * pv: Array., - * move_num: number, - * toplay: string, * scores: Array<{first_move: number, score: Object}>, * start_display_move_num: number - * }} DisplayLine + * }} * - * "start_display_move_num" is the (half-)move number to start displaying the PV at. - * "score" is also evaluated at this point. + * "start_display_move_num" is the (half-)move number to start displaying the PV at, + * i.e., the index into pv. + * + * "score" is also evaluated at this point. scores can be empty and is frequently + * sparse; it's generally only really useful for history (we obviously don't know + * much about how the score will * move during e.g. a PV, except that a mate/TB + * counter might go down). */ +var DisplayLine; /** All PVs that we currently know of. * @@ -187,7 +201,11 @@ let current_display_line = null; /** @type {boolean} @private */ let current_display_line_is_history = false; -/** @type {?number} @private */ +/** @type {?number} @private + * + * The highlighted/used/shown move in current_display_line.pv, in terms of absolute index + * (not relative to e.g. the start FEN). + */ let current_display_move = null; /** @@ -203,7 +221,7 @@ let current_analysis_xhr = null; * The current timer to fire off a request to get main analysis (not history), * if any, so that we can abort it. * - * @type {?Number} + * @type {?number} * @private */ let current_analysis_request_timer = null; @@ -228,12 +246,12 @@ let current_hash_xhr = null; * The current timer to display hash probe information (it could be waiting on the * board to stop animating), if any, so that we can abort it. * - * @type {?Number} + * @type {?number} * @private */ let current_hash_display_timer = null; -let supports_html5_storage = function() { +function supports_html5_storage() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { @@ -243,7 +261,7 @@ let supports_html5_storage = function() { // Make the unique token persistent so people refreshing the page won't count twice. // Of course, you can never fully protect against people deliberately wanting to spam. -let get_unique = function() { +function get_unique() { let use_local_storage = supports_html5_storage(); if (use_local_storage && window['localStorage']['unique']) { return window['localStorage']['unique']; @@ -255,7 +273,7 @@ let get_unique = function() { return unique; } -let request_update = function() { +function request_update() { current_analysis_request_timer = null; let handle_err = () => { @@ -301,7 +319,7 @@ let request_update = function() { } -let process_update_response = function(data, headers) { +function process_update_response(data, headers) { sync_server_clock(headers.get('Date')); ims = headers.get('X-RGLM'); let num_viewers = headers.get('X-RGNV'); @@ -342,7 +360,7 @@ let process_update_response = function(data, headers) { } } -let possibly_play_sound = function(old_data, new_data) { +function possibly_play_sound(old_data, new_data) { if (!enable_sound) { return; } @@ -353,8 +371,7 @@ let possibly_play_sound = function(old_data, new_data) { if (ding && ding.play) { if (old_data['position'] && old_data['position']['fen'] && new_data['position'] && new_data['position']['fen'] && - (old_data['position']['fen'] !== new_data['position']['fen'] || - old_data['position']['move_num'] !== new_data['position']['move_num'])) { + old_data['position']['fen'] !== new_data['position']['fen']) { ding.play(); } } @@ -363,7 +380,7 @@ let possibly_play_sound = function(old_data, new_data) { /** * @type {!string} server_date_string */ -let sync_server_clock = function(server_date_string) { +function sync_server_clock(server_date_string) { let server_time_ms = new Date(server_date_string).getTime(); let client_time_ms = new Date().getTime(); let estimated_offset_ms = server_time_ms - client_time_ms; @@ -377,7 +394,7 @@ let sync_server_clock = function(server_date_string) { } } -let clear_arrows = function() { +function clear_arrows() { for (let i = 0; i < arrows.length; ++i) { if (arrows[i].svg) { arrows[i].svg.remove(); @@ -392,16 +409,45 @@ let clear_arrows = function() { } } -let redraw_arrows = function() { +function redraw_arrows() { for (let i = 0; i < arrows.length; ++i) { position_arrow(arrows[i]); } } +/** @param {!string} fen + * @return {!string} + * + * Return whose side it is to play (w or b), given a FEN. + */ +function find_toplay(fen) { + return fen.split(' ')[1]; +} + +/** @param {!string} fen + * @return {!number} + * + * Return the move clock, starting from 1. See also find_toplay(). + */ +function find_move_num(fen) { + return parseInt(fen.split(' ')[5]); +} + +/** @param {!string} fen + * @return {!number} + * + * Return the half-move clock, starting from 0 (and never resetting). + */ +function find_halfmove_num(fen) { + let move_num = find_move_num(fen); + let toplay = find_toplay(fen); + return (move_num - 1) * 2 + (toplay === 'w' ? 0 : 1); +} + /** @param {!number} x * @return {!number} */ -let sign = function(x) { +function sign(x) { if (x > 0) { return 1; } else if (x < 0) { @@ -416,7 +462,7 @@ let sign = function(x) { * @param {!string} to The square the arrow is to (e.g. e4). * @return {boolean} */ -let interfering_arrow = function(from, to) { +function interfering_arrow(from, to) { let from_col = from.charCodeAt(0) - "a1".charCodeAt(0); let from_row = from.charCodeAt(1) - "a1".charCodeAt(1); let to_col = to.charCodeAt(0) - "a1".charCodeAt(0); @@ -457,7 +503,7 @@ let interfering_arrow = function(from, to) { * @param {!number} u * @return {!string} The point in "x y" form, suitable for SVG paths. */ -let point_from_start = function(x1, y1, x2, y2, t, u) { +function point_from_start(x1, y1, x2, y2, t, u) { let dx = x2 - x1; let dy = y2 - y1; @@ -480,7 +526,7 @@ let point_from_start = function(x1, y1, x2, y2, t, u) { * @param {!number} u * @return {!string} The point in "x y" form, suitable for SVG paths. */ -let point_from_end = function(x1, y1, x2, y2, t, u) { +function point_from_end(x1, y1, x2, y2, t, u) { let dx = x2 - x1; let dy = y2 - y1; @@ -493,7 +539,7 @@ let point_from_end = function(x1, y1, x2, y2, t, u) { return x + " " + y; } -let position_arrow = function(arrow) { +function position_arrow(arrow) { if (arrow.svg) { if (arrow.svg.parentElement) { arrow.svg.parentElement.removeChild(arrow.svg); @@ -504,12 +550,11 @@ let position_arrow = function(arrow) { return; } - let board_width = parseInt(document.querySelector(".board-b72b1").style.width, 10); - let zoom_factor = board_width / 400.0; - let line_width = arrow.line_width * zoom_factor; - let arrow_size = arrow.arrow_size * zoom_factor; + // We always draw as if the board is 400x400, the viewBox will adjust that for us + let line_width = arrow.line_width; + let arrow_size = arrow.arrow_size; - let square_width = board_width / 8; + let square_width = 400 / 8; let from_y, to_y, from_x, to_x; if (board.orientation() === 'black') { from_y = (arrow.from_row + 0.5)*square_width; @@ -526,10 +571,9 @@ let position_arrow = function(arrow) { let SVG_NS = "http://www.w3.org/2000/svg"; let XHTML_NS = "http://www.w3.org/1999/xhtml"; let svg = document.createElementNS(SVG_NS, "svg"); - svg.setAttribute("width", board_width); - svg.setAttribute("height", board_width); - svg.setAttribute("style", "position: absolute"); - svg.setAttribute("position", "absolute"); + svg.setAttribute("width", "100%"); + svg.setAttribute("height", "100%"); + svg.setAttribute("viewBox", "0 0 400 400"); svg.setAttribute("version", "1.1"); svg.setAttribute("class", "c1"); svg.setAttribute("xmlns", XHTML_NS); @@ -570,8 +614,9 @@ let position_arrow = function(arrow) { head.setAttribute("fill", arrow.fg_color); svg.appendChild(head); - svg.style.top = '2px'; /* Border for .board-b72b1. */ - svg.style.left = '2px'; + svg.style.position = 'absolute'; + svg.style.top = '0px'; /* Border for .board-b72b1. */ + svg.style.left = '0px'; svg.style.pointerEvents = 'none'; document.getElementById('board').appendChild(svg); arrow.svg = svg; @@ -584,7 +629,7 @@ let position_arrow = function(arrow) { * @param {number} line_width * @param {number} arrow_size */ -let create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) { +function create_arrow(from_square, to_square, fg_color, line_width, arrow_size) { let from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0); let from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1); let to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0); @@ -605,7 +650,7 @@ let create_arrow = function(from_square, to_square, fg_color, line_width, arrow_ arrows.push(arrow); } -let compare_by_score = function(refutation_lines, invert, a, b) { +function compare_by_score(refutation_lines, invert, a, b) { let sa = compute_score_sort_key(refutation_lines[b]['score'], refutation_lines[b]['depth'], invert); let sb = compute_score_sort_key(refutation_lines[a]['score'], refutation_lines[a]['depth'], invert); return sa - sb; @@ -622,7 +667,7 @@ let compare_by_score = function(refutation_lines, invert, a, b) { * @return {Array.} The FEN representation (e.g. Ne4) of all * moves, in score order. */ -let find_nonstupid_moves = function(data, margin, invert) { +function find_nonstupid_moves(data, margin, invert) { // First of all, if there are any moves that are more than 0.5 ahead of // the primary move, the refutation lines are probably bunk, so just // kill them all. @@ -656,7 +701,8 @@ let find_nonstupid_moves = function(data, margin, invert) { moves.push(move); } } - moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], data['position']['toplay'] === 'B', a, b) }); + let toplay = find_toplay(data['position']['fen']); + moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], toplay, a, b) }); moves.unshift(data['pv'][0]); return moves; @@ -666,26 +712,22 @@ let find_nonstupid_moves = function(data, margin, invert) { * @param {number} x * @return {!string} */ -let thousands = function(x) { +function thousands(x) { return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join(''); } /** * @param {!string} start_fen * @param {Array.} pv - * @param {number} move_num - * @param {!string} toplay - * @param {Array<{ first_move: integer, score: Object }>} scores + * @param {Array<{ first_move: number, score: Object }>} scores * @param {number} start_display_move_num * @param {number=} opt_limit * @param {boolean=} opt_showlast */ -let add_pv = function(start_fen, pv, move_num, toplay, scores, start_display_move_num, opt_limit, opt_showlast) { +function add_pv(start_fen, pv, scores, start_display_move_num, opt_limit, opt_showlast) { display_lines.push({ start_fen: start_fen, pv: pv, - move_num: parseInt(move_num), - toplay: toplay, scores: scores, start_display_move_num: start_display_move_num }); @@ -706,85 +748,78 @@ let add_pv = function(start_fen, pv, move_num, toplay, scores, start_display_mov * @param {number=} opt_limit If set, show at most this number of moves. * @param {boolean=} opt_showlast If limit is set, show the last moves instead of the first ones. */ -let print_pv = function(line_num, splicepos, opt_limit, opt_showlast) { +function print_pv(line_num, splicepos, opt_limit, opt_showlast) { let display_line = display_lines[line_num]; let pv = display_line.pv; - let move_num = display_line.move_num; - let toplay = display_line.toplay; + let halfmove_num = find_halfmove_num(display_line.start_fen) + 2; // From two, for simplicity. + let start_halfmove_num = halfmove_num; + + let ret = document.createDocumentFragment(); // Truncate PV at the start if needed. - let start_display_move_num = display_line.start_display_move_num; - if (start_display_move_num > 0) { - pv = pv.slice(start_display_move_num); - let to_add = start_display_move_num; - if (toplay === 'B') { - ++move_num; - toplay = 'W'; - --to_add; - } - if (to_add % 2 == 1) { - toplay = 'B'; - --to_add; - } - move_num += to_add / 2; - if (splicepos !== null && splicepos > 0) { - --splicepos; + let to_skip = display_line.start_display_move_num; + if (opt_limit && opt_showlast && pv.length - to_skip > opt_limit) { + // Explicit (UI-visible) truncation from the start, for the history. + ret.appendChild(document.createTextNode('(')); + let link = document.createElement('a'); + link.className = 'move'; + link.href = 'javascript:collapse_history(false)'; + link.textContent = '…'; + ret.appendChild(link); + ret.appendChild(document.createTextNode(') ')); + to_skip = pv.length - opt_limit; + to_skip += to_skip % 2; // Make sure it starts on a white move. + } + if (to_skip > 0) { + pv = pv.slice(to_skip); + halfmove_num += to_skip; + if (splicepos !== null) { + splicepos -= to_skip; + if (splicepos < 0) { + splicepos = 0; + } } } - let ret = ''; - let i = 0; - let in_tb = false; - if (opt_limit && opt_showlast && pv.length > opt_limit) { - // Truncate the PV at the beginning (instead of at the end). - // We assume here that toplay is 'W'. We also assume that if - // opt_showlast is set, then it is the history, and thus, - // the UI should be to expand the history. - ret = '(…) '; - i = pv.length - opt_limit; - if (i % 2 == 1) { - ++i; - } - move_num += i / 2; - } else if (toplay == 'B' && pv.length > 0) { - let move = ""; - if (splicepos === 0) { - move += "(TB: "; - in_tb = true; - } - move += "" + pv[0] + ""; - ret = move_num + '. … ' + move; - toplay = 'W'; - ++i; - ++move_num; + // The initial move number needs to go before any (TB: …) marker. + if (halfmove_num % 2 == 1) { + // Black move. + ret.appendChild(document.createTextNode((halfmove_num - 1) / 2 + '. … ')); + } else { + // White move. + ret.appendChild(document.createTextNode(halfmove_num / 2 + '. ')); } - for ( ; i < pv.length; ++i) { - let move = "" + pv[i] + ""; + let in_tb = false; + for (let i = 0; i < pv.length; ++i, ++halfmove_num) { + let prefix = ''; if (splicepos === i) { - ret += " (TB: "; + prefix = '(TB:'; in_tb = true; } - if (toplay == 'W') { + if (halfmove_num % 2 == 0 && i != 0) { if (i > opt_limit && !opt_showlast) { if (in_tb) { - ret += ")"; + prefix += ')'; } - return ret + ' (…)'; - } - if (ret != '') { - ret += ' '; + ret.appendChild(document.createTextNode(prefix + ' (…)')); + return ret; } - ret += move_num + '. ' + move; - ++move_num; - toplay = 'B'; + prefix += ' ' + (halfmove_num / 2) + '. '; } else { - ret += ' ' + move; - toplay = 'W'; + prefix += ' '; } + ret.appendChild(document.createTextNode(prefix)); + + let link = document.createElement('a'); + link.className = 'move'; + link.setAttribute('id', 'automove' + line_num + '-' + (halfmove_num - start_halfmove_num)); + link.textContent = pv[i]; + link.href = 'javascript:show_line(' + line_num + ', ' + (halfmove_num - start_halfmove_num) + ');'; + ret.appendChild(link); } if (in_tb) { - ret += ")"; + ret.appendChild(document.createTextNode(')')); } return ret; } @@ -792,7 +827,7 @@ let print_pv = function(line_num, splicepos, opt_limit, opt_showlast) { /** Update the highlighted to/from squares on the board. * Based on the global "highlight_from" and "highlight_to" letiables. */ -let update_board_highlight = function() { +function update_board_highlight() { document.getElementById("board").querySelectorAll('.square-55d63').forEach((square) => square.classList.remove('nonuglyhighlight')); if ((current_display_line === null || current_display_line_is_history) && highlight_from !== undefined && highlight_to !== undefined) { @@ -801,33 +836,50 @@ let update_board_highlight = function() { } } -let update_history = function() { +function update_history() { + let history = document.getElementById('history'); if (display_lines[0] === null || display_lines[0].pv.length == 0) { - document.getElementById("history").innerHTML = "No history"; + history.textContent = 'No history'; } else if (truncate_display_history) { - document.getElementById("history").innerHTML = print_pv(0, null, 8, true); + history.replaceChildren(print_pv(0, null, 8, true)); } else { - document.getElementById("history").innerHTML = - '(collapse) ' + - print_pv(0, null); + history.textContent = '('; + let link = document.createElement('a'); + link.className = 'move'; + link.href = 'javascript:collapse_history(true)'; + link.textContent = 'collapse'; + history.appendChild(link); + history.appendChild(document.createTextNode(') ')); + history.append(print_pv(0, null)); } } /** * @param {!boolean} truncate_history */ -let collapse_history = function(truncate_history) { +function collapse_history(truncate_history) { truncate_display_history = truncate_history; update_history(); } window['collapse_history'] = collapse_history; -/** Update the HTML display of multi-PV from the global "refutation_lines". +function choose_displayed_refutation_lines() { + if (hash_refutation_lines) { + // If we're in hash exploration, that takes precedence. + return [hash_refutation_lines, hash_refutation_lines_base_fen]; + } else { + let data = displayed_analysis_data || current_analysis_data; + return [data['refutation_lines'], data['position']['fen']]; + } +} + +/** Update the HTML display of multi-PV. * * Also recreates the global "display_lines". */ -let update_refutation_lines = function() { - if (base_fen === null) { +function update_refutation_lines() { + const [refutation_lines, refutation_lines_base_fen] = choose_displayed_refutation_lines(); + if (!refutation_lines) { return; } if (display_lines.length > 2) { @@ -858,7 +910,7 @@ let update_refutation_lines = function() { moves.push(move); } - let invert = (toplay === 'B'); + let invert = (find_toplay(refutation_lines_base_fen) === 'b'); if (current_display_line && current_display_move % 2 == 0 && !current_display_line_is_history) { invert = !invert; } @@ -876,10 +928,13 @@ let update_refutation_lines = function() { if (line['pv'].length == 0) { // Not found, so just make a one-move PV. - let move = "" + line['move'] + ""; - move_td.innerHTML = move; - let score_td = document.createElement("td"); + let link = document.createElement('a'); + link.className = 'move'; + link.href = 'javascript:show_line(' + display_lines.length + ', ' + 0 + ')'; + link.textContent = line['move']; + move_td.replaceChildren(link); + let score_td = document.createElement("td"); score_td.classList.add("score"); score_td.textContent = "—"; tr.appendChild(score_td); @@ -892,7 +947,7 @@ let update_refutation_lines = function() { let pv_td = document.createElement("td"); tr.appendChild(pv_td); pv_td.classList.add("pv"); - pv_td.innerHTML = add_pv(base_fen, base_line.concat([ line['move'] ]), move_num, toplay, scores, start_display_move_num); + pv_td.append(add_pv(refutation_lines_base_fen, base_line.concat([ line['move'] ]), scores, start_display_move_num)); tbl.append(tr); continue; @@ -921,7 +976,7 @@ let update_refutation_lines = function() { let pv_td = document.createElement("td"); tr.appendChild(pv_td); pv_td.classList.add("pv"); - pv_td.innerHTML = add_pv(base_fen, base_line.concat(line['pv']), move_num, toplay, scores, start_display_move_num, 10); + pv_td.append(add_pv(refutation_lines_base_fen, base_line.concat(line['pv']), scores, start_display_move_num, 10)); tbl.append(tr); } @@ -938,7 +993,7 @@ let update_refutation_lines = function() { * @param {Array.} moves * @param {number} last_move */ -let chess_from = function(fen, moves, last_move) { +function chess_from(fen, moves, last_move) { let hiddenboard = new Chess(); if (fen !== null && fen !== undefined) { hiddenboard.load(fen); @@ -955,7 +1010,7 @@ let chess_from = function(fen, moves, last_move) { return hiddenboard; } -let update_game_list = function(games) { +function update_game_list(games) { document.getElementById("games").textContent = ""; if (games === null) { return; @@ -1005,7 +1060,7 @@ let update_game_list = function(games) { * Try to find a running game that matches with the current hash, * and switch to it if we're not already displaying it. */ -let possibly_switch_game_from_hash = function() { +function possibly_switch_game_from_hash() { let history_match = window.location.hash.match(/^#history=([a-zA-Z0-9_-]+)/); if (history_match !== null) { let game_id = history_match[1]; @@ -1037,7 +1092,7 @@ let possibly_switch_game_from_hash = function() { * If this is a Chess960 castling which doesn't move the king, * move the rook instead. */ -let patch_move = function(move) { +function patch_move(move) { if (move === null) return null; if (move.from !== move.to) return move; @@ -1061,7 +1116,7 @@ let patch_move = function(move) { /** Update all the HTML on the page, based on current global state. */ -let update_board = function() { +function update_board() { document.body.style.opacity = null; let data = displayed_analysis_data || current_analysis_data; @@ -1073,8 +1128,8 @@ let update_board = function() { // unconditionally taken from current_data (we're not interested in // historic history). if (current_data['position']['history']) { - let start = (current_data['position'] && current_data['position']['start_fen']) ? current_data['position']['start_fen'] : 'start'; - add_pv(start, current_data['position']['history'], 1, 'W', null, 0, 8, true); + 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'; + add_pv(start, current_data['position']['history'], null, 0, 8, true); } else { display_lines.push(null); } @@ -1100,15 +1155,6 @@ let update_board = function() { headline = 'Analysis'; } - // Credits, where applicable. Note that we don't want the footer to change a lot - // when e.g. viewing history, so if any of these changed during the game, - // use the current one still. - if (current_data['using_lomonosov']) { - document.getElementById("lomonosov").style.display = null; - } else { - document.getElementById("lomonosov").style.display = 'none'; - } - // Credits: The engine name/version. if (current_data['engine'] && current_data['engine']['name'] !== null) { document.getElementById("engineid").textContent = current_data['engine']['name']; @@ -1157,18 +1203,19 @@ let update_board = function() { } else if (data['position']['last_move'] !== 'none') { // Find the previous move. let previous_move_num, previous_toplay; - if (data['position']['toplay'] == 'B') { - previous_move_num = data['position']['move_num']; - previous_toplay = 'W'; + let fen = data['position']['fen']; + if (find_toplay(fen) === 'b') { + previous_move_num = find_move_num(fen); + previous_toplay = 'w'; } else { - previous_move_num = data['position']['move_num'] - 1; - previous_toplay = 'B'; + previous_move_num = find_move_num(fen) - 1; + previous_toplay = 'b'; } last_move = format_move_with_number( data['position']['last_move'], previous_move_num, - previous_toplay == 'W'); + previous_toplay == 'w'); headline += ' after ' + last_move; } else { last_move = null; @@ -1219,7 +1266,6 @@ let update_board = function() { document.getElementById("refutationlines").replaceChildren(); document.getElementById("whiteclock").replaceChildren(); document.getElementById("blackclock").replaceChildren(); - refutation_lines = []; update_refutation_lines(); clear_arrows(); update_displayed_line(); @@ -1254,9 +1300,7 @@ let update_board = function() { // The search stats. if (data['searchstats']) { - document.getElementById("searchstats").innerHTML = data['searchstats']; - } else if (data['tablebase'] == 1) { - document.getElementById("searchstats").textContent = "Tablebase result"; + document.getElementById("searchstats").textContent = data['searchstats']; } else if (data['nodes'] && data['nps'] && data['depth']) { let stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply'; if (data['seldepth']) { @@ -1274,6 +1318,9 @@ let update_board = function() { } else { document.getElementById("searchstats").textContent = ""; } + if (admin_password !== null) { + document.getElementById("searchstats").innerHTML += " | ADMIN MODE (if password is right) | Undo move"; + } // Update the board itself. base_fen = data['position']['fen']; @@ -1283,10 +1330,11 @@ let update_board = function() { document.getElementById("pvtitle").textContent = "PV:"; let scores = [{ first_move: -1, score: data['score'] }]; - document.getElementById("pv").innerHTML = add_pv(data['position']['fen'], data['pv'], data['position']['move_num'], data['position']['toplay'], scores, 0); + document.getElementById("pv").replaceChildren(add_pv(data['position']['fen'], data['pv'], scores, 0)); // Update the PV arrow. clear_arrows(); + let toplay = find_toplay(data['position']['fen']); if (data['pv'].length >= 1) { let hiddenboard = new Chess(base_fen); @@ -1304,7 +1352,7 @@ let update_board = function() { hiddenboard.move(data['pv'][i + 1]); // To keep continuity. } - let alt_moves = find_nonstupid_moves(data, 30, data['position']['toplay'] === 'B'); + let alt_moves = find_nonstupid_moves(data, 30, toplay === 'b'); for (let i = 1; i < alt_moves.length && i < 3; ++i) { hiddenboard = new Chess(base_fen); let move = patch_move(hiddenboard.move(alt_moves[i])); @@ -1316,7 +1364,7 @@ let update_board = function() { // See if all semi-reasonable moves have only one possible response. if (data['pv'].length >= 2) { - let nonstupid_moves = find_nonstupid_moves(data, 300, data['position']['toplay'] === 'B'); + let nonstupid_moves = find_nonstupid_moves(data, 300, toplay === 'b'); let hiddenboard = new Chess(base_fen); hiddenboard.move(data['pv'][0]); let response = hiddenboard.move(data['pv'][1]); @@ -1354,18 +1402,14 @@ let update_board = function() { } } - // Update the refutation lines. base_fen = data['position']['fen']; - move_num = parseInt(data['position']['move_num']); - toplay = data['position']['toplay']; - refutation_lines = hash_refutation_lines || data['refutation_lines']; update_refutation_lines(); // Update the sparkline last, since its size depends on how everything else reflowed. update_sparkline(data); } -let update_sparkline = function(data) { +function update_sparkline(data) { let scorespark = document.getElementById('scoresparkcontainer'); scorespark.textContent = ''; if (data && data['score_history']) { @@ -1377,8 +1421,9 @@ let update_sparkline = function(data) { } } if (first_move_num !== undefined) { - let last_move_num = data['position']['move_num'] * 2 - 3; - if (data['position']['toplay'] === 'B') { + let fen = data['position']['fen']; + let last_move_num = find_move_num(fen) * 2 - 3; + if (find_toplay(fen) === 'b') { ++last_move_num; } @@ -1465,7 +1510,7 @@ let update_sparkline = function(data) { } } -let draw_hover = function(e, color, tooltip) { +function draw_hover(e, color, tooltip) { e.target.style.fill = 'rgb(' + color[0]*100.0 + '%, ' + color[1]*100.0 + '%, ' + color[2]*100.0 + '%)'; let hover = document.getElementById('sparklinehover'); @@ -1480,7 +1525,7 @@ let draw_hover = function(e, color, tooltip) { hover.style.top = top + 'px'; } -let hide_hover = function(e, color) { +function hide_hover(e, color) { e.target.style.fill = 'rgb(' + color[0]*100.0 + '%, ' + color[1]*100.0 + '%, ' + color[2]*100.0 + '%)'; document.getElementById('sparklinehover').style.display = 'none'; } @@ -1488,7 +1533,7 @@ let hide_hover = function(e, color) { /** * @param {number} num_viewers */ -let update_num_viewers = function(num_viewers) { +function update_num_viewers(num_viewers) { let text = ""; if (num_viewers === null) { text = ""; @@ -1507,7 +1552,7 @@ let update_num_viewers = function(num_viewers) { document.getElementById("numviewers").textContent = text; } -let update_clock = function() { +function update_clock() { clock_timer = null; let data = displayed_analysis_data || current_analysis_data; @@ -1584,7 +1629,7 @@ let update_clock = function() { // This matches what DGT clocks do. let show_seconds = (white_clock_ms < 60 * 20 * 1000 || black_clock_ms < 60 * 20 * 1000); - if (color) { + if (color && remaining_ms > 0) { // See when the clock will change next, and update right after that. let next_update_ms; if (show_seconds) { @@ -1600,10 +1645,10 @@ let update_clock = function() { } /** - * @param {Number} remaining_ms + * @param {number} remaining_ms * @param {boolean} show_seconds */ -let format_clock = function(remaining_ms, show_seconds) { +function format_clock(remaining_ms, show_seconds) { if (remaining_ms <= 0) { if (show_seconds) { return "00:00:00"; @@ -1626,9 +1671,9 @@ let format_clock = function(remaining_ms, show_seconds) { } /** - * @param {Number} x + * @param {number} x */ -let format_2d = function(x) { +function format_2d(x) { if (x >= 10) { return x; } else { @@ -1638,10 +1683,10 @@ let format_2d = function(x) { /** * @param {string} move - * @param {Number} move_num Move number of this move. + * @param {number} move_num Move number of this move. * @param {boolean} white_to_play Whether white is to play this move. */ -let format_move_with_number = function(move, move_num, white_to_play) { +function format_move_with_number(move, move_num, white_to_play) { let ret; if (white_to_play) { ret = move_num + '. '; @@ -1654,10 +1699,10 @@ let format_move_with_number = function(move, move_num, white_to_play) { /** * @param {string} move - * @param {Number} halfmove_num Half-move number that is to be played, + * @param {number} halfmove_num Half-move number that is to be played, * starting from 0. */ -let format_halfmove_with_number = function(move, halfmove_num) { +function format_halfmove_with_number(move, halfmove_num) { return format_move_with_number( move, Math.floor(halfmove_num / 2) + 1, @@ -1666,9 +1711,9 @@ let format_halfmove_with_number = function(move, halfmove_num) { /** * @param {Object} data - * @param {Number} halfmove_num + * @param {number} halfmove_num */ -let format_tooltip = function(data, halfmove_num) { +function format_tooltip(data, halfmove_num) { if (data['score_history'][halfmove_num + 1] || (halfmove_num + 1) === data['position']['history'].length) { // Position is in the history, or it is the current position @@ -1702,20 +1747,11 @@ let format_tooltip = function(data, halfmove_num) { } } -/** - * @param {boolean} truncate_history - */ -let set_truncate_history = function(truncate_history) { - truncate_display_history = truncate_history; - update_refutation_lines(); -} -window['set_truncate_history'] = set_truncate_history; - /** * @param {number} line_num * @param {number} move_num */ -let show_line = function(line_num, move_num) { +function show_line(line_num, move_num) { if (line_num == -1) { current_display_line = null; current_display_move = null; @@ -1729,7 +1765,7 @@ let show_line = function(line_num, move_num) { return; } else { current_display_line = {...display_lines[line_num]}; // Shallow clone. - current_display_move = move_num + current_display_line.start_display_move_num; + current_display_move = move_num; } current_display_line_is_history = (line_num == 0); @@ -1741,7 +1777,7 @@ let show_line = function(line_num, move_num) { } window['show_line'] = show_line; -let prev_move = function() { +function prev_move() { if (current_display_line && current_display_move >= current_display_line.start_display_move_num) { --current_display_move; @@ -1752,7 +1788,7 @@ let prev_move = function() { } window['prev_move'] = prev_move; -let next_move = function() { +function next_move() { if (current_display_line && current_display_move < current_display_line.pv.length - 1) { ++current_display_move; @@ -1763,7 +1799,7 @@ let next_move = function() { } window['next_move'] = next_move; -let next_game = function() { +function next_game() { if (current_games === null) { return; } @@ -1781,7 +1817,7 @@ let next_game = function() { // Couldn't find it; give up. } -let update_historic_analysis = function() { +function update_historic_analysis() { if (!current_display_line_is_history) { return; } @@ -1826,24 +1862,20 @@ let update_historic_analysis = function() { /** * @param {string} fen */ -let update_imbalance = function(fen) { - let hiddenboard = new Chess(fen); +function update_imbalance(fen) { let imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0}; - for (let row = 0; row < 8; ++row) { - for (let col = 0; col < 8; ++col) { - let col_text = String.fromCharCode('a1'.charCodeAt(0) + col); - let row_text = String.fromCharCode('a1'.charCodeAt(1) + row); - let square = col_text + row_text; - let contents = hiddenboard.get(square); - if (contents !== null) { - if (contents.color === 'w') { - ++imbalance[contents.type]; - } else { - --imbalance[contents.type]; - } - } + for (const c of fen) { + if (c === ' ') { + // End of board + break; + } + if (c != c.toUpperCase()) { + --imbalance[c]; + } else if (c != c.toLowerCase()) { + ++imbalance[c.toLowerCase()]; } } + let white_imbalance = document.getElementById('whiteimbalance'); let black_imbalance = document.getElementById('blackimbalance'); white_imbalance.textContent = ''; @@ -1882,7 +1914,7 @@ let update_imbalance = function(fen) { * Also replaces the PV with the current displayed line if it's not shown * anywhere else on the screen. */ -let update_move_highlight = function() { +function update_move_highlight() { if (highlighted_move !== null) { highlighted_move.classList.remove('highlight'); } @@ -1893,14 +1925,14 @@ let update_move_highlight = function() { document.getElementById("pvtitle").textContent = "Exploring:"; current_display_line.start_display_move_num = 0; display_lines.push(current_display_line); - document.getElementById("pv").innerHTML = print_pv(display_lines.length - 1, null); // FIXME + document.getElementById("pv").replaceChildren(print_pv(display_lines.length - 1, null)); // FIXME display_line_num = display_lines.length - 1; // Clear out the PV, so it's not selected by anything later. display_lines[1].pv = []; } - highlighted_move = document.getElementById("automove" + display_line_num + "-" + (current_display_move - current_display_line.start_display_move_num)); + highlighted_move = document.getElementById("automove" + display_line_num + "-" + current_display_move); if (highlighted_move !== null) { highlighted_move.classList.add('highlight'); } @@ -1914,7 +1946,7 @@ let update_move_highlight = function() { * * @return {?number} */ -let find_display_line_matching_num = function() { +function find_display_line_matching_num() { for (let i = 0; i < display_lines.length; ++i) { let line = display_lines[i]; if (line.start_display_move_num > 0) continue; @@ -1939,7 +1971,7 @@ let find_display_line_matching_num = function() { * TODO: This should really be called only whenever something changes, * instead of all the time. */ -let update_displayed_line = function() { +function update_displayed_line() { if (current_display_line === null) { document.getElementById("linenav").style.display = 'none'; document.getElementById("linemsg").style.display = 'revert'; @@ -1953,12 +1985,12 @@ let update_displayed_line = function() { document.getElementById("linemsg").style.display = 'none'; if (current_display_move <= 0) { - document.getElementById("prevmove").innerHTML = "Previous"; + document.getElementById("prevmove").textContent = "Previous"; } else { document.getElementById("prevmove").innerHTML = "Previous"; } if (current_display_move == current_display_line.pv.length - 1) { - document.getElementById("nextmove").innerHTML = "Next"; + document.getElementById("nextmove").textContent = "Next"; } else { document.getElementById("nextmove").innerHTML = "Next"; } @@ -1974,10 +2006,11 @@ let update_displayed_line = function() { update_imbalance(hiddenboard.fen()); } -let set_board_position = function(new_fen) { +function set_board_position(new_fen) { board_is_animating = true; let old_fen = board.fen(); - board.position(new_fen); + let animate = old_fen !== '8/8/8/8/8/8/8/'; + board.position(new_fen, animate); if (board.fen() === old_fen) { board_is_animating = false; } @@ -1986,7 +2019,7 @@ let set_board_position = function(new_fen) { /** * @param {boolean} param_enable_sound */ -let set_sound = function(param_enable_sound) { +function set_sound(param_enable_sound) { enable_sound = param_enable_sound; if (enable_sound) { document.getElementById("soundon").innerHTML = "On"; @@ -2012,7 +2045,7 @@ window['set_sound'] = set_sound; /** Send off a hash probe request to the backend. * @param {string} fen */ -let explore_hash = function(fen) { +function explore_hash(fen) { // If we already have a backend response going, abort it. if (current_hash_xhr) { current_hash_xhr.abort(); @@ -2039,7 +2072,7 @@ let explore_hash = function(fen) { * @param {!Object} data * @param {string} fen */ -let show_explore_hash_results = function(data, fen) { +function show_explore_hash_results(data, fen) { if (board_is_animating) { // Updating while the animation is still going causes // the animation to jerk. This is pretty crude, but it will do. @@ -2048,11 +2081,12 @@ let show_explore_hash_results = function(data, fen) { } current_hash_display_timer = null; hash_refutation_lines = data['lines']; + hash_refutation_lines_base_fen = fen; update_board(); } // almost all of this stuff comes from the chessboard.js example page -let onDragStart = function(source, piece, position, orientation) { +function onDragStart(source, piece, position, orientation) { let pseudogame = new Chess(display_fen); if (pseudogame.game_over() === true || (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) || @@ -2068,13 +2102,13 @@ let onDragStart = function(source, piece, position, orientation) { return true; } -let mousedownSquare = function(e) { - if (!e.target || !e.target.closest('.square-55d63')) { +function mousedownSquare(e) { + if (!e.target || !e.target.getAttribute('data-square')) { return; } reverse_dragging_from = null; - let square = e.target.closest('.square-55d63').getAttribute('data-square'); + let square = e.target.getAttribute('data-square'); let pseudogame = new Chess(display_fen); if (pseudogame.game_over() === true) { @@ -2098,14 +2132,14 @@ let mousedownSquare = function(e) { } } -let mouseupSquare = function(e) { - if (!e.target || !e.target.closest('.square-55d63')) { +function mouseupSquare(e) { + if (!e.target || !e.target.getAttribute('data-square')) { return; } if (reverse_dragging_from === null) { return; } - let source = e.target.closest('.square-55d63').getAttribute('data-square'); + let source = e.target.getAttribute('data-square'); let target = reverse_dragging_from; reverse_dragging_from = null; if (onDrop(source, target) !== 'snapback') { @@ -2116,7 +2150,7 @@ let mouseupSquare = function(e) { }); } -let get_best_move = function(game, source, target, invert) { +function get_best_move(game, source, target, invert) { let moves = game.moves({ verbose: true }); if (source !== null) { moves = moves.filter(function(move) { return move.from == source; }); @@ -2159,6 +2193,7 @@ let get_best_move = function(game, source, target, invert) { let best_move = null; let best_move_score = null; + let refutation_lines = choose_displayed_refutation_lines()[0]; for (let move in refutation_lines) { let line = refutation_lines[move]; if (!line['score']) { @@ -2176,7 +2211,7 @@ let get_best_move = function(game, source, target, invert) { return best_move; } -let onDrop = function(source, target) { +function onDrop(source, target) { if (source === target) { if (recommended_move === null) { return 'snapback'; @@ -2201,7 +2236,52 @@ let onDrop = function(source, target) { if (move === null) return 'snapback'; } -let onSnapEnd = function(source, target) { +/** + * If we are in admin mode, send this move to the backend. + * + * @param {string} fen + * @param {string} move + */ +function send_chosen_move(fen, move) { + if (admin_password !== null) { + let history = current_analysis_data['position']['history']; + let url = '/manual-override.pl'; + url += '?fen=' + encodeURIComponent(fen); + url += '&history=' + encodeURIComponent(JSON.stringify(history)); + url += '&move=' + encodeURIComponent(move); + url += '&player_w=' + encodeURIComponent(current_analysis_data['position']['player_w']); + url += '&player_b=' + encodeURIComponent(current_analysis_data['position']['player_b']); + url += '&password=' + encodeURIComponent(admin_password); + + console.log(fen, history); + fetch(url); // Ignore the result. + } +} + +function undo_move() { + if (admin_password !== null) { + let history = current_analysis_data['position']['history']; + history = history.slice(0, history.length - 1); + + let position = current_analysis_data['position']['start_fen']; + let hiddenboard = chess_from(position, history, history.length); + let fen = hiddenboard.fen(); + + let url = '/manual-override.pl'; + url += '?fen=' + encodeURIComponent(fen); + url += '&history=' + encodeURIComponent(JSON.stringify(history)); + url += '&move=null'; + url += '&player_w=' + encodeURIComponent(current_analysis_data['position']['player_w']); + url += '&player_b=' + encodeURIComponent(current_analysis_data['position']['player_b']); + url += '&password=' + encodeURIComponent(admin_password); + + console.log(fen, history); + fetch(url); // Ignore the result. + } +} +window['undo_move'] = undo_move; + +function onSnapEnd(source, target) { if (source === target && recommended_move !== null) { source = recommended_move.from; target = recommended_move.to; @@ -2214,6 +2294,11 @@ let onSnapEnd = function(source, target) { promotion: 'q' // NOTE: always promote to a queen for example simplicity }); + if (admin_password !== null) { + send_chosen_move(display_fen, move.san); + return; + } + // Move ahead on the line we're on -- this includes history if we've // gone backwards. if (current_display_line && @@ -2234,17 +2319,20 @@ let onSnapEnd = function(source, target) { } let line = display_lines[i]; if (line.pv[line.start_display_move_num] === move.san) { - show_line(i, 0); + show_line(i, line.start_display_move_num); return; } } // Shouldn't really be here if we have hash probes, but there's really // nothing we can do. + // FIXME: Just make a new line, probably (even if we don't have hash moves). + // As it is, we can actually drag (but not click) such a move in the UI, + // but it has no effect on what we're probing. } // End of dragging-related code. -let fmt_cp = function(v) { +function fmt_cp(v) { if (v === 0) { return "0.00"; } else if (v > 0) { @@ -2255,7 +2343,7 @@ let fmt_cp = function(v) { } } -let format_short_score = function(score) { +function format_short_score(score) { if (!score) { return "???"; } @@ -2288,7 +2376,7 @@ let format_short_score = function(score) { return null; } -let format_long_score = function(score) { +function format_long_score(score) { if (!score) { return "???"; } @@ -2324,7 +2412,7 @@ let format_long_score = function(score) { return null; } -let compute_plot_score = function(score) { +function compute_plot_score(score) { if (score[0] === 'M' || score[0] === 'T') { return 500; } else if (score[0] === 'm' || score[0] === 't') { @@ -2349,7 +2437,7 @@ let compute_plot_score = function(score) { * @param {boolean} invert Whether black is to play. * @return {number} */ -let compute_score_sort_key = function(score, depth, invert) { +function compute_score_sort_key(score, depth, invert) { let s; if (!score) { return -10000000; @@ -2382,7 +2470,7 @@ let compute_score_sort_key = function(score, depth, invert) { /** * @param {Object} game */ -let switch_backend = function(game) { +function switch_backend(game) { // Stop looking at historic data. current_display_line = null; current_display_move = null; @@ -2442,11 +2530,11 @@ const svg_pieces = { 'bP': 'data:image/svg+xml,%0A%0A', }; -let svg_piece_theme = function(piece) { +function svg_piece_theme(piece) { return svg_pieces[piece]; } -let init = function() { +function init() { unique = get_unique(); // Load settings from HTML5 local storage if available. @@ -2456,6 +2544,11 @@ let init = function() { set_sound(false); } + let admin_match = window.location.href.match(/\?password=([a-zA-Z0-9_-]+)/); + if (admin_match !== null) { + admin_password = admin_match[1]; + } + // Create board. board = new window.ChessBoard('board', { onMoveEnd: function() { board_is_animating = false; }, @@ -2469,6 +2562,11 @@ let init = function() { document.getElementById("board").addEventListener('mousedown', mousedownSquare); document.getElementById("board").addEventListener('mouseup', mouseupSquare); + if (window['inline_json']) { + let j = window['inline_json']; + process_update_response(j['data'], { 'get': (h) => j['headers'][h] }); + delete window['inline_json']; + } request_update(); window.addEventListener('resize', function() { board.resize(); @@ -2476,6 +2574,7 @@ let init = function() { update_board_highlight(); redraw_arrows(); }); + new ResizeObserver(() => update_sparkline(displayed_analysis_data || current_analysis_data)).observe(document.getElementById('scoresparkcontainer')); window.addEventListener('keyup', function(event) { if (event.which == 39) { // Left arrow. next_move();