diff --git a/OpenBench/static/board.css b/OpenBench/static/board.css new file mode 100644 index 0000000..52b0dae --- /dev/null +++ b/OpenBench/static/board.css @@ -0,0 +1,500 @@ +/* =========================================================================== + OpenBench - board analyser ( event page ) + Loaded after ux.css. Layout: the board on the left, the moves and the + evaluation graph on the right, with both columns the same height. + =========================================================================== */ + +:root { + --bd-light: #E3E8F1; + --bd-dark: #7A8FB3; +} + +/* ---------- Layout ---------- */ + +.bd-layout { + display: grid; + grid-template-columns: minmax(0, 640px) minmax(0, 1fr); + gap: 20px; + align-items: stretch; + margin-bottom: 20px; +} + +.bd-layout .card { + margin-bottom: 0; +} + +.bd-card { + display: flex; + flex-direction: column; +} + +.bd-body { + padding: 16px; +} + +/* The right column does not add to the row height, so it always matches the board */ +.ev-right { + position: relative; + min-width: 0; + min-height: 560px; +} + +.ev-right-inner { + position: absolute; + inset: 0; + display: flex; + flex-direction: column; + gap: 20px; +} + +.ev-moves-card { + display: flex; + flex: 1 1 0; + flex-direction: column; + min-height: 0; +} + +.ev-moves-card .ev-movelist { + flex: 1 1 0; + min-height: 0; + max-height: none; +} + +.bd-graph-card { + flex: none; +} + +/* ---------- Board ---------- */ + +.bd-grid { + display: grid; + grid-template-columns: 28px minmax(0, 1fr); + column-gap: 12px; + row-gap: 10px; +} + +#bd-top { grid-column: 2; grid-row: 1; } +.bd-eval { grid-column: 1; grid-row: 2; } +.bd-board { grid-column: 2; grid-row: 2; } +#bd-bottom { grid-column: 2; grid-row: 3; } + +.bd-board { + aspect-ratio: 1; + border-radius: var(--radius); + box-shadow: 0 0 0 1px var(--line-strong), 0 8px 22px rgba(0, 0, 0, 0.35); + overflow: hidden; +} + +.bd-board svg { + display: block; + width: 100%; + height: 100%; +} + +.bd-nojs { + margin: 0; + padding: 24px; + color: var(--muted); +} + +.bd-light { fill: var(--bd-light); } +.bd-dark { fill: var(--bd-dark); } + +.bd-hl-from { fill: rgba(250, 204, 21, 0.38); } +.bd-hl-to { fill: rgba(250, 204, 21, 0.55); } +.bd-hl-bad { fill: rgba(248, 113, 113, 0.5); } + +.bd-check-in { stop-color: #F87171; stop-opacity: 0.95; } +.bd-check-out { stop-color: #F87171; stop-opacity: 0; } + +.bd-coord { + font: 600 17px var(--font-sans); + pointer-events: none; + user-select: none; +} + +.bd-coord.on-dark { fill: var(--bd-light); } +.bd-coord.on-light { fill: var(--bd-dark); } + +.bd-arrow { opacity: 0.92; } +.bd-arrow line { stroke: #F87171; } +.bd-arrow polygon { fill: #F87171; } + +/* ---------- Evaluation bar ---------- */ + +.bd-eval { + position: relative; + align-self: stretch; + background-color: #161B26; + border-radius: var(--radius); + box-shadow: 0 0 0 1px var(--line-strong); + overflow: hidden; +} + +.bd-eval::after { + content: ''; + position: absolute; + top: 50%; + left: 0; + right: 0; + height: 1px; + background-color: rgba(120, 130, 150, 0.55); +} + +.bd-eval-fill { + position: absolute; + left: 0; + right: 0; + bottom: 0; + height: 50%; + background-color: #EDF0F6; + transition: height 0.25s ease; +} + +.bd-eval.is-flipped .bd-eval-fill { + top: 0; + bottom: auto; +} + +.bd-eval-label { + position: absolute; + left: 0; + right: 0; + z-index: 1; + font: 600 10.5px var(--font-mono); + letter-spacing: -0.03em; + text-align: center; +} + +.bd-eval-label.on-white { bottom: 6px; color: #161B26; } +.bd-eval-label.on-black { top: 6px; color: #E6EAF2; } + +.bd-eval.is-flipped .bd-eval-label.on-white { top: 6px; bottom: auto; } +.bd-eval.is-flipped .bd-eval-label.on-black { bottom: 6px; top: auto; } + +/* ---------- Players, captured pieces ---------- */ + +.bd-player { + display: flex; + align-items: center; + gap: 10px; + min-width: 0; + min-height: 34px; +} + +.bd-player .ev-piece { + flex: none; + width: 12px; + height: 12px; +} + +.bd-player.is-white .ev-piece { background-color: #F1F4FA; } +.bd-player.is-black .ev-piece { background-color: #0B0E14; } + +.bd-player.is-turn .ev-piece { + box-shadow: 0 0 0 2px var(--color2), 0 0 0 4px var(--accent); +} + +.bd-name { + flex: 0 1 auto; + min-width: 0; + overflow: hidden; + color: var(--color-font1); + font-size: 14px; + font-weight: 600; + text-overflow: ellipsis; + white-space: nowrap; +} + +.bd-caps { + display: flex; + flex: 1 1 auto; + align-items: center; + min-width: 0; + padding-left: 6px; + overflow: hidden; +} + +.bd-cap { + flex: none; + width: 20px; + height: 20px; +} + +.bd-cap + .bd-cap { + margin-left: -9px; +} + +.bd-mat { + flex: none; + color: var(--muted); + font: 600 12px var(--font-mono); +} + +/* ---------- Status, controls, FEN ---------- */ + +.bd-status { + min-height: 20px; + margin: 14px 0 0; + color: var(--color-font2); + font-size: 13px; + font-weight: 500; + text-align: center; +} + +.bd-status.is-bad { color: var(--bad); } +.bd-status.is-warn { color: var(--warn); } + +.bd-controls { + display: grid; + grid-template-columns: repeat(5, minmax(0, 1fr)) 52px; + gap: 8px; + margin-top: 12px; +} + +.bd-card .bd-btn { + display: inline-flex; + align-items: center; + justify-content: center; + height: 40px; + padding: 0; + background-color: var(--color3); + border: 1px solid var(--line-strong); + border-radius: var(--radius); + color: var(--color-font1); + font-size: 14px; + cursor: pointer; + transition: background-color 0.12s ease, border-color 0.12s ease; +} + +.bd-card .bd-btn:hover:not(:disabled) { + background-color: var(--surface-hover); + border-color: var(--accent); +} + +.bd-card .bd-btn:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +.bd-card .bd-btn:disabled { + opacity: 0.4; + cursor: not-allowed; +} + +.bd-card .bd-btn-main { + background-color: var(--accent); + border-color: var(--accent); + color: #FFFFFF; +} + +.bd-card .bd-btn-main:hover:not(:disabled) { + background-color: var(--accent-hover); + border-color: var(--accent-hover); +} + +.bd-card .bd-btn-main.is-playing { + background-color: var(--accent-soft); + border-color: var(--accent); + color: var(--color-font1); +} + +.bd-card .bd-btn-flip { + margin-left: 4px; +} + +.bd-fen { + display: flex; + align-items: center; + gap: 10px; + margin-top: 12px; + padding: 5px 5px 5px 12px; + background-color: var(--color1); + border: 1px solid var(--line); + border-radius: var(--radius); +} + +.bd-fen-label { + flex: none; + color: var(--muted); + font-size: 11px; + font-weight: 600; + letter-spacing: 0.1em; +} + +.bd-fen code { + flex: 1 1 auto; + min-width: 0; + padding: 0; + overflow: hidden; + background: none; + color: var(--color-font2); + font-family: var(--font-mono); + font-size: 12px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.bd-card .bd-btn-icon { + flex: none; + width: 32px; + height: 32px; +} + +/* ---------- Moves card ---------- */ + +.ev-moves-card .ev-sel { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 10px 16px; + padding: 14px 16px; + border-bottom: 1px solid var(--line); +} + +.ev-moves-card .ev-sel-main { + flex: 1 1 auto; + min-width: 0; +} + +.ev-moves-card .ev-sel-san { + font-size: 24px; +} + +.ev-sel-counter { + margin-left: auto; + color: var(--muted); + font-size: 12px; +} + +.ev-moves-card .ev-sel-stats { + grid-template-columns: repeat(3, minmax(64px, auto)); + margin-top: 0; +} + +.ev-moves-card .ev-sel-note { + flex-basis: 100%; + margin: 0; +} + +.ev-moves-foot { + display: flex; + flex-wrap: wrap; + gap: 6px 18px; + padding: 10px 16px; + border-top: 1px solid var(--line); + color: var(--muted); + font-size: 12px; +} + +.ev-moves-foot kbd { + display: inline-block; + min-width: 20px; + padding: 1px 6px; + background-color: var(--color3); + border: 1px solid var(--line-strong); + border-bottom-width: 2px; + border-radius: var(--radius); + color: var(--color-font2); + font: 11px var(--font-mono); + text-align: center; +} + +/* ---------- Evaluation graph ---------- */ + +.bd-graph-wrap { + padding: 14px 16px 16px; +} + +.bd-graph { + height: 132px; + background-color: #363F54; + border: 1px solid var(--line-strong); + border-radius: var(--radius); + cursor: crosshair; + overflow: hidden; + touch-action: none; +} + +.bd-graph svg { + display: block; + width: 100%; + height: 100%; +} + +.bd-area-white { fill: rgba(237, 240, 246, 0.88); } +.bd-area-black { fill: rgba(11, 14, 20, 0.92); } + +.bd-mid { + stroke: rgba(255, 255, 255, 0.28); + stroke-width: 1; + vector-effect: non-scaling-stroke; +} + +.bd-curve { + fill: none; + stroke: var(--accent-hover); + stroke-width: 2; + stroke-linejoin: round; + vector-effect: non-scaling-stroke; +} + +.bd-cursor { + stroke: var(--accent); + stroke-width: 2; + vector-effect: non-scaling-stroke; +} + +/* ---------- Responsive ---------- */ + +@media (max-width: 1180px) { + + .bd-layout { + grid-template-columns: minmax(0, 1fr); + } + + .bd-card { + width: 100%; + max-width: 640px; + justify-self: center; + } + + .ev-right { + min-height: 0; + } + + .ev-right-inner { + position: static; + } + + .ev-moves-card { + flex: none; + } + + .ev-moves-card .ev-movelist { + flex: none; + max-height: 420px; + } +} + +@media (max-width: 767px) { + + .bd-body { + padding: 12px; + } + + .bd-grid { + grid-template-columns: 22px minmax(0, 1fr); + column-gap: 8px; + } + + .bd-eval-label { + font-size: 9px; + } + + .bd-controls { + grid-template-columns: repeat(5, minmax(0, 1fr)) 44px; + gap: 6px; + } +} diff --git a/OpenBench/static/board.js b/OpenBench/static/board.js new file mode 100644 index 0000000..b4bf218 --- /dev/null +++ b/OpenBench/static/board.js @@ -0,0 +1,502 @@ +/* OpenBench board analyser. + + Replays the PGN of an event position by position ( see chess.js ), and draws + - the board, with the last move, checks, and any illegal move that was tried + - an evaluation bar and an evaluation graph, from the engine comments + - captured pieces and material for both sides + + event_viewer.js owns the selected move and tells us about it with the + "ob:ply" event. We only draw, and ask window.OpenBenchViewer to move. + + Piece artwork: "Cburnett" set by Colin M.L. Burnett, GPL-2.0-or-later. + https://en.wikipedia.org/wiki/User:Cburnett/GFDL_images/Chess */ + +(function () { + 'use strict'; + + var Chess = window.OBChess; + var host = document.getElementById('bd-board'); + + if (!Chess || !host) return; + + + var NS = 'http://www.w3.org/2000/svg'; + + function $(id) { return document.getElementById(id); } + + function readJSON(id, fallback) { + var element = $(id); + if (!element) return fallback; + try { return JSON.parse(element.textContent); } catch (error) { return fallback; } + } + + var game = readJSON('ev-game', null); + var moves = readJSON('ev-moves', []); + + if (!game || !moves.length) return; + + var total = moves.length; + var replayed = Chess.replay(game.startFen, moves.map(function (move) { return move.san; })); + var positions = replayed.positions; // positions[i] is the board after i moves + var problem = replayed.error; + var attempt = Chess.findUciMove(game.note); + + var current = total; + var flipped = false; + var timer = null; + + try { flipped = window.localStorage.getItem('ob:board:flipped') === '1'; } catch (error) { /* ignore */ } + + /* ---------- Evaluations, from the White point of view ---------- */ + + var evals = [{ value: null, label: '\u2013' }]; + + moves.forEach(function (move) { + + var raw = move.eval; + + if (!raw) return evals.push({ value: null, label: '\u2013' }); + if (raw === 'book') return evals.push({ value: null, label: 'book' }); + + var body = raw.replace(/^[+-]/, ''); + var mate = body.charAt(0) === 'M'; + var magnitude = mate ? 100 : parseFloat(body); + + if (isNaN(magnitude)) return evals.push({ value: null, label: '\u2013' }); + + // The comment is from the point of view of the side that moved + var value = (raw.charAt(0) === '-' ? -magnitude : magnitude) * (move.color === 'b' ? -1 : 1); + + var label = mate ? (value < 0 ? '-' : '') + body : (value > 0 ? '+' : '') + value.toFixed(1); + + evals.push({ value: value, label: label }); + }); + + var hasEvals = evals.some(function (entry) { return entry.value !== null; }); + + // Squashes pawns into -1 .. +1, so that a mate does not flatten everything else + function squash(pawns) { + return 2 / (1 + Math.exp(-pawns / 2.2)) - 1; + } + + /* ---------- Piece artwork, shared by every board and tray ---------- */ + + var PIECES = { + wK: '', + wQ: '', + wR: '', + wB: '', + wN: '', + wP: '', + bK: '', + bQ: '', + bR: '', + bB: '', + bN: '', + bP: '' + }; + + function buildSprite() { + + if ($('bd-sprite')) return; + + var defs = ''; + Object.keys(PIECES).forEach(function (key) { + defs += '' + PIECES[key] + ''; + }); + + var sprite = document.createElementNS(NS, 'svg'); + sprite.setAttribute('id', 'bd-sprite'); + sprite.setAttribute('width', '0'); + sprite.setAttribute('height', '0'); + sprite.setAttribute('aria-hidden', 'true'); + sprite.style.position = 'absolute'; + sprite.innerHTML = '' + defs + ''; + + document.body.appendChild(sprite); + } + + function pieceKey(piece) { + return (piece === piece.toUpperCase() ? 'w' : 'b') + piece.toUpperCase(); + } + + /* ---------- The board ---------- */ + + // Top left corner of a square, in the 800 x 800 space of the board + function corner(square) { + + var file = square & 7, rank = square >> 3; + + return flipped ? { x: (7 - file) * 100, y: rank * 100 } : { x: file * 100, y: (7 - rank) * 100 }; + } + + function centre(square) { + var at = corner(square); + return { x: at.x + 50, y: at.y + 50 }; + } + + function arrow(from, to, className) { + + var a = centre(from), b = centre(to); + var dx = b.x - a.x, dy = b.y - a.y, length = Math.sqrt(dx * dx + dy * dy); + + if (!length) return ''; + + var ux = dx / length, uy = dy / length; + var tip = { x: b.x - ux * 8, y: b.y - uy * 8 }; + var base = { x: tip.x - ux * 42, y: tip.y - uy * 42 }; + var from_ = { x: a.x + ux * 22, y: a.y + uy * 22 }; + + var points = [ + tip.x + ',' + tip.y, + (base.x - uy * 25) + ',' + (base.y + ux * 25), + (base.x + uy * 25) + ',' + (base.y - ux * 25) + ].join(' '); + + return '' + + '' + + ''; + } + + function square(at, className) { + return ''; + } + + function drawBoard(position, index) { + + var out = '' + + ''; + + var file, rank, at, s; + + for (rank = 0; rank < 8; rank++) { + for (file = 0; file < 8; file++) { + at = corner(rank * 8 + file); + out += square(at, 'bd-sq ' + ((file + rank) % 2 === 0 ? 'bd-dark' : 'bd-light')); + } + } + + if (position.from >= 0) { + out += square(corner(position.from), 'bd-hl bd-hl-from'); + out += square(corner(position.to), 'bd-hl bd-hl-to'); + } + + if (position.check >= 0) { + at = corner(position.check); + out += ''; + } + + var showAttempt = attempt && index === total && !problem; + + if (showAttempt) { + out += square(corner(attempt.from), 'bd-hl bd-hl-bad'); + out += square(corner(attempt.to), 'bd-hl bd-hl-bad'); + } + + // Coordinates sit inside the squares along the bottom and left edges + var bottom = flipped ? 7 : 0, left = flipped ? 7 : 0; + + for (file = 0; file < 8; file++) { + s = bottom * 8 + file; + at = corner(s); + out += '' + 'abcdefgh'.charAt(file) + ''; + } + + for (rank = 0; rank < 8; rank++) { + s = rank * 8 + left; + at = corner(s); + out += '' + (rank + 1) + ''; + } + + for (s = 0; s < 64; s++) { + var piece = position.board.charAt(s); + if (piece === '.') continue; + at = corner(s); + out += ''; + } + + if (showAttempt) out += arrow(attempt.from, attempt.to, 'bd-arrow'); + + return out + ''; + } + + /* ---------- Player strips, captured pieces, material ---------- */ + + var ORDER = { q: 0, r: 1, b: 2, n: 3, p: 4 }; + + function captured(list) { + + return list.split('').sort(function (a, b) { + return ORDER[a.toLowerCase()] - ORDER[b.toLowerCase()]; + }).map(function (piece) { + return ''; + }).join(''); + } + + function fillStrip(strip, color, position) { + + if (!strip) return; + + var other = color === 'w' ? 'b' : 'w'; + var material = Chess.material(position.board); + var lead = material[color] - material[other]; + + strip.className = 'bd-player is-' + (color === 'w' ? 'white' : 'black') + (position.turn === color ? ' is-turn' : ''); + strip.querySelector('.bd-name').textContent = color === 'w' ? game.white : game.black; + strip.querySelector('.bd-caps').innerHTML = captured(position.caps[color]); + strip.querySelector('.bd-mat').textContent = lead > 0 ? '+' + lead : ''; + } + + function describe(position, index) { + + if (problem && index > positions.length - 1) { + return { tone: 'warn', text: 'Move ' + (problem.ply + 1) + ' (' + problem.san + ') cannot be played on the board' }; + } + + if (position.status === 'checkmate') return { tone: 'bad', text: 'Checkmate' }; + if (position.status === 'stalemate') return { tone: 'warn', text: 'Stalemate' }; + + if (attempt && index === total) { + return { tone: 'bad', text: (position.turn === 'w' ? 'White' : 'Black') + ' tried ' + attempt.text + ', which is illegal' }; + } + + return { tone: position.check >= 0 ? 'warn' : '', text: (position.check >= 0 ? 'Check. ' : '') + (position.turn === 'w' ? 'White' : 'Black') + ' to move' }; + } + + /* ---------- Evaluation bar ---------- */ + + function drawEval(index) { + + var bar = $('bd-eval'); + if (!bar) return; + + var info = evals[Math.min(index, evals.length - 1)]; + var share = info.value === null ? 50 : 50 + 50 * squash(info.value); + var label = bar.querySelector('.bd-eval-label'); + + bar.classList.toggle('is-flipped', flipped); + bar.querySelector('.bd-eval-fill').style.height = share + '%'; + + label.textContent = info.label; + label.className = 'bd-eval-label ' + (info.value !== null && info.value < 0 ? 'on-black' : 'on-white'); + bar.setAttribute('title', 'Evaluation: ' + info.label); + } + + /* ---------- Evaluation graph ---------- */ + + var graph = { width: 600, height: 150, pad: 8, cursor: null }; + + function graphX(index) { return total ? (index / total) * graph.width : 0; } + + function graphY(value) { + var middle = graph.height / 2; + return middle - squash(value) * (middle - graph.pad); + } + + function moveLabel(index) { + + if (index === 0) return 'Start position'; + + var move = moves[index - 1]; + return move.num + (move.color === 'w' ? '.' : '\u2026') + ' ' + move.san; + } + + function buildGraph() { + + var host = $('bd-graph'); + var card = $('bd-graph-card'); + + if (!host) return; + + if (!hasEvals) { + if (card) card.hidden = true; + return; + } + + var middle = graph.height / 2, previous = 0, points = [], i; + + for (i = 0; i <= total; i++) { + if (evals[i].value !== null) previous = evals[i].value; + points.push([graphX(i), graphY(previous)]); + } + + var line = points.map(function (point, n) { return (n ? 'L' : 'M') + point[0].toFixed(1) + ' ' + point[1].toFixed(1); }).join(' '); + var area = 'M0 ' + middle + ' ' + line.replace(/^M/, 'L') + ' L' + graph.width + ' ' + middle + ' Z'; + + host.innerHTML = + '' + + '' + + '' + + '' + + '' + + '' + + '' + + ''; + + graph.cursor = $('bd-cursor'); + + var scrubbing = false; + + function indexAt(event) { + var box = host.getBoundingClientRect(); + var ratio = box.width ? (event.clientX - box.left) / box.width : 0; + return Math.max(0, Math.min(total, Math.round(ratio * total))); + } + + host.addEventListener('pointerdown', function (event) { + scrubbing = true; + if (host.setPointerCapture) host.setPointerCapture(event.pointerId); + go(indexAt(event)); + }); + + host.addEventListener('pointermove', function (event) { + var index = indexAt(event); + graphLabel(index); + if (scrubbing) go(index); + }); + + host.addEventListener('pointerup', function () { scrubbing = false; }); + host.addEventListener('pointercancel', function () { scrubbing = false; }); + host.addEventListener('pointerleave', function () { if (!scrubbing) graphLabel(current); }); + } + + function graphLabel(index) { + var label = $('bd-graph-label'); + if (label) label.textContent = moveLabel(index) + (evals[index].label !== '\u2013' ? ' \u00B7 ' + evals[index].label : ''); + } + + function drawGraphCursor(index) { + + if (graph.cursor) { + var x = graphX(index).toFixed(1); + graph.cursor.setAttribute('x1', x); + graph.cursor.setAttribute('x2', x); + } + + graphLabel(index); + } + + /* ---------- Putting it together ---------- */ + + function go(index) { + + index = Math.max(0, Math.min(total, index)); + + if (window.OpenBenchViewer) window.OpenBenchViewer.select(index); + else { current = index; render(); } + } + + function render() { + + var position = positions[Math.min(current, positions.length - 1)]; + var status = describe(position, current); + + host.innerHTML = drawBoard(position, current); + + // The side at the bottom of the board is the one that faces us + fillStrip($('bd-bottom'), flipped ? 'b' : 'w', position); + fillStrip($('bd-top'), flipped ? 'w' : 'b', position); + + drawEval(current); + drawGraphCursor(current); + + var note = $('bd-status'); + if (note) { + note.textContent = status.text; + note.className = 'bd-status' + (status.tone ? ' is-' + status.tone : ''); + } + + var fen = $('bd-fen'); + if (fen) { fen.textContent = position.fen; fen.setAttribute('title', position.fen); } + + [['bd-first', 0], ['bd-prev', 0], ['bd-next', total], ['bd-last', total]].forEach(function (pair) { + if ($(pair[0])) $(pair[0]).disabled = current === pair[1]; + }); + } + + function stop() { + + if (timer) window.clearInterval(timer); + timer = null; + + var play = $('bd-play'); + if (play) { + play.classList.remove('is-playing'); + play.setAttribute('aria-label', 'Play'); + play.innerHTML = ''; + } + } + + function play() { + + if (timer) return stop(); + + if (current >= total) go(0); + + timer = window.setInterval(function () { + if (current >= total) return stop(); + go(current + 1); + }, 900); + + var button = $('bd-play'); + if (button) { + button.classList.add('is-playing'); + button.setAttribute('aria-label', 'Pause'); + button.innerHTML = ''; + } + } + + function flip() { + + flipped = !flipped; + try { window.localStorage.setItem('ob:board:flipped', flipped ? '1' : '0'); } catch (error) { /* ignore */ } + render(); + } + + function bind(id, handler) { + if ($(id)) $(id).addEventListener('click', handler); + } + + bind('bd-first', function () { stop(); go(0); }); + bind('bd-prev', function () { stop(); go(current - 1); }); + bind('bd-next', function () { stop(); go(current + 1); }); + bind('bd-last', function () { stop(); go(total); }); + bind('bd-play', play); + bind('bd-flip', flip); + + bind('bd-copy', function () { + var position = positions[Math.min(current, positions.length - 1)]; + if (window.OpenBenchViewer) window.OpenBenchViewer.copy(position.fen, 'FEN copied'); + }); + + document.addEventListener('keydown', function (event) { + + if (event.altKey || event.ctrlKey || event.metaKey) return; + if (/^(INPUT|TEXTAREA|SELECT|BUTTON|A)$/.test((event.target && event.target.tagName) || '')) return; + + if (event.key === 'f' || event.key === 'F') { flip(); event.preventDefault(); } + if (event.key === ' ') { play(); event.preventDefault(); } + + // Moving by hand ends a running playback + if (/^(ArrowLeft|ArrowRight|Home|End)$/.test(event.key)) stop(); + }); + + document.addEventListener('ob:ply', function (event) { + current = event.detail.index; + render(); + }); + + window.OpenBenchBoard = { + flip : flip, + play : play, + positions : positions, + evals : evals + }; + + buildSprite(); + buildGraph(); + render(); + +})(); diff --git a/OpenBench/static/chess.js b/OpenBench/static/chess.js new file mode 100644 index 0000000..c0f879f --- /dev/null +++ b/OpenBench/static/chess.js @@ -0,0 +1,607 @@ +/* OpenBench chess rules: just enough chess for the event board analyser. + + - FEN in and out, including Chess960 ( Shredder and X-FEN castling fields ) + - Legal move generation, with castling, en passant, and promotions + - SAN parsing, so a PGN movetext can be replayed position by position + + No dependencies. Works in the browser ( window.OBChess ) and in Node, where + perft() is used to check the move generator against known node counts. */ + +(function (root, factory) { + if (typeof module === 'object' && module.exports) module.exports = factory(); + else root.OBChess = factory(); +})(typeof self !== 'undefined' ? self : this, function () { + 'use strict'; + + var START_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'; + var FILES = 'abcdefgh'; + + var KNIGHT = [[1, 2], [2, 1], [2, -1], [1, -2], [-1, -2], [-2, -1], [-2, 1], [-1, 2]]; + var KING = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]; + var DIAG = [[1, 1], [1, -1], [-1, 1], [-1, -1]]; + var ORTHO = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + + var VALUES = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 }; + + /* Squares are numbered a1 = 0, b1 = 1, ... h8 = 63 */ + + function sq(file, rank) { return rank * 8 + file; } + function fileOf(square) { return square & 7; } + function rankOf(square) { return square >> 3; } + function name(square) { return FILES[square & 7] + ((square >> 3) + 1); } + + function parseSquare(text) { + if (!/^[a-h][1-8]$/.test(text || '')) return -1; + return sq(FILES.indexOf(text[0]), parseInt(text[1], 10) - 1); + } + + function colorOf(piece) { return piece === piece.toUpperCase() ? 'w' : 'b'; } + + function Position() { + this.board = new Array(64).fill(null); + this.turn = 'w'; + this.castling = { w: { k: -1, q: -1 }, b: { k: -1, q: -1 } }; // Rook files + this.ep = -1; + this.halfmove = 0; + this.fullmove = 1; + this.king = { w: -1, b: -1 }; + } + + Position.fromFen = function (fen) { + + var parts = String(fen).trim().split(/\s+/); + if (parts.length < 2) throw new Error('Bad FEN'); + + var rows = parts[0].split('/'); + if (rows.length !== 8) throw new Error('Bad FEN: expected 8 ranks'); + + var pos = new Position(); + + for (var row = 0; row < 8; row++) { + + var rank = 7 - row, file = 0; + + for (var i = 0; i < rows[row].length; i++) { + + var ch = rows[row][i]; + + if (ch >= '1' && ch <= '8') { + file += parseInt(ch, 10); + } else if ('pnbrqkPNBRQK'.indexOf(ch) !== -1) { + if (file > 7) throw new Error('Bad FEN: rank too long'); + pos.board[sq(file, rank)] = ch; + if (ch === 'K') pos.king.w = sq(file, rank); + if (ch === 'k') pos.king.b = sq(file, rank); + file++; + } else { + throw new Error('Bad FEN: unknown piece ' + ch); + } + } + + if (file !== 8) throw new Error('Bad FEN: rank length'); + } + + if (pos.king.w < 0 || pos.king.b < 0) throw new Error('Bad FEN: missing king'); + + pos.turn = parts[1] === 'b' ? 'b' : 'w'; + pos.ep = parts[3] && parts[3] !== '-' ? parseSquare(parts[3]) : -1; + pos.halfmove = parseInt(parts[4], 10) || 0; + pos.fullmove = parseInt(parts[5], 10) || 1; + + pos.parseCastling(parts[2] || '-'); + + return pos; + }; + + Position.prototype.parseCastling = function (field) { + + if (field === '-') return; + + for (var i = 0; i < field.length; i++) { + + var ch = field[i]; + var color = ch === ch.toUpperCase() ? 'w' : 'b'; + var rank = color === 'w' ? 0 : 7; + var king = this.king[color]; + + if (rankOf(king) !== rank) continue; + + var kingFile = fileOf(king); + var rook = color === 'w' ? 'R' : 'r'; + var lower = ch.toLowerCase(); + var side = null, rookFile = -1, f; + + if (lower === 'k') { + side = 'k'; // Outermost rook, as X-FEN says + for (f = 7; f > kingFile; f--) if (this.board[sq(f, rank)] === rook) { rookFile = f; break; } + } else if (lower === 'q') { + side = 'q'; + for (f = 0; f < kingFile; f++) if (this.board[sq(f, rank)] === rook) { rookFile = f; break; } + } else if (lower >= 'a' && lower <= 'h') { + rookFile = FILES.indexOf(lower); // Shredder-FEN names the file + side = rookFile > kingFile ? 'k' : 'q'; + } + + if (side && rookFile >= 0 && this.board[sq(rookFile, rank)] === rook) { + this.castling[color][side] = rookFile; + } + } + }; + + Position.prototype.toFen = function () { + + var rows = []; + + for (var rank = 7; rank >= 0; rank--) { + + var row = '', empty = 0; + + for (var file = 0; file < 8; file++) { + var piece = this.board[sq(file, rank)]; + if (!piece) { empty++; continue; } + if (empty) { row += empty; empty = 0; } + row += piece; + } + + if (empty) row += empty; + rows.push(row); + } + + var rights = '', self = this; + + ['w', 'b'].forEach(function (color) { + ['k', 'q'].forEach(function (side) { + var file = self.castling[color][side]; + if (file < 0) return; + var letter = (side === 'k' ? file === 7 : file === 0) ? side : FILES[file]; + rights += color === 'w' ? letter.toUpperCase() : letter; + }); + }); + + return [rows.join('/'), this.turn, rights || '-', this.ep >= 0 ? name(this.ep) : '-', + this.halfmove, this.fullmove].join(' '); + }; + + /* One character per square, a1 first. "." is an empty square. */ + + Position.prototype.boardString = function () { + return this.board.map(function (piece) { return piece || '.'; }).join(''); + }; + + Position.prototype.isAttacked = function (square, by) { + + var board = this.board, f = fileOf(square), r = rankOf(square), i, nf, nr, p; + + var pawn = by === 'w' ? 'P' : 'p', knight = by === 'w' ? 'N' : 'n'; + var king = by === 'w' ? 'K' : 'k', bishop = by === 'w' ? 'B' : 'b'; + var rook = by === 'w' ? 'R' : 'r', queen = by === 'w' ? 'Q' : 'q'; + + // A white pawn attacks upwards, so it sits one rank below the target + var pr = r + (by === 'w' ? -1 : 1); + if (pr >= 0 && pr < 8) { + if (f > 0 && board[sq(f - 1, pr)] === pawn) return true; + if (f < 7 && board[sq(f + 1, pr)] === pawn) return true; + } + + for (i = 0; i < 8; i++) { + nf = f + KNIGHT[i][0]; nr = r + KNIGHT[i][1]; + if (nf >= 0 && nf < 8 && nr >= 0 && nr < 8 && board[sq(nf, nr)] === knight) return true; + } + + for (i = 0; i < 8; i++) { + nf = f + KING[i][0]; nr = r + KING[i][1]; + if (nf >= 0 && nf < 8 && nr >= 0 && nr < 8 && board[sq(nf, nr)] === king) return true; + } + + for (i = 0; i < 8; i++) { + + var diagonal = i < 4, dir = diagonal ? DIAG[i] : ORTHO[i - 4]; + var slider = diagonal ? bishop : rook; + + nf = f + dir[0]; nr = r + dir[1]; + + while (nf >= 0 && nf < 8 && nr >= 0 && nr < 8) { + p = board[sq(nf, nr)]; + if (p) { + if (p === slider || p === queen) return true; + break; + } + nf += dir[0]; nr += dir[1]; + } + } + + return false; + }; + + Position.prototype.inCheck = function () { + return this.isAttacked(this.king[this.turn], this.turn === 'w' ? 'b' : 'w'); + }; + + function newMove(from, to, piece, captured) { + return { f: from, t: to, p: piece, cap: captured || null, promo: null, ep: false, castle: null, rook: -1, rookTo: -1 }; + } + + Position.prototype.pseudoMoves = function () { + + var moves = [], board = this.board, us = this.turn, them = us === 'w' ? 'b' : 'w'; + var s, f, r, i, nf, nr, target, move, type, dirs, dir, df; + + var promotions = ['q', 'r', 'b', 'n']; + + for (s = 0; s < 64; s++) { + + var piece = board[s]; + if (!piece || colorOf(piece) !== us) continue; + + type = piece.toLowerCase(); + f = fileOf(s); r = rankOf(s); + + if (type === 'p') { + + var step = us === 'w' ? 1 : -1; + var home = us === 'w' ? 1 : 6; + var last = us === 'w' ? 7 : 0; + var one = sq(f, r + step); + + if (!board[one]) { + + if (r + step === last) { + for (i = 0; i < 4; i++) { move = newMove(s, one, piece); move.promo = promotions[i]; moves.push(move); } + } else { + moves.push(newMove(s, one, piece)); + if (r === home && !board[sq(f, r + 2 * step)]) moves.push(newMove(s, sq(f, r + 2 * step), piece)); + } + } + + for (df = -1; df <= 1; df += 2) { + + nf = f + df; + if (nf < 0 || nf > 7) continue; + + var to = sq(nf, r + step); + target = board[to]; + + if (target && colorOf(target) === them) { + + if (r + step === last) { + for (i = 0; i < 4; i++) { move = newMove(s, to, piece, target); move.promo = promotions[i]; moves.push(move); } + } else { + moves.push(newMove(s, to, piece, target)); + } + + } else if (!target && to === this.ep) { + move = newMove(s, to, piece, them === 'w' ? 'P' : 'p'); + move.ep = true; + moves.push(move); + } + } + + } else if (type === 'n' || type === 'k') { + + var offsets = type === 'n' ? KNIGHT : KING; + + for (i = 0; i < 8; i++) { + nf = f + offsets[i][0]; nr = r + offsets[i][1]; + if (nf < 0 || nf > 7 || nr < 0 || nr > 7) continue; + target = board[sq(nf, nr)]; + if (!target || colorOf(target) === them) moves.push(newMove(s, sq(nf, nr), piece, target)); + } + + } else { + + dirs = type === 'b' ? DIAG : type === 'r' ? ORTHO : DIAG.concat(ORTHO); + + for (i = 0; i < dirs.length; i++) { + + dir = dirs[i]; + nf = f + dir[0]; nr = r + dir[1]; + + while (nf >= 0 && nf < 8 && nr >= 0 && nr < 8) { + target = board[sq(nf, nr)]; + if (!target) moves.push(newMove(s, sq(nf, nr), piece)); + else { if (colorOf(target) === them) moves.push(newMove(s, sq(nf, nr), piece, target)); break; } + nf += dir[0]; nr += dir[1]; + } + } + } + } + + this.castlingMoves(moves); + return moves; + }; + + Position.prototype.castlingMoves = function (moves) { + + var board = this.board, us = this.turn, them = us === 'w' ? 'b' : 'w'; + var back = us === 'w' ? 0 : 7, king = this.king[us], self = this; + + if (rankOf(king) !== back || this.isAttacked(king, them)) return; + + ['k', 'q'].forEach(function (side) { + + var rookFile = self.castling[us][side]; + if (rookFile < 0) return; + + var rookSq = sq(rookFile, back); + if (board[rookSq] !== (us === 'w' ? 'R' : 'r')) return; + + var kingFile = fileOf(king); + var kingTo = side === 'k' ? 6 : 2; + var rookTo = side === 'k' ? 5 : 3; + var file; + + // Everything on the paths of the King and the Rook must be empty, apart from those two + var span = function (a, b, visit) { + for (var x = Math.min(a, b); x <= Math.max(a, b); x++) visit(x); + }; + + var clear = true; + var empty = function (x) { + var square = sq(x, back); + if (square !== king && square !== rookSq && board[square]) clear = false; + }; + + span(kingFile, kingTo, empty); + span(rookFile, rookTo, empty); + if (!clear) return; + + // The King may not pass through, or land on, an attacked square + var safe = true; + span(kingFile, kingTo, function (x) { if (self.isAttacked(sq(x, back), them)) safe = false; }); + if (!safe) return; + + var move = newMove(king, sq(kingTo, back), board[king]); + move.castle = side; + move.rook = rookSq; + move.rookTo = sq(rookTo, back); + moves.push(move); + }); + }; + + Position.prototype.clearRookRights = function (square) { + + var f = fileOf(square), r = rankOf(square), self = this; + + ['w', 'b'].forEach(function (color) { + if (r !== (color === 'w' ? 0 : 7)) return; + if (self.castling[color].k === f) self.castling[color].k = -1; + if (self.castling[color].q === f) self.castling[color].q = -1; + }); + }; + + Position.prototype.make = function (m) { + + var board = this.board, us = this.turn; + + var undo = { + m: m, ep: this.ep, half: this.halfmove, full: this.fullmove, + wk: this.castling.w.k, wq: this.castling.w.q, bk: this.castling.b.k, bq: this.castling.b.q, + kw: this.king.w, kb: this.king.b + }; + + var piece = board[m.f]; + this.ep = -1; + + if (m.castle) { + + board[m.f] = null; + board[m.rook] = null; + board[m.t] = piece; + board[m.rookTo] = us === 'w' ? 'R' : 'r'; + + this.king[us] = m.t; + this.castling[us].k = -1; + this.castling[us].q = -1; + + } else { + + board[m.f] = null; + if (m.ep) board[sq(fileOf(m.t), rankOf(m.f))] = null; + board[m.t] = m.promo ? (us === 'w' ? m.promo.toUpperCase() : m.promo) : piece; + + if (piece === 'K' || piece === 'k') { + this.king[us] = m.t; + this.castling[us].k = -1; + this.castling[us].q = -1; + } + + this.clearRookRights(m.f); + this.clearRookRights(m.t); + + if ((piece === 'P' || piece === 'p') && Math.abs(m.t - m.f) === 16) this.ep = (m.f + m.t) / 2; + } + + this.halfmove = (piece === 'P' || piece === 'p' || m.cap) ? 0 : this.halfmove + 1; + if (us === 'b') this.fullmove++; + this.turn = us === 'w' ? 'b' : 'w'; + + return undo; + }; + + Position.prototype.unmake = function (undo) { + + var m = undo.m, board = this.board; + + this.turn = this.turn === 'w' ? 'b' : 'w'; + var us = this.turn; + + if (m.castle) { + + board[m.t] = null; + board[m.rookTo] = null; + board[m.f] = m.p; + board[m.rook] = us === 'w' ? 'R' : 'r'; + + } else { + + board[m.f] = m.p; + + if (m.ep) { + board[m.t] = null; + board[sq(fileOf(m.t), rankOf(m.f))] = m.cap; + } else { + board[m.t] = m.cap; + } + } + + this.ep = undo.ep; + this.halfmove = undo.half; + this.fullmove = undo.full; + this.castling.w.k = undo.wk; this.castling.w.q = undo.wq; + this.castling.b.k = undo.bk; this.castling.b.q = undo.bq; + this.king.w = undo.kw; this.king.b = undo.kb; + }; + + Position.prototype.legalMoves = function () { + + var legal = [], us = this.turn, them = us === 'w' ? 'b' : 'w'; + var pseudo = this.pseudoMoves(); + + for (var i = 0; i < pseudo.length; i++) { + var undo = this.make(pseudo[i]); + if (!this.isAttacked(this.king[us], them)) legal.push(pseudo[i]); + this.unmake(undo); + } + + return legal; + }; + + var SAN_RE = /^([NBRQK])?([a-h])?([1-8])?x?([a-h][1-8])(?:=?([NBRQnbrq]))?$/; + + Position.prototype.parseSan = function (san) { + + var text = String(san).replace(/[+#!?]+$/, '').trim(); + var moves = this.legalMoves(); + + var castle = /^(O-O-O|0-0-0)$/.test(text) ? 'q' : /^(O-O|0-0)$/.test(text) ? 'k' : null; + + if (castle) { + return moves.filter(function (move) { return move.castle === castle; })[0] || null; + } + + var match = SAN_RE.exec(text); + if (!match) return null; + + var type = (match[1] || 'P').toLowerCase(); + var ff = match[2] ? FILES.indexOf(match[2]) : -1; + var fr = match[3] ? parseInt(match[3], 10) - 1 : -1; + var to = parseSquare(match[4]); + var promo = match[5] ? match[5].toLowerCase() : null; + + var found = moves.filter(function (move) { + if (move.castle || move.t !== to) return false; + if (move.p.toLowerCase() !== type) return false; + if ((move.promo || null) !== promo) return false; + if (ff >= 0 && fileOf(move.f) !== ff) return false; + if (fr >= 0 && rankOf(move.f) !== fr) return false; + return true; + }); + + return found[0] || null; + }; + + function snapshot(pos, move, san, captured) { + + var legal = pos.legalMoves().length; + var check = pos.inCheck(); + var status = legal === 0 ? (check ? 'checkmate' : 'stalemate') : ''; + + return { + fen : pos.toFen(), + board : pos.boardString(), + turn : pos.turn, + from : move ? move.f : -1, + to : move ? move.t : -1, + check : check ? pos.king[pos.turn] : -1, + status : status, + san : san || '', + caps : { w: captured.w, b: captured.b } + }; + } + + /* Replays moves from a start position. Returns every position, the start + position first, and the first move that could not be played ( if any ). */ + + function replay(startFen, sans) { + + var pos = Position.fromFen(startFen || START_FEN); + var captured = { w: '', b: '' }; + var out = [snapshot(pos, null, '', captured)]; + + for (var i = 0; i < sans.length; i++) { + + var move = pos.parseSan(sans[i]); + + if (!move) { + return { positions: out, error: { ply: i, san: sans[i], turn: pos.turn } }; + } + + if (move.cap) captured[pos.turn] += move.cap; + + pos.make(move); + out.push(snapshot(pos, move, sans[i], captured)); + } + + return { positions: out, error: null }; + } + + /* Pulls a coordinate move ( like e2e4 ) out of free text, for engines that + report the illegal move they tried to play */ + + function findUciMove(text) { + + var match = /\b([a-h][1-8])([a-h][1-8])([qrbnQRBN])?\b/.exec(text || ''); + if (!match) return null; + + return { from: parseSquare(match[1]), to: parseSquare(match[2]), text: match[0] }; + } + + function material(boardString) { + + var total = { w: 0, b: 0 }; + + for (var i = 0; i < 64; i++) { + var piece = boardString[i]; + if (piece === '.') continue; + total[colorOf(piece)] += VALUES[piece.toLowerCase()]; + } + + return total; + } + + function perft(fen, depth) { + + var pos = Position.fromFen(fen); + + function walk(d) { + + var moves = pos.legalMoves(); + if (d === 1) return moves.length; + + var nodes = 0; + + for (var i = 0; i < moves.length; i++) { + var undo = pos.make(moves[i]); + nodes += walk(d - 1); + pos.unmake(undo); + } + + return nodes; + } + + return depth === 0 ? 1 : walk(depth); + } + + return { + START_FEN : START_FEN, + Position : Position, + replay : replay, + perft : perft, + material : material, + findUciMove : findUciMove, + squareName : name, + parseSquare : parseSquare, + fileOf : fileOf, + rankOf : rankOf + }; +}); diff --git a/OpenBench/static/event_viewer.js b/OpenBench/static/event_viewer.js new file mode 100644 index 0000000..0ff02e3 --- /dev/null +++ b/OpenBench/static/event_viewer.js @@ -0,0 +1,242 @@ +/* Event viewer: move navigation for PGNs, filtering for plain logs, and the + copy / download buttons. + + "index" is the number of moves played: 0 is the start position, and + moves.length is the position after the last move. + + Whenever the selection changes, a CustomEvent named "ob:ply" is dispatched + on document with + + event.detail = { index: , ply: , move: , moves: } + + board.js draws the board from it. window.OpenBenchViewer exposes + { moves, total, select(index), current(), copy(text, message), toast(message) }. */ + +(function () { + 'use strict'; + + function $(id) { return document.getElementById(id); } + + function readJSON(id, fallback) { + var element = $(id); + if (!element) return fallback; + try { return JSON.parse(element.textContent); } catch (error) { return fallback; } + } + + var raw = readJSON('ev-raw', ''); + var moves = readJSON('ev-moves', []); + var toastTimer = null; + + function toast(message) { + + var element = $('toast'); + if (!element) return; + + element.textContent = message; + element.classList.add('show'); + + window.clearTimeout(toastTimer); + toastTimer = window.setTimeout(function () { element.classList.remove('show'); }, 1800); + } + + function copyText(text) { + + if (navigator.clipboard && window.isSecureContext) return navigator.clipboard.writeText(text); + + return new Promise(function (resolve, reject) { + + var area = document.createElement('textarea'); + area.value = text; + area.style.position = 'fixed'; + area.style.opacity = '0'; + document.body.appendChild(area); + area.select(); + + try { document.execCommand('copy') ? resolve() : reject(); } + catch (error) { reject(error); } + finally { document.body.removeChild(area); } + }); + } + + function copy(text, message) { + return copyText(text).then(function () { toast(message || 'Copied to clipboard'); }, function () { toast('Copy failed'); }); + } + + function download(name, text) { + + var url = URL.createObjectURL(new Blob([text], { type: 'text/plain;charset=utf-8' })); + var link = document.createElement('a'); + + link.href = url; + link.download = name; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + + window.setTimeout(function () { URL.revokeObjectURL(url); }, 1000); + } + + function bindActions() { + + var copyButton = $('ev-copy'), save = $('ev-download'); + + if (copyButton) copyButton.addEventListener('click', function () { copy(raw, 'Copied to clipboard'); }); + + if (save) save.addEventListener('click', function () { + download(save.getAttribute('data-filename') || 'event.log', raw); + }); + } + + function setText(id, text) { + var element = $(id); + if (element) element.textContent = text; + } + + function initMoves() { + + var list = $('ev-movelist'); + + window.OpenBenchViewer = { + moves : moves, + total : moves.length, + copy : copy, + toast : toast + }; + + if (!list || !moves.length) return; + + var total = moves.length; + var buttons = {}; + var current = -1; + + Array.prototype.forEach.call(list.querySelectorAll('.ev-move[data-ply]'), function (button) { + var ply = parseInt(button.getAttribute('data-ply'), 10); + buttons[ply] = button; + button.addEventListener('click', function () { select(ply + 1, false); }); + }); + + function select(index, scroll) { + + index = Math.max(0, Math.min(total, index)); + + var move = index ? moves[index - 1] : null; + + if (buttons[current - 1]) { + buttons[current - 1].classList.remove('is-active'); + buttons[current - 1].removeAttribute('aria-selected'); + } + + current = index; + + var button = buttons[index - 1]; + if (button) { + button.classList.add('is-active'); + button.setAttribute('aria-selected', 'true'); + if (scroll !== false) { + list.scrollTop = Math.max(0, button.offsetTop - list.clientHeight / 2 + button.offsetHeight / 2); + } + } else if (scroll !== false) { + list.scrollTop = 0; + } + + setText('sel-counter', index + ' / ' + total); + setText('sel-label', move ? move.num + (move.color === 'w' ? '.' : '\u2026') : ''); + setText('sel-san', move ? move.san : 'Start position'); + setText('sel-eval', move && move.eval ? move.eval : '\u2013'); + setText('sel-depth', move && move.depth ? move.depth : '\u2013'); + setText('sel-time', move && move.time ? move.time : '\u2013'); + + var evalElement = $('sel-eval'); + if (evalElement) evalElement.className = 'mono ' + (move && move.tone ? move.tone : ''); + + var note = $('sel-note'); + if (note) { + note.textContent = move && move.note ? move.note : ''; + note.hidden = !(move && move.note); + } + + document.dispatchEvent(new CustomEvent('ob:ply', { + detail: { index: index, ply: index - 1, move: move, moves: moves } + })); + } + + document.addEventListener('keydown', function (event) { + + if (event.altKey || event.ctrlKey || event.metaKey) return; + if (/^(INPUT|TEXTAREA|SELECT)$/.test((event.target && event.target.tagName) || '')) return; + + var handled = true; + + switch (event.key) { + case 'ArrowLeft': select(current - 1); break; + case 'ArrowRight': select(current + 1); break; + case 'Home': select(0); break; + case 'End': select(total); break; + default: handled = false; + } + + if (handled) event.preventDefault(); + }); + + window.OpenBenchViewer.select = select; + window.OpenBenchViewer.current = function () { return current; }; + + // Start on the last move, which is usually the one that ended the game + select(total); + } + + function initLog() { + + var body = $('log-body'); + if (!body) return; + + var filter = $('log-filter'), wrap = $('log-wrap'), issues = $('log-issues'); + var empty = $('log-empty'); + + var lines = Array.prototype.map.call(body.querySelectorAll('.ev-line'), function (line) { + return { + element : line, + level : line.getAttribute('data-level'), + text : line.querySelector('.ev-lt').textContent.toLowerCase() + }; + }); + + function apply() { + + var query = filter ? filter.value.trim().toLowerCase() : ''; + var only = issues ? issues.checked : false; + var shown = 0; + + lines.forEach(function (line) { + var visible = (!query || line.text.indexOf(query) !== -1) && (!only || line.level !== 'info'); + line.element.hidden = !visible; + if (visible) shown++; + }); + + if (empty) empty.hidden = shown !== 0; + } + + if (filter) filter.addEventListener('input', apply); + if (issues) issues.addEventListener('change', apply); + + if (wrap) wrap.addEventListener('change', function () { + body.classList.toggle('ev-wrap', wrap.checked); + }); + + // Jump to the first problem, since that is what people came here for + var first = body.querySelector('.ev-line-bad'); + if (first) body.scrollTop = Math.max(0, first.offsetTop - body.clientHeight / 3); + } + + function ready(fn) { + if (document.readyState !== 'loading') fn(); + else document.addEventListener('DOMContentLoaded', fn); + } + + ready(function () { + bindActions(); + initMoves(); + initLog(); + }); + +})(); diff --git a/OpenBench/static/ux.css b/OpenBench/static/ux.css new file mode 100644 index 0000000..3661fc4 --- /dev/null +++ b/OpenBench/static/ux.css @@ -0,0 +1,764 @@ +/* =========================================================================== + OpenBench - UX layer + + Loaded after style.css and builds on its design tokens ( --color*, --accent, + --line, ... ). Everything new lives here, so the base theme stays untouched + and this file is easy to review, tweak, or drop. + =========================================================================== */ + +:root { + + /* Slightly softer corners than the base theme ( 2px ). + Set this back to 2px to revert the rounding everywhere. */ + --radius: 4px; + + --purple: #A78BFA; + --purple-soft: rgba(167, 139, 250, 0.14); + --shadow-card: inset 0 1px 0 rgba(255, 255, 255, 0.025), 0 1px 3px rgba(0, 0, 0, 0.3); +} + +/* ---------- Depth + interaction polish ---------- */ + +.card { + box-shadow: var(--shadow-card); +} + +#content table.hoverable tr:not(.table-header):not(.table-spacer):not(.table-spacer-small):hover > td:first-child { + box-shadow: inset 2px 0 0 var(--accent); +} + +#content tr[data-href] { + cursor: pointer; +} + +#content th.numeric { + text-align: right; +} + +#content th.sorted { + color: var(--color-font1); +} + +.muted-small { + color: var(--muted); + font-size: 12.5px; +} + +/* ---------- Sidebar: collapsible sections ---------- */ + +#sidebar .nav-title.collapsible { + display: flex; + align-items: center; + justify-content: space-between; + cursor: pointer; + user-select: none; + border-radius: var(--radius); +} + +#sidebar .nav-title.collapsible:hover { + color: var(--color-font2); +} + +#sidebar .nav-title.collapsible::after { + content: ''; + width: 6px; + height: 6px; + margin-right: 4px; + border-right: 1.5px solid currentColor; + border-bottom: 1.5px solid currentColor; + transform: rotate(45deg) translate(-1px, -1px); + transition: transform 0.15s ease; +} + +#sidebar .nav-section.collapsed .nav-title.collapsible::after { + transform: rotate(-45deg); +} + +#sidebar .nav-section.collapsed ul { + display: none; +} + +/* ---------- Stat cards ---------- */ + +.stat-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); + gap: 12px; + margin-bottom: 20px; +} + +.stat-card { + display: flex; + align-items: center; + gap: 14px; + min-width: 0; + padding: 14px 16px; + background-color: var(--color2); + border: 1px solid var(--line); + border-radius: var(--radius); + box-shadow: var(--shadow-card); +} + +.stat-icon { + display: grid; + place-items: center; + flex: none; + width: 40px; + height: 40px; + border-radius: var(--radius); + background-color: var(--accent-soft); + color: var(--accent-hover); + font-size: 16px; +} + +.stat-green .stat-icon { background-color: rgba(52, 211, 153, 0.13); color: var(--ok); } +.stat-yellow .stat-icon { background-color: rgba(245, 185, 65, 0.13); color: var(--warn); } +.stat-purple .stat-icon { background-color: var(--purple-soft); color: var(--purple); } + +.stat-value { + color: var(--color-font1); + font-family: var(--font-mono); + font-size: 22px; + font-weight: 650; + line-height: 1.1; + font-variant-numeric: tabular-nums; +} + +.stat-label { + margin-top: 2px; + color: var(--muted); + font-size: 11.5px; + font-weight: 600; + letter-spacing: 0.1em; + text-transform: uppercase; +} + +.stat-sub { + margin-top: 2px; + color: var(--muted); + font-size: 12px; +} + +/* ---------- Test progress ---------- */ + +.ob-progress { + min-width: 96px; + height: 3px; + margin-top: 7px; + border-radius: 2px; + background-color: var(--line); + overflow: hidden; +} + +.ob-progress > span { + display: block; + height: 100%; + border-radius: inherit; + background-color: var(--accent); + transition: width 0.4s ease; +} + +.ob-progress-pos > span { background-color: var(--ok); } +.ob-progress-neg > span { background-color: var(--bad); } + +/* ---------- Empty states ---------- */ + +#content .empty-row td { + padding: 38px 14px; +} + +#content .empty-row i { + display: block; + margin-bottom: 10px; + font-size: 24px; + opacity: 0.55; +} + +.empty-state { + padding: 52px 20px; + color: var(--muted); + text-align: center; +} + +.empty-state i { + display: block; + margin-bottom: 12px; + font-size: 28px; + opacity: 0.5; +} + +.empty-state p { + margin: 0; +} + +/* ---------- Segmented control ---------- */ + +.seg { + display: inline-flex; + gap: 2px; + padding: 3px; + background-color: var(--color2); + border: 1px solid var(--line); + border-radius: calc(var(--radius) + 2px); +} + +#content a.seg-btn:link, +#content a.seg-btn:visited { + padding: 5px 13px; + border-radius: var(--radius); + color: var(--color-font2); + font-size: 13px; + font-weight: 500; + transition: background-color 0.15s ease, color 0.15s ease; +} + +#content a.seg-btn:hover { + background-color: var(--surface-hover); + color: var(--color-font1); +} + +#content a.seg-btn.active { + background-color: var(--accent-soft); + box-shadow: inset 0 0 0 1px rgba(76, 141, 255, 0.4); + color: var(--color-font1); +} + +/* ---------- Users: STC / LTC split ---------- */ + +.splitbar { + display: flex; + min-width: 150px; + height: 8px; + border-radius: 4px; + background-color: var(--line); + overflow: hidden; +} + +.splitbar-lg { + height: 12px; + border-radius: 6px; +} + +.splitbar > span { + display: block; + height: 100%; +} + +.splitbar-stc { background-color: var(--accent); } +.splitbar-ltc { background-color: var(--purple); } +.splitbar-other { background-color: #566074; } + +.legend { + display: flex; + flex-wrap: wrap; + gap: 4px 16px; + color: var(--color-font2); + font-size: 12.5px; + font-weight: 500; +} + +.legend .dot { + display: inline-block; + width: 9px; + height: 9px; + margin-right: 7px; + border-radius: 2px; + vertical-align: middle; +} + +.dot-stc { background-color: var(--accent); } +.dot-ltc { background-color: var(--purple); } +.dot-other { background-color: #566074; } + +.split-overview { + padding: 16px; +} + +.split-overview p { + margin: 12px 0 0; +} + +#content td.num-stc { color: var(--accent-hover); } +#content td.num-ltc { color: var(--purple); } + +#content td.rank { + width: 44px; + color: var(--muted); + font-family: var(--font-mono); +} + +/* ---------- Errors table ---------- */ + +#content a.ev-open:link, +#content a.ev-open:visited { + display: inline-flex; + align-items: center; + gap: 7px; + font-weight: 600; +} + +#content a.ev-open i { + font-size: 11px; + transition: transform 0.15s ease; +} + +#content tr:hover a.ev-open i { + transform: translateX(3px); +} + +.tc-chip { + margin-left: 8px; + color: var(--muted); + font-family: var(--font-mono); + font-size: 12px; +} + +/* ---------- Event viewer ---------- */ + +#content a.crumb:link, +#content a.crumb:visited { + display: inline-flex; + align-items: center; + gap: 8px; + margin-bottom: 8px; + color: var(--muted); + font-size: 13px; + font-weight: 500; +} + +#content a.crumb:hover { + color: var(--color-font1); +} + +.ev-meta { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); + gap: 1px; + margin: 0 0 20px; + background-color: var(--line); + border: 1px solid var(--line); + border-radius: var(--radius); + overflow: hidden; +} + +.ev-meta > div { + min-width: 0; + padding: 11px 14px; + background-color: var(--color2); +} + +.ev-meta dt { + margin-bottom: 4px; + color: var(--muted); + font-size: 11px; + font-weight: 600; + letter-spacing: 0.1em; + text-transform: uppercase; +} + +.ev-meta dd { + margin: 0; + overflow: hidden; + color: var(--color-font1); + font-size: 14px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.ev-versus { + display: grid; + grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); + align-items: center; + gap: 16px; + padding: 24px 20px; +} + +.ev-player { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 0; +} + +.ev-player strong { + overflow: hidden; + color: var(--color-font1); + font-size: 18px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.ev-player small { + display: flex; + align-items: center; + gap: 7px; + color: var(--muted); + font-size: 11.5px; + font-weight: 600; + letter-spacing: 0.1em; + text-transform: uppercase; +} + +.ev-black { + align-items: flex-end; + text-align: right; +} + +.ev-black small { + flex-direction: row-reverse; +} + +.ev-piece { + display: inline-block; + width: 10px; + height: 10px; + border: 1px solid var(--line-strong); + border-radius: 50%; +} + +.ev-white .ev-piece { background-color: #F1F4FA; } +.ev-black .ev-piece { background-color: #0B0E14; } + +.ev-result { + padding: 6px 16px; + background-color: var(--color1); + border: 1px solid var(--line-strong); + border-radius: var(--radius); + color: var(--color-font1); + font-size: 22px; + font-weight: 650; +} + +.ev-callout { + display: flex; + align-items: flex-start; + gap: 12px; + margin: 0 20px 18px; + padding: 12px 14px; + background-color: var(--color1); + border: 1px solid var(--line); + border-left: 3px solid currentColor; + border-radius: var(--radius); +} + +.ev-callout i { + margin-top: 3px; +} + +.ev-callout-bad { color: var(--bad); } +.ev-callout-warn { color: var(--warn); } +.ev-callout-info { color: var(--accent); } + +.ev-callout-body { + min-width: 0; + color: var(--color-font2); + word-break: break-word; +} + +.ev-callout-body strong { + display: block; + color: var(--color-font1); +} + +.ev-facts { + display: flex; + flex-wrap: wrap; + gap: 10px 32px; + margin: 0; + padding: 14px 20px 16px; + border-top: 1px solid var(--line); +} + +.ev-facts > div { + min-width: 0; +} + +.ev-facts dt { + margin-bottom: 2px; + color: var(--muted); + font-size: 11px; + font-weight: 600; + letter-spacing: 0.1em; + text-transform: uppercase; +} + +.ev-facts dd { + margin: 0; + color: var(--color-font1); + font-size: 13px; + word-break: break-all; +} + +.ev-headers { + border-top: 1px solid var(--line); +} + +.ev-headers summary { + padding: 11px 20px; + color: var(--muted); + font-size: 12.5px; + font-weight: 600; + cursor: pointer; + user-select: none; +} + +.ev-headers summary:hover { + color: var(--color-font1); +} + +.ev-headers table { + width: 100%; + margin: 0 0 8px; +} + +.ev-headers td:first-child { + width: 180px; + color: var(--muted); +} + +.ev-movelist { + position: relative; + max-height: 580px; + padding: 8px; + overflow-y: auto; + font-family: var(--font-mono); + font-size: 13px; + outline: none; +} + +.ev-row { + display: grid; + grid-template-columns: 46px minmax(0, 1fr) minmax(0, 1fr); + gap: 2px; +} + +.ev-num { + padding: 7px 8px; + color: var(--muted); + text-align: right; +} + +.ev-move { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + padding: 7px 10px; + background: transparent; + border: 1px solid transparent; + border-radius: var(--radius); + color: var(--color-font1); + font: inherit; + text-align: left; + cursor: pointer; + transition: background-color 0.12s ease; +} + +button.ev-move:hover { + background-color: var(--surface-hover); +} + +.ev-move.is-active { + background-color: var(--accent-soft); + border-color: rgba(76, 141, 255, 0.45); +} + +.ev-move.is-final { + box-shadow: inset 2px 0 0 var(--bad); +} + +.ev-move.ev-empty { + color: var(--muted); + cursor: default; +} + +.ev-eval { + color: var(--muted); + font-size: 11.5px; + font-style: normal; +} + +.ev-eval.pos, #sel-eval.pos { color: var(--ok); } +.ev-eval.neg, #sel-eval.neg { color: var(--bad); } + +.ev-sel { + padding: 16px; +} + +.ev-sel-main { + display: flex; + align-items: baseline; + gap: 8px; +} + +.ev-sel-label { + color: var(--muted); + font-size: 15px; +} + +.ev-sel-san { + color: var(--color-font1); + font-size: 28px; + font-weight: 650; +} + +.ev-sel-stats { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 8px; + margin-top: 14px; +} + +.ev-sel-stats > div { + padding: 9px 11px; + background-color: var(--color1); + border: 1px solid var(--line); + border-radius: var(--radius); +} + +.ev-sel-stats span { + display: block; + margin-bottom: 2px; + color: var(--muted); + font-size: 10.5px; + font-weight: 600; + letter-spacing: 0.1em; + text-transform: uppercase; +} + +.ev-sel-stats strong { + color: var(--color-font1); + font-size: 14px; +} + +.ev-sel-note { + margin: 12px 0 0; + padding: 9px 11px; + border-left: 3px solid var(--warn); + border-radius: var(--radius); + background-color: rgba(245, 185, 65, 0.08); + color: var(--color-font2); + font-size: 13px; +} + +.ev-sel-note[hidden] { + display: none; +} + +/* Plain text logs */ + +.ev-tools { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 14px; +} + +.ev-input { + width: 220px; + max-width: 100%; + padding: 6px 10px; + background-color: var(--color1); + border: 1px solid var(--line-strong); + border-radius: var(--radius); + color: var(--color-font1); + font-family: var(--font-sans); + font-size: 13px; +} + +.ev-input::placeholder { + color: var(--muted); +} + +.ev-toggle { + display: inline-flex; + align-items: center; + gap: 6px; + color: var(--color-font2); + font-size: 12.5px; + cursor: pointer; + user-select: none; +} + +.ev-logbody { + max-height: 70vh; + padding: 8px 0; + overflow: auto; + background-color: var(--color1); + font-family: var(--font-mono); + font-size: 12.5px; + line-height: 1.55; +} + +.ev-line { + display: flex; + gap: 14px; + padding: 0 14px; + border-left: 2px solid transparent; +} + +.ev-line[hidden] { + display: none; +} + +.ev-line:hover { + background-color: var(--surface-hover); +} + +.ev-ln { + flex: 0 0 48px; + color: #4A5469; + text-align: right; + user-select: none; +} + +.ev-lt { + min-height: 1.55em; + color: var(--color-font2); + white-space: pre; +} + +.ev-wrap .ev-lt { + min-width: 0; + white-space: pre-wrap; + word-break: break-word; +} + +.ev-line-bad { background-color: rgba(248, 113, 113, 0.08); border-left-color: var(--bad); } +.ev-line-warn { background-color: rgba(245, 185, 65, 0.07); border-left-color: var(--warn); } +.ev-line-bad .ev-lt { color: #FFB4B4; } +.ev-line-warn .ev-lt { color: #FFD479; } + +.ev-log-note { + padding: 8px 14px; + border-bottom: 1px solid var(--line); + color: var(--muted); + font-size: 12.5px; +} + +/* ---------- Responsive ---------- */ + +@media (max-width: 767px) { + + .ev-versus { + grid-template-columns: 1fr; + gap: 10px; + } + + .ev-black { + align-items: flex-start; + text-align: left; + } + + .ev-black small { + flex-direction: row; + } + + .ev-result { + justify-self: start; + } + + .ev-meta dd { + white-space: normal; + } +} diff --git a/OpenBench/static/ux.js b/OpenBench/static/ux.js new file mode 100644 index 0000000..f11e188 --- /dev/null +++ b/OpenBench/static/ux.js @@ -0,0 +1,149 @@ +/* OpenBench UX layer: small progressive enhancements, no dependencies. + Every feature degrades gracefully when this file does not load. */ + +(function () { + 'use strict'; + + function ready(fn) { + if (document.readyState !== 'loading') fn(); + else document.addEventListener('DOMContentLoaded', fn); + } + + function normalise(path) { + path = (path || '').replace(/\/+$/, ''); + return path === '' ? '/' : path.toLowerCase(); + } + + /* Highlight the sidebar entry for the current page. Pages that live under + another section ( an event belongs to Errors or Events ) can say so with + a data-nav="/errors" attribute anywhere in their content. */ + + function highlightNav() { + + var nav = document.getElementById('sidebar'); + if (!nav) return; + + var hint = document.querySelector('[data-nav]'); + var current = normalise(hint ? hint.getAttribute('data-nav') : window.location.pathname); + + if (current === '/' || /^\/index(\/|$)/.test(current)) current = '/index'; + + var best = null, bestLength = -1; + + Array.prototype.forEach.call(nav.querySelectorAll('li a'), function (link) { + + if (link.origin !== window.location.origin) return; + + var path = normalise(link.pathname); + var hit = current === path || current.indexOf(path + '/') === 0; + + if (hit && path.length > bestLength) { best = link; bestLength = path.length; } + }); + + if (best) { + best.classList.add('active'); + best.setAttribute('aria-current', 'page'); + } + } + + /* Sidebar sections can be folded, and the choice is remembered. The list of + Engines starts folded, since it grows with every engine added. */ + + function collapsibleNav() { + + var KEY = 'ob:nav:collapsed'; + var collapsed = ['Engines']; + + try { + var stored = JSON.parse(window.localStorage.getItem(KEY)); + if (Array.isArray(stored)) collapsed = stored; + } catch (error) { /* storage unavailable, use the default */ } + + Array.prototype.forEach.call(document.querySelectorAll('#sidebar .nav-section'), function (section) { + + var title = section.querySelector('.nav-title'); + if (!title) return; + + var name = title.textContent.trim(); + + title.classList.add('collapsible'); + title.setAttribute('role', 'button'); + title.setAttribute('tabindex', '0'); + + function apply(state) { + section.classList.toggle('collapsed', state); + title.setAttribute('aria-expanded', String(!state)); + } + + // Never hide the section that holds the current page + apply(collapsed.indexOf(name) !== -1 && !section.querySelector('a.active')); + + function toggle() { + + var state = !section.classList.contains('collapsed'); + var index = collapsed.indexOf(name); + + apply(state); + + if (state && index === -1) collapsed.push(name); + if (!state && index !== -1) collapsed.splice(index, 1); + + try { window.localStorage.setItem(KEY, JSON.stringify(collapsed)); } catch (error) { /* ignore */ } + } + + title.addEventListener('click', toggle); + title.addEventListener('keydown', function (event) { + if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); toggle(); } + }); + }); + } + + /* Browser tabs say what the page is, instead of "RektBench" everywhere */ + + function setPageTitle() { + + var heading = document.querySelector('.page-title'); + var brand = document.querySelector('.brand-name'); + if (!heading) return; + + var name = brand ? brand.textContent.trim() : 'OpenBench'; + document.title = heading.textContent.trim() + ' \u00B7 ' + name; + } + + /* Whole rows of the test lists are clickable. Real links, buttons, and text + selection keep working as usual. */ + + function clickableRows() { + + var rows = document.querySelectorAll('#content table.test-list tbody tr'); + + Array.prototype.forEach.call(rows, function (row) { + var link = row.querySelector('.col-test a'); + if (link && !row.getAttribute('data-href')) row.setAttribute('data-href', link.getAttribute('href')); + }); + + document.addEventListener('click', function (event) { + + if (event.defaultPrevented || !event.target.closest) return; + + var row = event.target.closest('tr[data-href]'); + if (!row) return; + + if (event.target.closest('a, button, input, select, textarea, label, summary')) return; + if (window.getSelection && String(window.getSelection())) return; + + var href = row.getAttribute('data-href'); + + if (event.metaKey || event.ctrlKey) window.open(href, '_blank'); + else window.location.href = href; + }); + } + + ready(function () { + highlightNav(); + collapsibleNav(); + setPageTitle(); + clickableRows(); + }); + +})(); diff --git a/OpenBench/templatetags/uitags.py b/OpenBench/templatetags/uitags.py new file mode 100644 index 0000000..90e739c --- /dev/null +++ b/OpenBench/templatetags/uitags.py @@ -0,0 +1,86 @@ +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# # +# Template filters for the UX layer ( status dots, progress bars, ... ). # +# Kept apart from mytags.py. Use with {% load uitags %} # +# # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +import re + +from django import template + +from OpenBench.uiutils import event_tone + +register = template.Library() + +@register.filter +def test_status(test): + + # One of: running, pending, awaiting, passed, failed, stopped, deleted + + if test.deleted: + return 'deleted' + + if test.finished: + if test.passed: return 'passed' + if test.failed: return 'failed' + return 'stopped' + + if not test.approved: + return 'pending' + + if test.awaiting: + return 'awaiting' + + return 'running' + +@register.filter +def progress_info(test): + + # Only running tests get a progress bar. Returns None, or a dict holding the + # percentage and a tone: pos ( leaning to a pass ), neg ( leaning to a fail ), + # or neutral ( for tests without a meaningful direction ) + + if test_status(test) != 'running': + return None + + try: + + if test.test_mode == 'SPRT': + + current, lower, upper = float(test.currentllr), float(test.lowerllr), float(test.upperllr) + + if current >= 0 and upper > 0: + fraction, tone = current / upper, 'pos' if current > 0 else 'neutral' + elif current < 0 and lower < 0: + fraction, tone = current / lower, 'neg' + else: + fraction, tone = 0.0, 'neutral' + + return { 'pct' : int(max(0.0, min(1.0, fraction)) * 100), 'tone' : tone } + + if test.max_games: + fraction = test.games / float(test.max_games) + return { 'pct' : int(max(0.0, min(1.0, fraction)) * 100), 'tone' : 'neutral' } + + except (TypeError, ValueError, ZeroDivisionError): + pass + + return None + +@register.filter +def fleet_stats(status): + + # Parses the string from utils.getMachineStatus(), which looks like + # ": 3 Machines / 48 Threads / 12.5 MNPS " + + match = re.search(r'(\d+)\s+Machines\s*/\s*(\d+)\s+Threads\s*/\s*([\d.]+)\s+MNPS', status or '') + + if not match: + return None + + return { 'machines' : int(match.group(1)), 'threads' : int(match.group(2)), 'mnps' : match.group(3) } + +@register.filter(name='event_tone') +def event_tone_filter(summary): + return event_tone(summary) diff --git a/OpenBench/uiutils.py b/OpenBench/uiutils.py new file mode 100644 index 0000000..d2cd3aa --- /dev/null +++ b/OpenBench/uiutils.py @@ -0,0 +1,381 @@ +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# # +# UI helpers for the OpenBench website. # +# # +# Kept out of views.py / utils.py so the presentation logic ( time control # +# buckets, PGN and log parsing for the event viewer ) is easy to find, # +# test, and extend. Nothing in here touches the database schema. # +# # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +import re + +from functools import lru_cache + +from django.db.models import Sum + +from OpenBench.models import Profile, Result + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# TIME CONTROLS # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +# Fischer time controls with a base time below this many seconds are STC, and +# anything at or above it is LTC. ( 10+0.1 is STC, 60+0.6 is LTC ) +STC_MAX_BASE_SECONDS = 30 + +BUCKETS = ('STC', 'LTC', 'OTHER') + +START_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1' + +@lru_cache(maxsize=512) +def classify_time_control(time_control): + + # Imported here, since utils.py imports views.py which imports this module + from OpenBench.utils import TimeControl + + try: + tc = str(time_control or '') + + # Fixed nodes, depth, movetime, and cyclic controls are not STC or LTC + if TimeControl.control_type(tc) != TimeControl.FISCHER: + return 'OTHER' + + base = TimeControl.control_base(tc) + return 'STC' if base < STC_MAX_BASE_SECONDS else 'LTC' + + except Exception: + return 'OTHER' + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# USERS PAGE # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +SORT_KEYS = { + 'total' : lambda row: (-row['total'], -row['tests']), + 'stc' : lambda row: (-row['stc' ], -row['total']), + 'ltc' : lambda row: (-row['ltc' ], -row['total']), + 'tests' : lambda row: (-row['tests'], -row['total']), +} + +def _share(part, whole): + # Returned as a string, so templates never localise it into "63,20" + return '%.2f' % (100.0 * part / whole) if whole else '0.00' + +def users_context(request): + + sort = request.GET.get('sort', 'total') + if sort not in SORT_KEYS: + sort = 'total' + + # Games are credited to whoever's machines played them, which is not + # necessarily the author of the test. Results hold one row per (test, machine) + # so grouping by user and time control in the database stays cheap. + + per_user = {} + grouped = Result.objects.values('machine__user__username', 'test__dev_time_control') + grouped = grouped.annotate(total=Sum('games')) + + for entry in grouped: + buckets = per_user.setdefault(entry['machine__user__username'], dict.fromkeys(BUCKETS, 0)) + buckets[classify_time_control(entry['test__dev_time_control'])] += entry['total'] or 0 + + rows = [] + for profile in Profile.objects.select_related('user'): + + if not (profile.games or profile.tests or profile.approver): + continue + + buckets = per_user.get(profile.user.username, dict.fromkeys(BUCKETS, 0)) + split = sum(buckets.values()) + + rows.append({ + 'username' : profile.user.username, + 'approver' : profile.approver, + 'engine' : profile.engine, + 'joined' : profile.user.date_joined, + 'total' : profile.games, + 'tests' : profile.tests, + 'stc' : buckets['STC' ], + 'ltc' : buckets['LTC' ], + 'other' : buckets['OTHER'], + 'stc_share' : _share(buckets['STC' ], split), + 'ltc_share' : _share(buckets['LTC' ], split), + 'oth_share' : _share(buckets['OTHER'], split), + }) + + rows.sort(key=lambda row: SORT_KEYS[sort](row) + (row['username'].lower(),)) + + stc = sum(row['stc' ] for row in rows) + ltc = sum(row['ltc' ] for row in rows) + other = sum(row['other'] for row in rows) + whole = stc + ltc + other + + summary = { + 'users' : len(rows), + 'total' : sum(row['total'] for row in rows), + 'stc' : stc, + 'ltc' : ltc, + 'other' : other, + 'stc_share' : _share(stc, whole), + 'ltc_share' : _share(ltc, whole), + 'oth_share' : _share(other, whole), + } + + return { + 'rows' : rows, + 'summary' : summary, + 'sort' : sort, + 'show_other' : other > 0, + 'stc_limit' : STC_MAX_BASE_SECONDS, + } + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# EVENT VIEWER # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +def event_tone(summary): + + # Colour used for badges: bad ( red ), warn ( amber ), info ( blue ) + text = (summary or '').lower() + + bad = ('illegal', 'disconnect', 'crash', 'fail', 'bad bench', 'missing', 'error') + if any(word in text for word in bad): + return 'bad' + + if any(word in text for word in ('stall', 'timeout', 'timeloss', 'warn')): + return 'warn' + + return 'info' + +# When a worker reports an Illegal Move, Disconnect, or Stalled game, the client +# uploads the PGN of that game ( see PGNHelper.pretty_format in Client/worker.py ). +# Other events ( build failures, bad benches, ... ) carry plain text logs. + +PGN_PROBE_RE = re.compile(r'^\s*\[Event\s+"', re.MULTILINE) +HEADER_RE = re.compile(r'^\[(\w+)\s+"(.*)"\]\s*$') +TOKEN_RE = re.compile(r'\{[^}]*\}|\([^)]*\)|\$\d+|\d+\.(?:\.\.)?|1-0|0-1|1/2-1/2|\*|[^\s{}()]+') +NUMBER_RE = re.compile(r'^\d+\.(?:\.\.)?$') +EVAL_RE = re.compile(r'^(?P[+-]?(?:M\d+|\d+(?:\.\d+)?))/(?P\d+)(?:\s+(?P