Compare commits

..
62 Commits
Author SHA1 Message Date
claude 7ab973ff67 Merge pull request 'Gitea sources without a token: direct archive links' (#17) from gitea-anonymous into master 2026-11-15 01:30:35 +01:00
rektdieandclaude 4bd7a68864 Gitea sources without a token: direct archive links
With REQUIRE_SIGNIN_VIEW off, public Gitea repositories can be read
anonymously, so the token is no longer required. Without one, the server
calls the Gitea API without credentials and hands workers the plain
<repo>/archive/<commit>.zip link, like Github. With a token, private
repositories still go through the signed /giteaSource/ proxy.

When a lookup fails without a token, the error says the repository must
be public.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 01:30:15 +01:00
claude 30032fd42d Merge pull request 'Add Rigby (MCTS engine) to the engine list' (#15) from add-rigby into master 2026-11-15 00:46:10 +01:00
claude f915c30f02 Merge pull request 'Accept engine sources from Gitea servers' (#16) from gitea-sources into master 2026-11-15 00:45:59 +01:00
rektdieandclaude 754283d95e Sign Gitea source links with the Gitea token
settings.py, SECRET_KEY included, is part of the public repository, so
links signed with it could be forged to read any repository the token can
see. The token in Config/credentials.gitea is gitignored and is now the
signing key. Without a token, Gitea tests are refused at creation and no
link validates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:45:17 +01:00
rektdieandclaude e8cd615d83 Rigby: take sources from Gitea
Needs the Gitea source support from the gitea-sources branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:43:28 +01:00
rektdieandclaude c721cc6b5b Accept engine sources from Gitea servers
Tests, tunes and datagen could only use https://github.com/<user>/<repo>.
Gitea servers listed under "gitea_hosts" in Config/config.json are now
accepted too, starting with https://gitea.rektdie.com.

- OpenBench/git_hosts.py holds all host logic: repo validation, API base,
  resolving a branch/tag/sha, compare counts, diff links and source URLs.
- The server talks to Gitea with the token in Config/credentials.gitea and
  sends it nowhere else; Github requests stay unchanged.
- Gitea may require a login even to read, so workers cannot download the
  archive themselves. The server gives them a /giteaSource/ link signed with
  an HMAC of repo and commit (SECRET_KEY), and streams the archive from the
  Gitea API. No client change, no client version bump.
- Diff links, the out-of-date check and the profile page handle Gitea repos;
  the repo fields of the forms accept every configured prefix.
- Private engines stay Github-only, they depend on Github Actions artifacts.
- Static version bumped to v5 for the changed default_text.js.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:42:43 +01:00
rektdieandclaude 619d29b12e Add Rigby (MCTS engine) to the engine list
Rigby is a PUCT search engine, so its tree needs far more memory than an
alpha-beta hash: STC and LTC run with Hash=64 and Hash=256. Non-regression
presets are included for simplifications. Reference nps is calibrated
against Eleanor on the same machine (1.10M measured for 800k reference,
Rigby measures 1.08M).

The source points at a GitHub mirror, because test creation only accepts
github.com repositories.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:36:42 +01:00
claude d77f096932 Make the site discoverable as "RektBench" in search engines (#14) 2026-10-11 22:18:32 +02:00
claude 07935271cb Redesign site icon to match the theme (#13) 2026-10-11 21:59:44 +02:00
rektdie 0e39c20ef3 Merge pull request 'Spsa panel' (#12) from spsa-panel into master
Reviewed-on: #12
2026-10-11 21:31:09 +02:00
claude 22bb0b934d Tune page: live updates that keep the SPSA panel interactive
live.js already polled /tune/<id>, but patching the page in place would have
wiped the chart, reordered the parameter rows under their listeners, dropped
pinned lines and closed any fold the reader had opened.

- live.js: leave the chart, the parameter list and its empty notice alone, keep
  the 'open' attribute of folds, and fire a 'live:patched' event with the fresh
  page after every patch.
- spsa_chart.js: on that event, hand the new history to the existing chart
  (pinned lines and the inspected point stay), or build it if the first results
  have just arrived.
- spsa_panel.js: on that event, refresh the numbers, bars and limit markers of
  each row in place, and re-sort when sorted by movement without jumping the
  scroll position.
2026-10-11 20:43:21 +02:00
claude 0167e19057 Tune page: collapsible Results by Machine, padding inside the progress panel and below Modify
- Results by Machine is a fold on Tune pages, closed by default, like the other
  secondary sections.
- .card has no padding of its own, so the content of the Tuning progress panel
  ran up to the border. It now keeps 16px clear on both sides and at the bottom.
- The Actions card ended on the Modify button with 4px below it; it now has 16px.
2026-10-11 20:42:25 +02:00
claude efc0a42f8b Tune page: keep the SPSA parameter list to a bounded, scrollable height
The list used to grow with the number of parameters and pushed the results
table far down the page. It now scrolls inside the panel, with the filter and
sort bar staying in view, and jumps back to the top when the order or filter
changes.
2026-10-11 20:35:16 +02:00
claude 87886c5771 Revert "Tune page: chart and parameter list side by side, every secondary section collapsed"
This reverts commit 7269fd96e9. Restores workload.html and spsa_chart.css to the state of de5ec59.
2026-10-11 20:34:13 +02:00
claude 7269fd96e9 Tune page: chart and parameter list side by side, every secondary section collapsed
The progress summary, the movement chart and a scrollable parameter list now
share one panel. Settings, Actions, Parameter details and Contributors are
single-line folds, closed by default, so the page fits on roughly one screen.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TyAt5S5MAwLBY2idan1SwU
2026-10-11 18:52:04 +02:00
claude de5ec59ece Tune page: parameter history chart, two-column layout, collapsed settings
Record every SPSA parameter value as results arrive (media/spsa_history/<id>.json,
same idea as the LLR history). The Tune page plots how far each parameter has
moved from its start, as a share of its allowed range. Hovering or pinning a
parameter name follows its line. The page is now a main column (progress,
history, results, details) plus a side column (actions, settings), and the
settings and parameter details start collapsed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TyAt5S5MAwLBY2idan1SwU
2026-10-11 18:43:54 +02:00
claude 9aa7678b62 Tune page: visual SPSA parameter panel
Each parameter gets a range track (min to max) with its start tick, current
value and the drift between them. The panel header shows iteration progress.
Parameters can be filtered by name and sorted by how far they moved. The old
table stays below as "Parameter details".

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TyAt5S5MAwLBY2idan1SwU
2026-10-11 18:37:35 +02:00
claude 4fffbf50b4 Merge pull request 'Design refresh: new theme, Ctrl+K quick search, live updates' (#11) from design-refresh into master 2026-10-11 17:52:35 +02:00
claude d5cea13fd6 Live updates: keep the LLR history graph current 2026-10-11 17:49:31 +02:00
claude deb68caa64 LLR history: redraw in place when newer data arrives 2026-10-11 17:49:25 +02:00
claude 6a024f3e5a Live updates: load live.css and live.js 2026-10-11 17:39:54 +02:00
claude 9aa9a2b447 Live updates: styles 2026-10-11 17:39:50 +02:00
claude c367dd761a Live updates: pages refresh themselves in place 2026-10-11 17:39:43 +02:00
claude 05275645f5 Quick search: build workload urls in the view 2026-10-11 17:29:32 +02:00
claude 5793204b1b Quick search: Ctrl+K palette, live test endpoint and wiring 2026-10-11 17:29:20 +02:00
claude 26a0394ca9 Quick search: palette behaviour 2026-10-11 17:28:50 +02:00
claude d2827ee8f3 Quick search: fix font fallbacks 2026-10-11 17:28:19 +02:00
claude 963ba2151e Quick search: palette styles 2026-10-11 17:28:10 +02:00
claude 977ac2e4f9 Quick search: drop the Discord entry 2026-10-11 17:27:52 +02:00
claude 0b8862cc2c Quick search: palette markup partial 2026-10-11 12:56:01 +02:00
claude cbf4e59672 Index: drop the Awaiting artifacts counter card 2026-10-11 12:47:06 +02:00
claude 0dab31718a Restore result cell styling (outline, hatching, clearer blue) 2026-10-11 12:27:50 +02:00
claude 142296006b Workload page: revert hero, Dev/Base table, action hiding and confirms; keep full author names and server-rendered timestamps 2026-10-11 12:26:12 +02:00
claude 54538edcb1 Test list: drop state class from result cell 2026-10-11 12:25:23 +02:00
claude 44d6bfe7e8 Remove result cell restyling (outline, hatching, blue); keep full author names 2026-10-11 12:25:18 +02:00
claude e67bdfaa03 Workload page: load uitags so test_status and progress_info resolve (fixes 500) 2026-10-11 12:23:03 +02:00
claude e16b2e0b60 Workload config as Dev/Base comparison, full author names, server-rendered <time> stamps
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TyAt5S5MAwLBY2idan1SwU
2026-10-11 11:59:25 +02:00
claude 236d69cfb8 Workload page: result hero, hide unavailable actions, confirm destructive ones
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TyAt5S5MAwLBY2idan1SwU
2026-10-11 11:55:32 +02:00
claude 7718d593f4 Result cells: outline for tests without a verdict, diagonal hatching for stopped tests, clearer blue 2026-10-11 01:41:03 +02:00
claude dfa7687247 Design refresh: warm graphite palette, green accent, sentence-case labels, LLR gauge for SPRT tests 2026-10-11 01:33:55 +02:00
claude 5c65feb27d Merge pull request 'UI refresh: UX layer, Users/Errors/Event redesign, board analyser' (#10) from ui-refresh into master 2026-10-10 17:05:53 +02:00
claude 3dcc3ee2ab Remove the status dot and the CSS replaced by the board analyser 2026-10-10 16:02:40 +02:00
claude 611a117a38 Pass start FEN and game data to the board analyser, load board.css, drop the status dot 2026-10-10 16:02:29 +02:00
claude 309754bb08 Event viewer: index-based move selection, new board analyser layout 2026-10-10 16:01:57 +02:00
claude 9fba5f41b7 Add board analyser: board, evaluation bar and graph, captured pieces, controls 2026-10-10 16:01:01 +02:00
claude c8aa90ee91 Add chess rules engine for the board analyser (legal moves, SAN, FEN, Chess960) 2026-10-10 15:59:25 +02:00
claude d8045ddb73 Redesign Users (STC/LTC split), Errors, and Event pages; add status dots and progress to test lists 2026-10-10 00:43:55 +02:00
claude e76aa8a977 Wire the UX layer into views.py and base.html 2026-10-10 00:42:34 +02:00
claude 2b06146e7c Add UX layer: time control buckets, event/PGN parser, template filters, styles and scripts 2026-10-10 00:42:23 +02:00
rektdie f80349de11 Ignore generated static files 2026-10-09 22:27:57 +02:00
rektdie 2730d8643c Configure production settings for Raspberry Pi 2026-10-09 22:26:28 +02:00
rektdie 5b253544e6 Merge pull request 'Modern redesign' (#9) from modern-redesign into master
Reviewed-on: #9
2026-10-09 22:22:47 +02:00
claude 56e22e6936 LLR history: back to a simple graph, back in the Actions card, fixed snapping
- Simple graph again: plot with grid, 3 y labels, games axis, bounds/zero
  when in range, green/red line, hover marker + one-line tooltip. Removed the
  header, progress bar, legend, area fill, zones, pulse and animations.
  Colours are unchanged.
- The LLR panel is back at the end of the Actions card (below Adjust) where it
  was originally; the separate LLR card and its grid placement are gone.
- Snapping: the marker now locks onto every visible peak and valley. Peaks
  are found with a swing filter (a turning point counts once the line has
  moved >= 3px away from it), so plateaus and tiny wiggles no longer steal
  the snap from the real peaks. The first and latest points snap as well.
2026-10-09 22:15:23 +02:00
claude 8ac2335020 LLR history: responsive client-side chart with snapping crosshair
- llr_history.js: draws the chart in the browser (fills its card, crisp at
  any width), nice axis ticks, green/red line + area split at zero, pass/fail
  bound lines and zones, estimated segments dashed, live-pulse marker,
  progress-to-bound header, entrance animation
- Snapping: crosshair locks to the nearest point and is pulled towards
  nearby peaks/valleys; mouse, touch scrubbing and keyboard
  (arrows, Shift x10, Home/End, Escape) with screen-reader announcements
- Loading: skeleton, error state with Retry
- mytags.llr_history_graph now only returns data (JSON in data-chart); the
  old static SVG renderer is kept as _llr_history_graph_static
- workload.html: LLR gets its own wide card, inline script removed,
  fixed a stray <tr> in the SPSA parameter table
- workload.css: grid placement + chart styles
2026-10-09 21:57:02 +02:00
claude acf5c004cb Fix mobile test list: card rule must not override stacked layout 2026-10-09 05:38:33 +02:00
claude 9761853076 Add page headers to list/detail pages, fix invalid markup
- page_head block on machines, machine, events, errors, users, networks,
  network and uploadnet
- networks: remove stray ')' in the Hash header onclick, replace inline
  icon colours with classes
- network: close the two unclosed <select> elements
- uploadnet: close the form with </form>
2026-10-09 05:38:07 +02:00
claude 782e5190c3 Redesign forms: create workload, search, login, register, profile
- create_workload: presets moved above the form, cards per section,
  sticky submit bar; fixed stray attribute and wrong label target
- search: grouped filters, colour-coded result chips, results table with
  column headers
- login/register/profile: labels linked to inputs, autocomplete hints,
  centred auth card
Field ids/names, JS hooks and Django logic are unchanged.
2026-10-09 05:37:39 +02:00
claude 8969b8d4dd Redesign workload view: card layout, labelled actions, page header
Markup-only changes around the existing Django logic; the LLR script,
copy_text() targets (#long-statblock, #spsa-input, #spsa-output) and all
form field ids/names are untouched. Copy actions are now real <button>s
(keyboard accessible) and disabled actions are no longer fake links.
2026-10-09 05:36:35 +02:00
claude a506ae3b5a Redesign styles: new layout, cards, tables, buttons, forms
- style.css rewritten for the topbar/sidebar shell, cards, test list with
  mobile card layout, workload grid, badges, banners, toast, LLR widget
- form.css rewritten: forms are grids of cards, stacked on small screens,
  filter chips, presets grid, sticky submit bar, auth card
2026-10-09 05:36:03 +02:00
claude cb3d99fa45 Redesign shell: topbar + sidebar navigation, ui.js, new test list markup
- base.html: new topbar/sidebar/main layout, accessible mobile menu,
  dismissible message banners, toast container, page_head block
- ui.js: current-page nav highlight, mobile menu close, copy toast
- index/testsummary: one card per section with column headers,
  labelled flags instead of coloured asterisks, empty state
- pagebrowser: nav landmark + aria labels
All Django logic, URLs, IDs and JS hooks are unchanged.
2026-10-08 22:37:46 +02:00
claude 7bbcff231d Modern redesign: new dark theme, Inter/JetBrains Mono, sharp corners
Visual-only changes: restyle style.css, form.css and paging.css and swap
the web font in base.html. No class names, IDs or markup logic changed.
2026-10-08 22:21:55 +02:00
59 changed files with 9786 additions and 1192 deletions

No files matched your search

+1
View File
@@ -18,3 +18,4 @@ Media/*
Media/PGNs/* Media/PGNs/*
Media/Networks/* Media/Networks/*
Media/Events/* Media/Events/*
/staticfiles/
+6 -1
View File
@@ -8,6 +8,10 @@
"require_manual_registration" : false, "require_manual_registration" : false,
"balance_engine_throughputs" : true, "balance_engine_throughputs" : true,
"gitea_hosts" : [
"https://gitea.rektdie.com"
],
"books" : [ "books" : [
"2moves_v1.epd", "2moves_v1.epd",
"3moves_FRC.epd", "3moves_FRC.epd",
@@ -33,6 +37,7 @@
"Prelude", "Prelude",
"Simpler", "Simpler",
"Stormphrax", "Stormphrax",
"Impact" "Impact",
"Rigby"
] ]
} }
+78
View File
@@ -0,0 +1,78 @@
{
"private" : false,
"nps" : 780000,
"source" : "https://gitea.rektdie.com/rektdie/Rigby",
"build" : {
"path" : "",
"compilers" : ["clang++"],
"cpuflags" : [],
"systems" : ["Linux", "Windows", "Darwin"]
},
"test_presets" : {
"default" : {
"base_branch" : "main",
"book_name" : "UHO_Lichess_4852_v1.epd",
"test_bounds" : "[0.00, 5.00]",
"test_confidence" : "[0.05, 0.05]",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10"
},
"STC" : {
"both_options" : "Threads=1 Hash=64",
"both_time_control" : "8.0+0.08",
"workload_size" : 32
},
"LTC" : {
"both_options" : "Threads=1 Hash=256",
"both_time_control" : "40.0+0.4",
"workload_size" : 8
},
"Non-Regression STC" : {
"test_bounds" : "[-5.00, 0.00]",
"both_options" : "Threads=1 Hash=64",
"both_time_control" : "8.0+0.08",
"workload_size" : 32
},
"Non-Regression LTC" : {
"test_bounds" : "[-5.00, 0.00]",
"both_options" : "Threads=1 Hash=256",
"both_time_control" : "40.0+0.4",
"workload_size" : 8
}
},
"tune_presets" : {
"default" : {
"book_name" : "UHO_Lichess_4852_v1.epd",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10"
},
"STC" : {
"dev_options" : "Threads=1 Hash=64",
"dev_time_control" : "8.0+0.08"
},
"LTC" : {
"dev_options" : "Threads=1 Hash=256",
"dev_time_control" : "40.0+0.4"
}
},
"datagen_presets" : {
"default" : {
"win_adj" : "None",
"draw_adj" : "None",
"workload_size" : 128
}
}
}
+6 -1
View File
@@ -25,7 +25,7 @@ import traceback
from OpenSite.settings import PROJECT_PATH from OpenSite.settings import PROJECT_PATH
OPENBENCH_STATIC_VERSION = 'v4' OPENBENCH_STATIC_VERSION = 'v5'
OPENBENCH_CONFIG = None # Initialized by OpenBench/apps.py OPENBENCH_CONFIG = None # Initialized by OpenBench/apps.py
@@ -101,6 +101,11 @@ def verify_general_config(conf):
assert type(conf.get("require_manual_registration") == bool) assert type(conf.get("require_manual_registration") == bool)
assert type(conf.get("balance_engine_throughputs" ) == bool) assert type(conf.get("balance_engine_throughputs" ) == bool)
# Optional: Gitea servers that may serve engine sources, e.g. "https://gitea.example.com"
hosts = conf.get("gitea_hosts", [])
assert type(hosts) == list
assert all(type(x) == str and x.startswith('https://') and x.count('/') == 2 for x in hosts)
def verify_engine_basics(conf): def verify_engine_basics(conf):
assert type(conf.get('private')) == bool assert type(conf.get('private')) == bool
+214
View File
@@ -0,0 +1,214 @@
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# OpenBench is a chess engine testing framework authored by Andrew Grant. #
# <https://github.com/AndyGrant/OpenBench> <andrew@grantnet.us> #
# #
# OpenBench is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# OpenBench is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Everything OpenBench needs to know about where engine sources live.
#
# Sources can be on Github, or on a Gitea server listed under "gitea_hosts" in
# Config/config.json.
#
# Workers download sources with a plain GET and no credentials. Github archives
# are public, so workers fetch them directly. For Gitea there are two modes:
#
# - Without a token, the repository must be readable anonymously (public, and
# REQUIRE_SIGNIN_VIEW off on the Gitea server). The API is called without
# credentials and workers get the plain archive link, exactly like Github.
#
# - With an API token in Config/credentials.gitea, private repositories and
# servers that require a login work too. The token is never sent to any other
# host. Workers cannot log in, so the server hands them a signed link to
# /giteaSource/, which fetches the archive with the token and passes it on.
#
# The links are signed with the Gitea token itself, not Django's SECRET_KEY:
# settings.py is part of the public repository, and a forged link would let
# anyone read every repository the token can see. Replacing the token
# invalidates the source links of tests created before.
import hashlib
import hmac
import os
import re
import urllib.parse
import requests
import OpenBench.config
from OpenSite.settings import PROJECT_PATH
GITHUB_PREFIX = 'https://github.com/'
GITHUB_PATTERN = r'^https:\/\/github\.com\/[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+\/?$'
REPO_TAIL = r'\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/?$'
REQUEST_TIMEOUT = 30
def gitea_hosts():
return [host.rstrip('/') for host in OpenBench.config.OPENBENCH_CONFIG.get('gitea_hosts', [])]
def repo_prefixes():
return [GITHUB_PREFIX] + ['%s/' % (host) for host in gitea_hosts()]
def gitea_host(repo):
for host in gitea_hosts():
if repo.startswith(host + '/'):
return host
return None
def is_gitea(repo):
return gitea_host(repo) is not None
def is_valid_repo(repo):
if re.match(GITHUB_PATTERN, repo):
return True
host = gitea_host(repo)
return bool(host and re.match(REPO_TAIL, repo[len(host):]))
def owner_and_name(repo):
host = gitea_host(repo) or GITHUB_PREFIX.rstrip('/')
owner, name = repo[len(host):].strip('/').split('/')[:2]
return owner, name
def api_base(repo):
if (host := gitea_host(repo)):
return '%s/api/v1/repos/%s/%s' % ((host,) + owner_and_name(repo))
return repo.rstrip('/').replace('github.com', 'api.github.com/repos')
def read_gitea_token():
path = os.path.join(PROJECT_PATH, 'Config', 'credentials.gitea')
if os.path.exists(path):
with open(path) as fin:
return fin.readline().strip() or None
def gitea_headers():
token = read_gitea_token()
return { 'Authorization' : 'token %s' % (token) } if token else {}
def api_headers(engine, repo):
if is_gitea(repo):
return gitea_headers()
import OpenBench.utils
return OpenBench.utils.read_git_credentials(engine) or {}
def fetch_commit(repo, ref, headers):
# Returns { 'sha', 'tree', 'message' } for a branch, tag, or commit sha.
# Raises when the reference cannot be resolved.
base = api_base(repo)
bysha = bool(re.search('^[0-9a-fA-F]{40}$', ref))
if is_gitea(repo):
# One endpoint resolves branches, tags and commit shas alike
params = { 'sha' : ref, 'limit' : 1, 'stat' : 'false', 'verification' : 'false', 'files' : 'false' }
data = requests.get(base + '/commits', params=params, headers=headers, timeout=REQUEST_TIMEOUT).json()
data = data[0]
else:
# Lookup branch or commit sha, but will fail for tags
url = '%s/%s/%s' % (base, 'commits' if bysha else 'branches', ref)
data = requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT).json()
# Check to see if the branch name was actually a tag name
if not bysha and 'commit' not in data:
url = '%s/commits/%s' % (base, ref)
data = requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT).json()
# Actual branches have to go one layer deeper
elif not bysha: data = data['commit']
# A lookup by sha must land on exactly that commit
if bysha and data['sha'].lower() != ref.lower():
raise ValueError('%s resolved to %s' % (ref, data['sha']))
return {
'sha' : data['sha'],
'tree' : (data['commit'].get('tree') or {}).get('sha'),
'message' : data['commit']['message'],
}
def commits_ahead(repo, dev_sha, base_sha, headers):
# Number of commits on base_sha that dev_sha does not have
base = api_base(repo)
if is_gitea(repo):
url = '%s/compare/%s...%s' % (base, dev_sha, base_sha)
params = { 'verification' : 'false', 'files' : 'false' }
return int(requests.get(url, params=params, headers=headers, timeout=REQUEST_TIMEOUT).json().get('total_commits', 0))
url = '%s/compare/%s...%s' % (base, dev_sha, base_sha)
return int(requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT).json().get('ahead_by', 0))
def compare_url(repo, base_sha, dev_sha):
repo = repo.rstrip('/')
if is_gitea(repo):
return '%s/compare/%s...%s' % (repo, base_sha, dev_sha)
return '%s/compare/%s..%s' % (repo, base_sha, dev_sha)
def source_signature(repo, sha):
# Without a token there is nothing secret to sign with, and nothing to fetch with
if not (key := read_gitea_token()):
return None
message = ('openbench-gitea-source\n%s\n%s' % (repo.rstrip('/'), sha.lower())).encode('utf-8')
return hmac.new(key.encode('utf-8'), message, hashlib.sha256).hexdigest()
def source_url(request, repo, commit):
# Github serves archives by tree sha, so identical trees share one download
if not is_gitea(repo):
return '%s/archive/%s.zip' % (repo.rstrip('/'), commit['tree'])
# Without a token the repository is public: workers download it directly.
# Gitea archives are addressed by commit, not by tree.
if not read_gitea_token():
return '%s/archive/%s.zip' % (repo.rstrip('/'), commit['sha'])
query = urllib.parse.urlencode({
'repo' : repo.rstrip('/'),
'sha' : commit['sha'],
'sig' : source_signature(repo, commit['sha']),
})
return request.build_absolute_uri('/giteaSource/?%s' % (query))
def verify_source_request(repo, sha, sig):
if not (is_valid_repo(repo) and is_gitea(repo) and re.match('^[0-9a-fA-F]{40}$', sha or '')):
return False
expected = source_signature(repo, sha)
return bool(expected) and hmac.compare_digest(expected, sig or '')
def open_gitea_archive(repo, sha):
# Streams the .zip for one commit from the Gitea API
url = '%s/archive/%s.zip' % (api_base(repo), sha)
response = requests.get(url, headers=gitea_headers(), stream=True, timeout=REQUEST_TIMEOUT)
response.raise_for_status()
return response
+50
View File
@@ -0,0 +1,50 @@
import django.http
# Public pages worth listing for search engines. The API, the client
# endpoints, the account pages and the creation forms are left out on purpose.
PUBLIC_PATHS = [
'/',
'/index/',
'/greens/',
'/users/',
'/events/',
'/machines/',
'/networks/',
]
# Prefixes that crawlers have no business visiting
DISALLOWED_PREFIXES = [
'/api/',
'/client',
'/scripts/',
'/login/',
'/register/',
'/logout/',
'/profile',
'/newTest/',
'/newTune/',
'/newDatagen/',
'/newNetwork/',
]
def robots_txt(request):
lines = ['User-agent: *']
lines += ['Disallow: {}'.format(prefix) for prefix in DISALLOWED_PREFIXES]
lines += ['', 'Sitemap: {}'.format(request.build_absolute_uri('/sitemap.xml'))]
return django.http.HttpResponse('\n'.join(lines) + '\n', content_type='text/plain')
def sitemap_xml(request):
entries = ''.join(
'<url><loc>{}</loc></url>'.format(request.build_absolute_uri(path))
for path in PUBLIC_PATHS
)
body = (
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">{}</urlset>\n'
).format(entries)
return django.http.HttpResponse(body, content_type='application/xml')
+500
View File
@@ -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;
}
}
+502
View File
@@ -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: '<g fill="none" fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22.5 11.63V6M20 8h5" stroke-linejoin="miter"/><path d="M22.5 25s4.5-7.5 3-10.5c0 0-1-2.5-3-2.5s-3 2.5-3 2.5c-1.5 3 3 10.5 3 10.5" fill="#fff" stroke-linecap="butt" stroke-linejoin="miter"/><path d="M11.5 37c5.5 3.5 15.5 3.5 21 0v-7s9-4.5 6-10.5c-4-6.5-13.5-3.5-16 4V27v-3.5c-3.5-7.5-13-10.5-16-4-3 6 5 10 5 10V37z" fill="#fff"/><path d="M11.5 30c5.5-3 15.5-3 21 0m-21 3.5c5.5-3 15.5-3 21 0m-21 3.5c5.5-3 15.5-3 21 0"/></g>',
wQ: '<g fill="#fff" fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M8 12a2 2 0 1 1-4 0 2 2 0 1 1 4 0zm16.5-4.5a2 2 0 1 1-4 0 2 2 0 1 1 4 0zM41 12a2 2 0 1 1-4 0 2 2 0 1 1 4 0zM16 8.5a2 2 0 1 1-4 0 2 2 0 1 1 4 0zM33 9a2 2 0 1 1-4 0 2 2 0 1 1 4 0z"/><path d="M9 26c8.5-1.5 21-1.5 27 0l2-12-7 11V11l-5.5 13.5-3-15-3 15-5.5-14V25L7 14l2 12z" stroke-linecap="butt"/><path d="M9 26c0 2 1.5 2 2.5 4 1 1.5 1 1 .5 3.5-1.5 1-1.5 2.5-1.5 2.5-1.5 1.5.5 2.5.5 2.5 6.5 1 16.5 1 23 0 0 0 1.5-1 0-2.5 0 0 .5-1.5-1-2.5-.5-2.5-.5-2 .5-3.5 1-2 2.5-2 2.5-4-8.5-1.5-18.5-1.5-27 0z" stroke-linecap="butt"/><path d="M11.5 30c3.5-1 18.5-1 22 0M12 33.5c6-1 15-1 21 0" fill="none"/></g>',
wR: '<g fill="#fff" fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M9 39h27v-3H9v3zm3-3v-4h21v4H12zm-1-22V9h4v2h5V9h5v2h5V9h4v5" stroke-linecap="butt"/><path d="M34 14l-3 3H14l-3-3"/><path d="M31 17v12.5H14V17" stroke-linecap="butt" stroke-linejoin="miter"/><path d="M31 29.5l1.5 2.5h-20l1.5-2.5"/><path d="M11 14h23" fill="none" stroke-linejoin="miter"/></g>',
wB: '<g fill="none" fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><g fill="#fff" stroke-linecap="butt"><path d="M9 36c3.39-.97 10.11.43 13.5-2 3.39 2.43 10.11 1.03 13.5 2 0 0 1.65.54 3 2-.68.97-1.65.99-3 .5-3.39-.97-10.11.46-13.5-1-3.39 1.46-10.11.03-13.5 1-1.354.49-2.323.47-3-.5 1.354-1.94 3-2 3-2z"/><path d="M15 32c2.5 2.5 12.5 2.5 15 0 .5-1.5 0-2 0-2 0-2.5-2.5-4-2.5-4 5.5-1.5 6-11.5-5-15.5-11 4-10.5 14-5 15.5 0 0-2.5 1.5-2.5 4 0 0-.5.5 0 2z"/><path d="M25 8a2.5 2.5 0 1 1-5 0 2.5 2.5 0 1 1 5 0z"/></g><path d="M17.5 26h10M15 30h15m-7.5-14.5v5M20 18h5" stroke-linejoin="miter"/></g>',
wN: '<g fill="none" fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 10c10.5 1 16.5 8 16 29H15c0-9 10-6.5 8-21" fill="#fff"/><path d="M24 18c.38 2.91-5.55 7.37-8 9-3 2-2.82 4.34-5 4-1.042-.94 1.41-3.04 0-3-1 0 .19 1.23-1 2-1 0-4.003 1-4-4 0-2 6-12 6-12s1.89-1.9 2-3.5c-.73-.994-.5-2-.5-3 1-1 3 2.5 3 2.5h2s.78-1.992 2.5-3c1 0 1 3 1 3" fill="#fff"/><path d="M9.5 25.5a.5.5 0 1 1-1 0 .5.5 0 1 1 1 0zm5.433-9.75a.5 1.5 30 1 1-.866-.5.5 1.5 30 1 1 .866.5z" fill="#000"/></g>',
wP: '<path d="M22.5 9c-2.21 0-4 1.79-4 4 0 .89.29 1.71.78 2.38C17.33 16.5 16 18.59 16 21c0 2.03.94 3.84 2.41 5.03-3 1.06-7.41 5.55-7.41 13.47h23c0-7.92-4.41-12.41-7.41-13.47 1.47-1.19 2.41-3 2.41-5.03 0-2.41-1.33-4.5-3.28-5.62.49-.67.78-1.49.78-2.38 0-2.21-1.79-4-4-4z" fill="#fff" stroke="#000" stroke-width="1.5" stroke-linecap="round"/>',
bK: '<g fill="none" fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22.5 11.63V6" stroke-linejoin="miter"/><path d="M22.5 25s4.5-7.5 3-10.5c0 0-1-2.5-3-2.5s-3 2.5-3 2.5c-1.5 3 3 10.5 3 10.5" fill="#000" stroke-linecap="butt" stroke-linejoin="miter"/><path d="M11.5 37c5.5 3.5 15.5 3.5 21 0v-7s9-4.5 6-10.5c-4-6.5-13.5-3.5-16 4V27v-3.5c-3.5-7.5-13-10.5-16-4-3 6 5 10 5 10V37z" fill="#000"/><path d="M20 8h5" stroke-linejoin="miter"/><path d="M32 29.5s8.5-4 6.03-9.65C34.15 14 25 18 22.5 24.5l.01 2.1-.01-2.1C20 18 9.906 14 6.997 19.85c-2.497 5.65 4.853 9 4.853 9" stroke="#ececec"/><path d="M11.5 30c5.5-3 15.5-3 21 0m-21 3.5c5.5-3 15.5-3 21 0m-21 3.5c5.5-3 15.5-3 21 0" stroke="#ececec"/></g>',
bQ: '<g fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><g stroke="none"><circle cx="6" cy="12" r="2.75"/><circle cx="14" cy="9" r="2.75"/><circle cx="22.5" cy="8" r="2.75"/><circle cx="31" cy="9" r="2.75"/><circle cx="39" cy="12" r="2.75"/></g><path d="M9 26c8.5-1.5 21-1.5 27 0l2.5-12.5L31 25l-.3-14.1-5.2 13.6-3-14.5-3 14.5-5.2-13.6L14 25 6.5 13.5 9 26z" stroke-linecap="butt"/><path d="M9 26c0 2 1.5 2 2.5 4 1 1.5 1 1 .5 3.5-1.5 1-1.5 2.5-1.5 2.5-1.5 1.5.5 2.5.5 2.5 6.5 1 16.5 1 23 0 0 0 1.5-1 0-2.5 0 0 .5-1.5-1-2.5-.5-2.5-.5-2 .5-3.5 1-2 2.5-2 2.5-4-8.5-1.5-18.5-1.5-27 0z" stroke-linecap="butt"/><path d="M11 38.5a35 35 1 0 0 23 0" fill="none" stroke-linecap="butt"/><path d="M11 29a35 35 1 0 1 23 0m-21.5 2.5h20m-21 3a35 35 1 0 0 22 0m-23 3a35 35 1 0 0 24 0" fill="none" stroke="#ececec"/></g>',
bR: '<g fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M9 39h27v-3H9v3zm3.5-7l1.5-2.5h17l1.5 2.5h-20zm-.5 4v-4h21v4H12z" stroke-linecap="butt"/><path d="M14 29.5v-13h17v13H14z" stroke-linecap="butt" stroke-linejoin="miter"/><path d="M14 16.5L11 14h23l-3 2.5H14zM11 14V9h4v2h5V9h5v2h5V9h4v5H11z" stroke-linecap="butt"/><path d="M12 35.5h21m-20-4h19m-18-2h17m-17-13h17M11 14h23" fill="none" stroke="#ececec" stroke-width="1" stroke-linejoin="miter"/></g>',
bB: '<g fill="none" fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><g fill="#000" stroke-linecap="butt"><path d="M9 36c3.39-.97 10.11.43 13.5-2 3.39 2.43 10.11 1.03 13.5 2 0 0 1.65.54 3 2-.68.97-1.65.99-3 .5-3.39-.97-10.11.46-13.5-1-3.39 1.46-10.11.03-13.5 1-1.354.49-2.323.47-3-.5 1.354-1.94 3-2 3-2z"/><path d="M15 32c2.5 2.5 12.5 2.5 15 0 .5-1.5 0-2 0-2 0-2.5-2.5-4-2.5-4 5.5-1.5 6-11.5-5-15.5-11 4-10.5 14-5 15.5 0 0-2.5 1.5-2.5 4 0 0-.5.5 0 2z"/><path d="M25 8a2.5 2.5 0 1 1-5 0 2.5 2.5 0 1 1 5 0z"/></g><path d="M17.5 26h10M15 30h15m-7.5-14.5v5M20 18h5" stroke="#ececec" stroke-linejoin="miter"/></g>',
bN: '<g fill="none" fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 10c10.5 1 16.5 8 16 29H15c0-9 10-6.5 8-21" fill="#000"/><path d="M24 18c.38 2.91-5.55 7.37-8 9-3 2-2.82 4.34-5 4-1.042-.94 1.41-3.04 0-3-1 0 .19 1.23-1 2-1 0-4.003 1-4-4 0-2 6-12 6-12s1.89-1.9 2-3.5c-.73-.994-.5-2-.5-3 1-1 3 2.5 3 2.5h2s.78-1.992 2.5-3c1 0 1 3 1 3" fill="#000"/><path d="M9.5 25.5a.5.5 0 1 1-1 0 .5.5 0 1 1 1 0zm5.433-9.75a.5 1.5 30 1 1-.866-.5.5 1.5 30 1 1 .866.5z" fill="#ececec" stroke="#ececec"/><path d="M24.55 10.4l-.45 1.45.5.15c3.15 1 5.65 2.49 7.9 6.75S35.75 29.06 35.25 39l-.05.5h2.25l.05-.5c.5-10.06-.88-16.85-3.25-21.34-2.37-4.49-5.79-6.64-9.19-7.16l-.51-.1z" fill="#ececec" stroke="none"/></g>',
bP: '<path d="M22.5 9c-2.21 0-4 1.79-4 4 0 .89.29 1.71.78 2.38C17.33 16.5 16 18.59 16 21c0 2.03.94 3.84 2.41 5.03-3 1.06-7.41 5.55-7.41 13.47h23c0-7.92-4.41-12.41-7.41-13.47 1.47-1.19 2.41-3 2.41-5.03 0-2.41-1.33-4.5-3.28-5.62.49-.67.78-1.49.78-2.38 0-2.21-1.79-4-4-4z" stroke="#000" stroke-width="1.5" stroke-linecap="round"/>'
};
function buildSprite() {
if ($('bd-sprite')) return;
var defs = '';
Object.keys(PIECES).forEach(function (key) {
defs += '<g id="bd-p-' + key + '">' + PIECES[key] + '</g>';
});
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>' + defs + '</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 '<g class="' + className + '">' +
'<line x1="' + from_.x + '" y1="' + from_.y + '" x2="' + (base.x + ux * 2) + '" y2="' + (base.y + uy * 2) + '" stroke-width="15"/>' +
'<polygon points="' + points + '"/></g>';
}
function square(at, className) {
return '<rect class="' + className + '" x="' + at.x + '" y="' + at.y + '" width="100" height="100"/>';
}
function drawBoard(position, index) {
var out = '<svg viewBox="0 0 800 800" role="img" aria-label="Chess board"><defs>' +
'<radialGradient id="bd-check"><stop offset="0" class="bd-check-in"/><stop offset="0.75" class="bd-check-out"/></radialGradient></defs>';
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 += '<rect fill="url(#bd-check)" x="' + at.x + '" y="' + at.y + '" width="100" height="100"/>';
}
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 += '<text class="bd-coord ' + (((file + bottom) % 2 === 0) ? 'on-dark' : 'on-light') +
'" x="' + (at.x + 93) + '" y="' + (at.y + 91) + '" text-anchor="end">' + 'abcdefgh'.charAt(file) + '</text>';
}
for (rank = 0; rank < 8; rank++) {
s = rank * 8 + left;
at = corner(s);
out += '<text class="bd-coord ' + (((left + rank) % 2 === 0) ? 'on-dark' : 'on-light') +
'" x="' + (at.x + 7) + '" y="' + (at.y + 20) + '">' + (rank + 1) + '</text>';
}
for (s = 0; s < 64; s++) {
var piece = position.board.charAt(s);
if (piece === '.') continue;
at = corner(s);
out += '<use href="#bd-p-' + pieceKey(piece) + '" transform="translate(' + at.x + ' ' + at.y + ') scale(2.2222)"/>';
}
if (showAttempt) out += arrow(attempt.from, attempt.to, 'bd-arrow');
return out + '</svg>';
}
/* ---------- 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 '<svg class="bd-cap" viewBox="0 0 45 45" aria-hidden="true"><use href="#bd-p-' + pieceKey(piece) + '"/></svg>';
}).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 =
'<svg viewBox="0 0 ' + graph.width + ' ' + graph.height + '" preserveAspectRatio="none" role="img" aria-label="Evaluation graph">' +
'<defs><clipPath id="bd-clip-top"><rect x="0" y="0" width="' + graph.width + '" height="' + middle + '"/></clipPath>' +
'<clipPath id="bd-clip-bottom"><rect x="0" y="' + middle + '" width="' + graph.width + '" height="' + middle + '"/></clipPath></defs>' +
'<path class="bd-area-white" d="' + area + '" clip-path="url(#bd-clip-top)"/>' +
'<path class="bd-area-black" d="' + area + '" clip-path="url(#bd-clip-bottom)"/>' +
'<line class="bd-mid" x1="0" y1="' + middle + '" x2="' + graph.width + '" y2="' + middle + '"/>' +
'<path class="bd-curve" d="' + line + '"/>' +
'<line class="bd-cursor" id="bd-cursor" x1="0" y1="0" x2="0" y2="' + graph.height + '"/></svg>';
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 = '<i class="fa-solid fa-play"></i>';
}
}
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 = '<i class="fa-solid fa-pause"></i>';
}
}
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();
})();
+607
View File
@@ -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
};
});
+6 -1
View File
@@ -1,5 +1,9 @@
function enforce_default_text(id, text) { function enforce_default_text(id, text) {
// `text` may be a list of accepted prefixes; the first one is the default.
var prefixes = Array.isArray(text) ? text : [text];
text = prefixes[0];
window.addEventListener('DOMContentLoaded', function() { window.addEventListener('DOMContentLoaded', function() {
var field = document.getElementById(id); var field = document.getElementById(id);
@@ -9,7 +13,8 @@ function enforce_default_text(id, text) {
field.addEventListener('input', function() { field.addEventListener('input', function() {
if (field.value.startsWith(text) || field.value === text) // Accept any allowed prefix, and anything still being typed towards one
if (prefixes.some(function(p) { return field.value.startsWith(p) || p.startsWith(field.value); }))
return; return;
if (field.value.endsWith('/')) if (field.value.endsWith('/'))
+242
View File
@@ -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: <moves played>, ply: <index - 1>, move: <move or null>, moves: <all 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();
});
})();
+283 -72
View File
@@ -1,106 +1,172 @@
/* ==========================================================================
OpenBench - forms (modern dark theme)
========================================================================== */
/* A .form is a grid of cards: .col (half width), .col-full (full width) */
#content .form {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 20px;
align-items: start;
margin-bottom: 20px;
}
#content .form > .col,
#content .form > .col-full {
min-width: 0;
padding: 4px 20px 20px;
background-color: var(--color2);
border: 1px solid var(--line);
border-radius: var(--radius);
white-space: normal;
}
#content .form > .col-full {
grid-column: 1 / -1;
}
#content .form > .col:only-child {
grid-column: 1 / -1;
max-width: 640px;
}
#content .form .col-half { #content .form .col-half {
display: inline-block;
width: 25%;
white-space: normal;
box-sizing: border-box;
vertical-align: top;
}
#content .form .col {
display: inline-block;
width: 50%;
white-space: normal;
margin-left: 0;
box-sizing: border-box;
vertical-align: top;
}
#content .form .col-full {
display: block; display: block;
width: 100%; width: auto;
white-space: normal; white-space: normal;
margin-left: 0;
box-sizing: border-box;
vertical-align: top;
}
/* Styles for screen widths less than 600px */
@media (max-width: 1024px) {
#content .form .col {
display: block;
width: 100%;
}
} }
#content .form h3 { #content .form h3 {
font-size: 14px; margin: 20px 0 14px;
color: var(--color-font3); padding: 0 0 8px;
border-bottom: 1px solid var(--line);
color: var(--muted);
font-size: 12px;
font-weight: 600;
letter-spacing: 0.1em;
text-align: left; text-align: left;
padding-left: 1.5rem; text-transform: uppercase;
} }
/* Rows: label on the left, control fills the rest */
#content .form .row { #content .form .row {
display: flex; display: flex;
align-items: center; align-items: center;
margin-bottom: 0.25rem; gap: 12px;
margin-bottom: 8px;
} }
#content .row label { #content .row label {
font-size: 13px; flex: 0 0 150px;
width: 25%; width: auto;
min-width: 128px;
margin-right: 1rem;
text-align: right;
color: var(--color-font2)
}
#content .row input, #content .row select, #content .row textarea {
flex-grow: 1;
min-width: 0; min-width: 0;
border: 1px solid var(--color3); margin: 0;
border-radius: 4px;
padding: 9px 6px 6px;
background-color: var(--color2);
color: var(--color-font2); color: var(--color-font2);
font-family: "Courier Prime", serif; font-size: 13px;
font-weight: 500;
text-align: left;
} }
#content .row input[type="file"]{ #content .row label select {
padding: 2px 2px; width: 100%;
} }
#content .row input:focus, #content .row select:focus, #content .row textarea:focus { #content .row input,
#content .row select,
#content .row textarea {
flex: 1 1 auto;
min-width: 0;
padding: 8px 10px;
background-color: #0C1016;
border: 1px solid var(--line-strong);
border-radius: var(--radius);
color: var(--color-font1);
font-family: var(--font-sans);
font-size: 13.5px;
transition: border-color 0.15s ease, box-shadow 0.15s ease, background-color 0.15s ease;
}
#content .row textarea {
font-family: var(--font-mono);
font-size: 12.5px;
line-height: 1.5;
resize: vertical;
}
#content .row input::placeholder,
#content .row textarea::placeholder {
color: #566074;
}
#content .row input:hover,
#content .row select:hover,
#content .row textarea:hover {
border-color: #3A4862;
}
#content .row input:focus,
#content .row select:focus,
#content .row textarea:focus {
outline: none; outline: none;
border-color: var(--color3); border-color: var(--accent);
box-shadow: 0 0 0 2px rgba(77, 144, 254, 0.75); box-shadow: 0 0 0 3px rgba(76, 141, 255, 0.22);
background-color: var(--color2); background-color: #0E131B;
color: var(--color-font2);
} }
#content .row select > option{ #content .row input[type="file"] {
font-family: "Helvetica", serif; padding: 4px;
} }
#content .row input[type="file"]::file-selector-button { #content .row input[type="checkbox"],
background-color: var(--color3); #content .row input[type="radio"] {
border: 1px solid var(--color2); flex: 0 0 auto;
border-radius: 4px; width: 16px;
padding: 6px 6px 3px; height: 16px;
color: var(--color-font2); padding: 0;
accent-color: var(--accent);
cursor: pointer; cursor: pointer;
transition: background-color 0.3s, border-color 0.3s;
font-family: "Courier Prime", serif;
} }
#content .row input[type="file"]::file-selector-button:hover { #content .row select > option {
background-color: rgba(77, 144, 254, 0.8); font-family: var(--font-sans);
border-color: var(--color2); background-color: #0C1016;
color: var(--color-font1);
} }
#content .row input[readonly] { #content .row input[readonly] {
background-color: var(--color2);
color: var(--color-font1); color: var(--color-font1);
font-family: var(--font-mono);
font-size: 13px;
}
#content .row input[type="file"]::file-selector-button {
margin-right: 10px;
padding: 6px 12px;
background-color: var(--color3);
border: 1px solid var(--line-strong);
border-radius: var(--radius);
color: var(--color-font1);
font-family: var(--font-sans);
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: background-color 0.15s, border-color 0.15s;
}
#content .row input[type="file"]::file-selector-button:hover {
background-color: var(--accent);
border-color: var(--accent);
color: #FFFFFF;
}
/* Buttons that sit directly in a form card */
#content .form .col > .anchorbutton,
#content .form .col-full > .anchorbutton {
margin-top: 14px;
} }
#content .form .flex { #content .form .flex {
@@ -108,17 +174,162 @@
flex-wrap: wrap; flex-wrap: wrap;
max-width: 100%; max-width: 100%;
justify-content: flex-start; justify-content: flex-start;
gap: 6px;
} }
#content .form .flex button{ #content .form .flex button {
max-width: 100%; max-width: 100%;
} }
/* Sticky submit bar (create workload) */
#content .form-actions {
position: sticky;
bottom: 0;
z-index: 5;
padding: 16px 0 4px;
background: linear-gradient(to top, var(--color1) 65%, rgba(11, 14, 20, 0));
}
#content .form-actions .anchorbutton {
min-width: 260px;
padding: 12px 22px;
font-size: 14px;
}
/* Presets generated by create_workload.js */
#content #test-mode-buttons {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: 8px;
}
#content #test-mode-buttons .col-half {
width: auto;
padding: 0;
}
#content #test-mode-buttons .anchorbutton {
width: 100%;
margin: 0;
}
/* Search filters */
#content .chips {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
#content .chip {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 7px 12px;
background-color: #0C1016;
border: 1px solid var(--line-strong);
border-radius: var(--radius);
color: var(--color-font2);
font-size: 13px;
font-weight: 500;
cursor: pointer;
user-select: none;
transition: border-color 0.15s ease, background-color 0.15s ease;
}
#content .chip:hover {
border-color: #3A4862;
background-color: var(--surface-hover);
}
#content .chip input {
margin: 0;
accent-color: var(--accent);
cursor: pointer;
}
#content .chip::before {
content: "";
width: 8px;
height: 8px;
background-color: var(--muted);
}
#content .chip-green::before { background-color: #34D399; }
#content .chip-blue::before { background-color: #4C8DFF; }
#content .chip-yellow::before { background-color: #F5B941; }
#content .chip-red::before { background-color: #F87171; }
/* Sign in / sign up */
#content .auth-wrap {
max-width: 440px;
margin: 24px auto 0;
}
#content .auth-wrap .form > .col:only-child {
max-width: none;
}
#content .auth-wrap .row {
flex-direction: column;
align-items: stretch;
gap: 6px;
margin-bottom: 14px;
}
#content .auth-wrap .row label {
flex-basis: auto;
}
/* Profile engine list */
#content #engines-container span { #content #engines-container span {
margin: 0px 4px 0px 4px; display: inline-flex;
align-items: center;
margin: 0 4px;
cursor: pointer; cursor: pointer;
} }
#content #engines-container span input { #content #engines-container span input {
cursor: pointer; cursor: pointer;
} }
#content #engines-container .fa-trash-can {
color: #C25555;
}
#content #engines-container span:hover .fa-trash-can {
color: var(--bad);
}
@media (max-width: 1024px) {
#content .form {
grid-template-columns: minmax(0, 1fr);
}
}
@media (max-width: 640px) {
#content .form .row {
flex-direction: column;
align-items: stretch;
gap: 6px;
}
#content .row label {
flex-basis: auto;
}
#content .form > .col,
#content .form > .col-full {
padding: 4px 14px 16px;
}
#content .form-actions .anchorbutton {
width: 100%;
min-width: 0;
}
}
+68
View File
@@ -0,0 +1,68 @@
/* ==========================================================================
Live updates. Loaded after refresh.css, and uses its tokens.
========================================================================== */
/* The small status pill in the corner: a pulse while updates are on */
.live-pill {
position: fixed;
right: 16px;
bottom: 16px;
z-index: 40;
display: inline-flex;
align-items: center;
gap: 8px;
padding: 6px 12px 6px 10px;
border: 1px solid var(--line-strong);
border-radius: 999px;
background: rgba(26, 29, 34, 0.92);
-webkit-backdrop-filter: blur(8px);
backdrop-filter: blur(8px);
color: var(--color-font2);
font-family: var(--font-sans);
font-size: 12.5px;
font-weight: 500;
line-height: 1;
cursor: pointer;
}
.live-pill[hidden] { display: none; }
.live-pill:hover {
border-color: var(--muted);
color: var(--color-font1);
}
.live-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--ok);
animation: live-pulse 2.4s ease-out infinite;
}
.live-pill[data-state="paused"] .live-dot { background: var(--muted); animation: none; }
.live-pill[data-state="retry"] .live-dot { background: var(--warn); animation: none; }
@keyframes live-pulse {
0% { box-shadow: 0 0 0 0 rgba(110, 219, 154, 0.45); }
70%, 100% { box-shadow: 0 0 0 7px rgba(110, 219, 154, 0); }
}
/* Whatever just changed gets a brief outline that fades away */
.live-flash { animation: live-flash 1.4s ease-out; }
@keyframes live-flash {
0% { outline: 2px solid rgba(110, 219, 154, 0.65); outline-offset: -2px; }
100% { outline: 2px solid rgba(110, 219, 154, 0); outline-offset: -2px; }
}
@media (prefers-reduced-motion: reduce) {
.live-dot,
.live-flash { animation: none; }
}
@media (max-width: 640px) {
.live-pill { right: 10px; bottom: 10px; }
}
+325
View File
@@ -0,0 +1,325 @@
/* OpenBench live updates: the pages keep themselves current.
Every few seconds the page asks the server for its own HTML, and only the
parts that changed are swapped in. Scroll position, text selection, open
forms and the LLR history graph are left alone. Polling pauses in a hidden
tab, backs off when the server is unreachable, and can be switched off with
the pill in the corner. No dependencies, and the pages work without it. */
(function () {
'use strict';
var PAGES = /^\/(?:(?:index|greens|machines|events|errors)(?:\/\d+)?|user\/[^\/]+(?:\/\d+)?|(?:test|tune|datagen)\/\d+)?\/?$/;
if (!PAGES.test(window.location.pathname)) return;
var content = document.getElementById('content');
if (!content || !window.fetch || !window.DOMParser) return;
var FULL = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false };
var DAY = { month: 'short', day: '2-digit' };
// Never replaced: forms keep what is typed, banners can be dismissed, the graphs load themselves.
// The SPSA chart and parameter list ( Tune pages ) are interactive, so their scripts refresh them
// from the 'live:patched' event instead.
var PROTECT = 'form, .banner, .llr-history-panel, .spsa-chart, #spsa-rows, #spsa-empty, [data-live-skip], script, style';
// Attributes that other scripts, or the reader, add after the page loads ( 'open' is a fold the reader opened )
var KEEP = { 'data-href': true, 'data-epoch': true, 'open': true };
/* ---------- Timestamps ----------
The pages print raw epochs and the browser formats them. Remember the
epoch before that happens, so that two versions can be compared. */
function stash(root) {
Array.prototype.forEach.call(root.querySelectorAll('.timestamp, .datestamp'), function (el) {
var text = el.textContent.trim();
if (!el.hasAttribute('data-epoch') && /^\d+(\.\d+)?$/.test(text)) el.setAttribute('data-epoch', text);
});
}
function formatStamp(el) {
var epoch = parseFloat(el.getAttribute('data-epoch'));
if (isNaN(epoch)) return;
el.textContent = new Date(1000 * epoch).toLocaleString(undefined, el.classList.contains('datestamp') ? DAY : FULL);
}
function isStamp(el) {
return el.classList.contains('timestamp') || el.classList.contains('datestamp');
}
stash(content);
/* ---------- Patching ---------- */
function flash(el) {
if (!el || el.nodeType !== 1) return;
el.classList.remove('live-flash');
void el.offsetWidth;
el.classList.add('live-flash');
setTimeout(function () { el.classList.remove('live-flash'); }, 1500);
}
function protectedNode(node) {
return node.nodeType === 1 && node.matches(PROTECT);
}
function kids(el) {
return Array.prototype.filter.call(el.childNodes, function (child) {
if (child.nodeType === 3) return child.nodeValue.trim() !== '';
return child.nodeType === 1 && !protectedNode(child);
});
}
function same(a, b) {
if (a.nodeType !== b.nodeType) return false;
return a.nodeType !== 1 || a.tagName === b.tagName;
}
function syncAttributes(o, n) {
var i, attr;
for (i = 0; i < n.attributes.length; i++) {
attr = n.attributes[i];
if (attr.name === 'class') continue;
if (o.getAttribute(attr.name) !== attr.value) o.setAttribute(attr.name, attr.value);
}
for (i = o.attributes.length - 1; i >= 0; i--) {
attr = o.attributes[i];
if (attr.name === 'class' || KEEP[attr.name]) continue;
if (!n.hasAttribute(attr.name)) o.removeAttribute(attr.name);
}
// Classes come from the server, except the highlight this script adds
var wanted = (n.getAttribute('class') || '') + (o.classList.contains('live-flash') ? ' live-flash' : '');
if ((o.getAttribute('class') || '') !== wanted) {
if (wanted.trim()) o.setAttribute('class', wanted);
else o.removeAttribute('class');
}
}
function patchNode(o, n) {
if (o.nodeType === 3) {
if (o.nodeValue !== n.nodeValue) {
o.nodeValue = n.nodeValue;
flash(o.parentNode);
}
return;
}
if (o.nodeType !== 1 || protectedNode(o)) return;
if (isStamp(o)) {
if (o.getAttribute('data-epoch') !== n.getAttribute('data-epoch')) {
var fresh = document.importNode(n, true);
formatStamp(fresh);
o.parentNode.replaceChild(fresh, o);
flash(fresh);
}
return;
}
syncAttributes(o, n);
patchChildren(o, n);
}
/* Children are matched from both ends, and only what is left in the
middle is replaced. A row that appears, or a button that disappears,
leaves the rest of its parent untouched. */
function patchChildren(oldEl, newEl) {
var o = kids(oldEl), n = kids(newEl);
var start = 0, oe = o.length, ne = n.length, i;
while (start < oe && start < ne && same(o[start], n[start])) {
patchNode(o[start], n[start]);
start++;
}
while (oe > start && ne > start && same(o[oe - 1], n[ne - 1])) {
oe--; ne--;
patchNode(o[oe], n[ne]);
}
if (start === oe && start === ne) return;
var before = o[oe] || null;
for (i = start; i < oe; i++) oldEl.removeChild(o[i]);
for (i = start; i < ne; i++) {
var node = document.importNode(n[i], true);
if (node.nodeType === 1) {
Array.prototype.forEach.call(node.querySelectorAll('.timestamp, .datestamp'), formatStamp);
if (isStamp(node)) formatStamp(node);
}
oldEl.insertBefore(node, before);
flash(node.nodeType === 1 ? node : oldEl);
}
}
// ux.js makes whole rows clickable once, when the page loads
function restoreRows() {
Array.prototype.forEach.call(content.querySelectorAll('table.test-list tbody tr'), function (row) {
var link = row.querySelector('.col-test a');
if (link && !row.getAttribute('data-href')) row.setAttribute('data-href', link.getAttribute('href'));
});
}
function apply(html) {
var doc = new DOMParser().parseFromString(html, 'text/html');
var fresh = doc.getElementById('content');
if (!fresh) return false;
stash(fresh);
patchChildren(content, fresh);
restoreRows();
// Scripts that own a part of the page that is never patched ( see PROTECT ) refresh it from here
document.dispatchEvent(new CustomEvent('live:patched', { detail: { fresh: fresh } }));
return true;
}
/* ---------- The indicator ---------- */
var pill = document.createElement('button');
pill.type = 'button';
pill.id = 'live-indicator';
pill.className = 'live-pill';
pill.innerHTML = '<span class="live-dot" aria-hidden="true"></span><span class="live-text">Live</span>';
document.body.appendChild(pill);
var enabled = true;
try { enabled = window.localStorage.getItem('ob:live') !== 'off'; } catch (error) { /* storage unavailable */ }
var timer = null, busy = false, failures = 0, last = Date.now(), dead = false;
function setState(state) {
var label = { live: 'Live', paused: 'Paused', retry: 'Reconnecting' }[state];
pill.setAttribute('data-state', state);
pill.setAttribute('aria-pressed', String(enabled));
pill.querySelector('.live-text').textContent = label;
pill.title = state === 'paused'
? 'Automatic updates are off. Click to turn them on.'
: 'Updated ' + new Date(last).toLocaleTimeString() + '. Click to pause.';
}
/* ---------- Polling ---------- */
function running() {
return !!document.querySelector('.page-head .fa-spin');
}
function interval() {
var path = window.location.pathname, base = 10000;
if (/^\/(test|tune|datagen)\//.test(path)) base = document.querySelector('.page-head .fa-spin') ? 8000 : 45000;
else if (/^\/(events|errors)/.test(path)) base = 20000;
return base * Math.pow(2, Math.min(failures, 3));
}
// Leave the page alone while somebody is reading, selecting or typing
function occupied() {
var selection = window.getSelection && window.getSelection();
if (selection && !selection.isCollapsed && selection.anchorNode && content.contains(selection.anchorNode)) return true;
var focused = document.activeElement;
if (focused && content.contains(focused) && /^(INPUT|TEXTAREA|SELECT)$/.test(focused.tagName)) return true;
var palette = document.getElementById('palette');
return !!(palette && !palette.hidden);
}
function schedule(delay) {
clearTimeout(timer);
if (!enabled || dead || document.hidden) return;
timer = setTimeout(tick, delay === undefined ? interval() : delay);
}
function tick() {
if (document.hidden) return;
if (occupied()) { schedule(3000); return; }
poll();
}
function strip(path) { return path.replace(/\/+$/, ''); }
function poll() {
if (busy) return;
busy = true;
var path = window.location.pathname;
fetch(window.location.pathname + window.location.search, {
credentials : 'same-origin',
cache : 'no-store',
headers : { 'Accept': 'text/html' }
})
.then(function (response) {
// Sent somewhere else ( a login page, or another kind of workload ): stop quietly
if (response.redirected && strip(new URL(response.url).pathname) !== strip(path)) {
dead = true;
throw new Error('moved');
}
if (!response.ok) throw new Error('status ' + response.status);
return response.text();
})
.then(function (html) {
// A test that has just finished still has a last data point to draw
var wasRunning = running();
if (!apply(html)) throw new Error('no content');
if (window.refreshLLRHistory && (wasRunning || running())) window.refreshLLRHistory();
failures = 0;
last = Date.now();
setState('live');
})
.catch(function () {
failures++;
if (dead) pill.hidden = true;
else setState('retry');
})
.then(function () {
busy = false;
schedule();
});
}
pill.addEventListener('click', function () {
enabled = !enabled;
try { window.localStorage.setItem('ob:live', enabled ? 'on' : 'off'); } catch (error) { /* ignore */ }
if (enabled) { setState('live'); poll(); }
else { clearTimeout(timer); setState('paused'); }
});
document.addEventListener('visibilitychange', function () {
if (document.hidden) { clearTimeout(timer); return; }
if (!enabled || dead) return;
// Coming back to the tab: catch up at once, unless it was just done
if (Date.now() - last > 4000) poll();
else schedule();
});
setState(enabled ? 'live' : 'paused');
schedule();
})();
+484
View File
@@ -0,0 +1,484 @@
/* ==========================================================================
OpenBench - LLR history graph
The server (mytags.llr_history_graph) supplies the data as a
<div class="llr-chart" data-chart="{json}">, and the graph is drawn here
so that it fills the width of its panel.
Hovering snaps the marker to the nearest point of the graph, and to the
peaks / valleys of the line when the pointer is near one.
========================================================================== */
(function () {
'use strict';
var SVG_NS = 'http://www.w3.org/2000/svg';
var MINUS = '\u2212';
var HEIGHT = 124;
var MARGIN = { l: 40, r: 8, t: 8, b: 20 };
var MAGNET = 12; // px: how far a peak / valley pulls the marker
var SWING = 3; // px: smallest rise / fall that counts as a peak / valley
var uid = 0;
/* ---------- helpers ---------- */
function svg(name, attrs, parent) {
var node = document.createElementNS(SVG_NS, name);
for (var key in attrs)
if (Object.prototype.hasOwnProperty.call(attrs, key))
node.setAttribute(key, attrs[key]);
if (parent)
parent.appendChild(node);
return node;
}
function div(className, parent) {
var node = document.createElement('div');
node.className = className;
if (parent)
parent.appendChild(node);
return node;
}
function fmt(value) {
return value.toFixed(2).replace('-', MINUS);
}
function commas(value) {
return String(Math.round(value)).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
function compact(value) {
if (value >= 1e6) return parseFloat((value / 1e6).toFixed(1)) + 'M';
if (value >= 1e3) return parseFloat((value / 1e3).toFixed(1)) + 'k';
return String(Math.round(value));
}
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
// Index of the first point with games >= target
function lowerBound(points, target) {
var lo = 0, hi = points.length;
while (lo < hi) {
var mid = (lo + hi) >> 1;
if (points[mid].games < target) lo = mid + 1;
else hi = mid;
}
return lo;
}
// Keep the first / min / max / last point of every pixel column
function decimate(points, sx) {
var out = [], i = 0, n = points.length;
while (i < n) {
var key = Math.round(sx(points[i].games));
var j = i, lo = i, hi = i;
while (j + 1 < n && Math.round(sx(points[j + 1].games)) === key) {
j++;
if (points[j].llr < points[lo].llr) lo = j;
if (points[j].llr > points[hi].llr) hi = j;
}
[i, lo, hi, j].filter(function (value, index, all) {
return all.indexOf(value) === index;
}).sort(function (a, b) { return a - b; }).forEach(function (k) {
out.push(points[k]);
});
i = j + 1;
}
return out;
}
/* Peaks and valleys: every turning point of the line where it rises or
falls by at least `threshold` before turning around. Flat stretches and
tiny wiggles (smaller than a few pixels) are ignored, so what snaps is
exactly what is visible on the graph. */
function findPivots(points, threshold) {
var pivots = [];
var trend = 0, hi = 0, lo = 0;
for (var i = 1; i < points.length; i++) {
var value = points[i].llr;
if (value >= points[hi].llr) hi = i;
if (value <= points[lo].llr) lo = i;
if (trend >= 0 && points[hi].llr - value >= threshold) {
pivots.push(hi);
trend = -1; hi = i; lo = i;
}
else if (trend <= 0 && value - points[lo].llr >= threshold) {
pivots.push(lo);
trend = 1; hi = i; lo = i;
}
}
return pivots;
}
/* ======================================================================
Graph
====================================================================== */
function Graph(root, data) {
this.root = root;
this.lower = Number(data.lower);
this.upper = Number(data.upper);
this.games = Number(data.games);
this.active = -1;
this.rendered = 0;
this.points = data.history.map(function (p) {
return { games: Number(p[0]), llr: Number(p[1]), estimated: !!p[2] };
}).sort(function (a, b) { return a.games - b.games; });
root.textContent = '';
this.plot = div('llrg-plot', root);
this.plot.tabIndex = 0;
this.plot.setAttribute('role', 'img');
this.plot.setAttribute('aria-label', 'LLR history. Use the arrow keys to inspect the points.');
this.svgEl = svg('svg', { 'class': 'llrg-svg', 'aria-hidden': 'true' }, this.plot);
this.tip = div('llrg-tip', this.plot);
this.render();
this.bind();
}
Graph.prototype.render = function () {
var W = Math.floor(this.plot.clientWidth);
if (W < 120)
return;
this.rendered = W;
var H = HEIGHT, m = MARGIN;
var iw = W - m.l - m.r;
var ih = H - m.t - m.b;
var points = this.points;
var xMax = Math.max(points[points.length - 1].games, this.games, 1);
/* Vertical range: what was observed, and zero, with a minimum height */
var lo = 0, hi = 0;
points.forEach(function (p) {
if (p.llr < lo) lo = p.llr;
if (p.llr > hi) hi = p.llr;
});
var yMin, yMax;
if (hi - lo < 0.75) {
var center = (lo + hi) / 2;
yMin = center - 0.375;
yMax = center + 0.375;
} else {
var pad = Math.max((hi - lo) * 0.15, 0.15);
yMin = lo - pad;
yMax = hi + pad;
}
function sx(games) { return m.l + iw * (games / xMax); }
function sy(value) { return m.t + ih * (1 - (value - yMin) / (yMax - yMin)); }
this.g = { W: W, H: H, m: m, iw: iw, ih: ih, xMax: xMax, sx: sx, sy: sy };
/* Peaks and valleys, plus both ends, are what the marker snaps to */
var pivots = findPivots(points, SWING * (yMax - yMin) / ih);
pivots.push(0, points.length - 1);
this.pivots = pivots.filter(function (value, index, all) {
return all.indexOf(value) === index;
}).sort(function (a, b) { return a - b; });
/* Drawing */
var el = this.svgEl;
var id = 'llrg' + (++uid);
var zeroY = sy(0);
el.textContent = '';
el.setAttribute('viewBox', '0 0 ' + W + ' ' + H);
el.setAttribute('width', W);
el.setAttribute('height', H);
var defs = svg('defs', {}, el);
var above = svg('clipPath', { id: id + '-a' }, defs);
svg('rect', { x: m.l, y: m.t, width: iw, height: Math.max(zeroY - m.t, 0) }, above);
var below = svg('clipPath', { id: id + '-b' }, defs);
svg('rect', { x: m.l, y: zeroY, width: iw, height: Math.max(m.t + ih - zeroY, 0) }, below);
svg('rect', { 'class': 'llrg-bg', x: m.l, y: m.t, width: iw, height: ih }, el);
// Horizontal grid + labels: top, middle, bottom
[yMax, (yMin + yMax) / 2, yMin].forEach(function (value) {
var y = sy(value);
svg('line', { 'class': 'llrg-grid', x1: m.l, x2: m.l + iw, y1: y, y2: y }, el);
var label = svg('text', { 'class': 'llrg-tick', x: m.l - 6, y: y, dy: '0.32em', 'text-anchor': 'end' }, el);
label.textContent = fmt(value);
});
// Vertical grid
[0.25, 0.5, 0.75].forEach(function (fraction) {
var x = m.l + iw * fraction;
svg('line', { 'class': 'llrg-grid', x1: x, x2: x, y1: m.t, y2: m.t + ih }, el);
});
// Games axis
[[0, 'start', m.l], [xMax / 2, 'middle', m.l + iw / 2], [xMax, 'end', m.l + iw]].forEach(function (tick) {
var label = svg('text', { 'class': 'llrg-tick', x: tick[2], y: H - 5, 'text-anchor': tick[1] }, el);
label.textContent = tick[0] === 0 ? '0' : compact(tick[0]);
});
// Bounds and zero, when they are in range
var lower = this.lower, upper = this.upper;
[[lower, 'llrg-bound'], [0, 'llrg-zero'], [upper, 'llrg-bound']].forEach(function (guide) {
if (guide[0] >= yMin && guide[0] <= yMax) {
var y = sy(guide[0]);
svg('line', { 'class': guide[1], x1: m.l, x2: m.l + iw, y1: y, y2: y }, el);
}
});
// The line: green above zero, red below
var drawn = points.length > iw * 1.5 ? decimate(points, sx) : points;
var d = drawn.map(function (p, i) {
return (i ? 'L' : 'M') + sx(p.games).toFixed(1) + ' ' + sy(p.llr).toFixed(1);
}).join('');
svg('path', { 'class': 'llrg-line llrg-line-pos', d: d, 'clip-path': 'url(#' + id + '-a)' }, el);
svg('path', { 'class': 'llrg-line llrg-line-neg', d: d, 'clip-path': 'url(#' + id + '-b)' }, el);
// Marker
this.hoverLine = svg('line', { 'class': 'llrg-hover-line', y1: m.t, y2: m.t + ih }, el);
this.hoverDot = svg('circle', { 'class': 'llrg-hover-dot', r: 3.5 }, el);
if (this.active >= 0)
this.setActive(this.active);
};
/* Live updates: take a newer answer from the server and redraw in place.
The plot, and whichever point is being inspected, stay where they are. */
Graph.prototype.update = function (data) {
this.lower = Number(data.lower);
this.upper = Number(data.upper);
this.games = Number(data.games);
this.points = data.history.map(function (p) {
return { games: Number(p[0]), llr: Number(p[1]), estimated: !!p[2] };
}).sort(function (a, b) { return a.games - b.games; });
if (this.active >= this.points.length)
this.active = -1;
this.render();
};
/* ---------- snapping ---------- */
Graph.prototype.pick = function (x) {
var g = this.g, points = this.points;
var target = clamp((x - g.m.l) / g.iw, 0, 1) * g.xMax;
// Nearest point
var after = Math.min(lowerBound(points, target), points.length - 1);
var before = Math.max(after - 1, 0);
var best = Math.abs(g.sx(points[before].games) - x) <= Math.abs(g.sx(points[after].games) - x) ? before : after;
// Nearest peak / valley, if the pointer is close enough to one
var magnet = -1, magnetDistance = MAGNET + 1;
for (var i = 0; i < this.pivots.length; i++) {
var distance = Math.abs(g.sx(points[this.pivots[i]].games) - x);
if (distance < magnetDistance) {
magnet = this.pivots[i];
magnetDistance = distance;
}
}
return magnet >= 0 ? magnet : best;
};
Graph.prototype.setActive = function (index) {
if (index < 0 || !this.g) {
this.active = -1;
this.hoverLine.classList.remove('active');
this.hoverDot.classList.remove('active', 'llrg-pos', 'llrg-neg');
this.tip.classList.remove('active');
return;
}
var g = this.g, p = this.points[index];
var x = g.sx(p.games), y = g.sy(p.llr);
this.active = index;
this.hoverLine.setAttribute('x1', x);
this.hoverLine.setAttribute('x2', x);
this.hoverDot.setAttribute('cx', x);
this.hoverDot.setAttribute('cy', y);
this.hoverDot.setAttribute('class', 'llrg-hover-dot active ' + (p.llr >= 0 ? 'llrg-pos' : 'llrg-neg'));
this.hoverLine.classList.add('active');
this.tip.textContent = commas(p.games) + ' games | LLR ' + (p.estimated ? '\u2248' : '') + fmt(p.llr);
this.tip.classList.add('active');
var left = clamp(x + 8, 0, g.W - this.tip.offsetWidth);
var top = clamp(y - this.tip.offsetHeight - 8, 0, g.H - this.tip.offsetHeight);
this.tip.style.left = left + 'px';
this.tip.style.top = top + 'px';
};
/* ---------- events ---------- */
Graph.prototype.bind = function () {
var self = this, plot = this.plot;
function move(event) {
if (!self.g)
return;
var box = self.svgEl.getBoundingClientRect();
var x = (event.clientX - box.left) * (self.g.W / (box.width || self.g.W));
self.setActive(self.pick(x));
}
plot.addEventListener('pointerenter', move);
plot.addEventListener('pointermove', move);
plot.addEventListener('pointerdown', move);
plot.addEventListener('pointerleave', function (event) {
if (event.pointerType === 'mouse')
self.setActive(-1);
});
plot.addEventListener('keydown', function (event) {
var last = self.points.length - 1;
var step = event.shiftKey ? 10 : 1;
var index = self.active;
if (event.key === 'ArrowLeft') index = index < 0 ? last : index - step;
else if (event.key === 'ArrowRight') index = index < 0 ? last : index + step;
else if (event.key === 'Home') index = 0;
else if (event.key === 'End') index = last;
else if (event.key === 'Escape') { self.setActive(-1); return; }
else return;
event.preventDefault();
self.setActive(clamp(index, 0, last));
});
plot.addEventListener('blur', function () { self.setActive(-1); });
function redraw() {
if (Math.floor(plot.clientWidth) !== self.rendered)
self.render();
}
if ('ResizeObserver' in window) {
var queued = false;
new ResizeObserver(function () {
if (queued) return;
queued = true;
window.requestAnimationFrame(function () { queued = false; redraw(); });
}).observe(plot);
} else {
window.addEventListener('resize', redraw);
}
};
/* ======================================================================
Loading
====================================================================== */
function showError(container, text) {
container.removeAttribute('aria-busy');
container.innerHTML = '<div class="llr-history-placeholder llr-history-placeholder-error">' + text + '</div>';
}
function load(container) {
var url = container.getAttribute('data-history-url');
if (!url)
return;
container.setAttribute('aria-busy', 'true');
fetch(url, { credentials: 'same-origin' }).then(function (response) {
if (!response.ok)
throw new Error('Unable to load history graph');
return response.text();
}).then(function (markup) {
container.innerHTML = markup;
container.removeAttribute('aria-busy');
var node = container.querySelector('.llr-chart');
if (!node)
return showError(container, 'No history to show yet.');
graph = new Graph(node, JSON.parse(node.getAttribute('data-chart')));
}).catch(function () {
showError(container, 'Unable to load history graph.');
});
}
var graph = null;
function refresh(container) {
var url = container.getAttribute('data-history-url');
if (!url || !graph)
return Promise.resolve();
return fetch(url, { credentials: 'same-origin', cache: 'no-store' }).then(function (response) {
if (!response.ok)
throw new Error('Unable to refresh history graph');
return response.text();
}).then(function (markup) {
var holder = document.createElement('div');
holder.innerHTML = markup;
var node = holder.querySelector('.llr-chart');
if (node)
graph.update(JSON.parse(node.getAttribute('data-chart')));
});
}
// Called by live.js whenever the page has been brought up to date
window.refreshLLRHistory = function () {
var container = document.getElementById('llr-history-container');
return container ? refresh(container).catch(function () { /* keep the current graph */ }) : Promise.resolve();
};
document.addEventListener('DOMContentLoaded', function () {
var container = document.getElementById('llr-history-container');
if (container)
load(container);
});
})();
+21 -130
View File
@@ -1,133 +1,24 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <?xml version="1.0" encoding="UTF-8"?>
<svg <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 250 250" width="250" height="250">
xmlns:dc="http://purl.org/dc/elements/1.1/" <title>OpenBench</title>
xmlns:cc="http://creativecommons.org/ns#" <defs>
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" <clipPath id="tile">
xmlns:svg="http://www.w3.org/2000/svg" <rect width="250" height="250" rx="48"/>
xmlns="http://www.w3.org/2000/svg" </clipPath>
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="250mm"
height="250mm"
viewBox="0 0 250 250"
version="1.1"
id="svg8"
inkscape:version="1.0 (4035a4f, 2020-05-01)"
sodipodi:docname="logo.svg">
<defs
id="defs2">
<inkscape:perspective
sodipodi:type="inkscape:persp3d"
inkscape:vp_x="-192.73904 : 85.416586 : 1"
inkscape:vp_y="0 : 999.99996 : 0"
inkscape:vp_z="210 : 101.5 : 1"
inkscape:persp3d-origin="105 : 51.999997 : 1"
id="perspective857" />
<rect
x="191.06123"
y="167.60974"
width="9.3152771"
height="28.649736"
id="rect853" />
<rect
x="120.10982"
y="27.845661"
width="83.140968"
height="150.35945"
id="rect24" />
<rect
x="113.84743"
y="28.873098"
width="68.721581"
height="89.834076"
id="rect18" />
<rect
x="37.502277"
y="98.018333"
width="79.874741"
height="106.64691"
id="rect12" />
</defs> </defs>
<sodipodi:namedview
id="base" <!-- Board: graphite base, accent-green and surface-grey squares -->
pagecolor="#ffffff" <g clip-path="url(#tile)">
bordercolor="#666666" <rect width="250" height="250" fill="#14161A"/>
borderopacity="1.0" <rect x="0" y="0" width="125" height="125" fill="#4F8160"/>
inkscape:pageopacity="0.0" <rect x="125" y="125" width="125" height="125" fill="#4F8160"/>
inkscape:pageshadow="2" <rect x="125" y="0" width="125" height="125" fill="#23272D"/>
inkscape:zoom="1" <rect x="0" y="125" width="125" height="125" fill="#23272D"/>
inkscape:cx="509.11884"
inkscape:cy="432.95515"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
inkscape:document-rotation="0"
showgrid="false"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="0"
fit-margin-bottom="0"
inkscape:snap-bbox="false"
inkscape:window-width="1853"
inkscape:window-height="1025"
inkscape:window-x="67"
inkscape:window-y="27"
inkscape:window-maximized="1" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(16.1122,-26.054426)">
<rect
style="fill:#94e196;fill-opacity:1;stroke-width:0.264583"
id="rect873"
width="250"
height="250"
x="-16.1122"
y="26.054426" />
<g
id="g949">
<rect
y="26.054426"
x="-16.1122"
height="125"
width="125"
id="rect875"
style="fill:#118c40;fill-opacity:1;stroke-width:0.264583" />
<rect
style="fill:#118c40;fill-opacity:1;stroke-width:0.264583"
id="rect875-3"
width="125"
height="125"
x="108.88778"
y="151.05443" />
</g>
<text
xml:space="preserve"
id="text16"
style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;white-space:pre;shape-inside:url(#rect18);fill:#000000;fill-opacity:1;stroke:none;" />
<path
id="path860"
style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-size:88.1944px;line-height:1.25;font-family:sans-serif;-inkscape-font-specification:'sans-serif Bold';white-space:pre;fill:#0d0208;fill-opacity:1;stroke:none;stroke-width:3.24563"
d="m 108.88778,78.418988 q -23.454412,0 -36.380997,19.056735 -12.926584,19.056717 -12.926584,53.651967 0,34.4487 12.926584,53.50539 12.926585,19.05675 36.380997,19.05675 23.5877,0 36.51428,-19.05675 12.92658,-19.05669 12.92658,-53.50539 0,-34.59525 -12.92658,-53.651967 -12.92658,-19.056735 -36.51428,-19.056735 z m 0,-40.898628 q 47.97497,0 75.16077,30.197581 27.18582,30.197552 27.18582,83.409749 0,53.06564 -27.18582,83.26322 -27.1858,30.19758 -75.16077,30.19758 -47.841678,0 -75.16075,-30.19758 Q 6.5412263,204.19333 6.5412263,151.12769 6.5412263,97.915493 33.72703,67.717941 61.046102,37.52036 108.88778,37.52036 Z" />
<path
id="path863"
style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-size:105.833px;line-height:1.25;font-family:sans-serif;-inkscape-font-specification:'sans-serif Bold';white-space:pre;fill:#008f11;fill-opacity:1;stroke:none;stroke-width:2.06305"
d="m -87.315338,146.28255 q 9.70158,0 14.71229,-4.26443 5.0107,-4.26443 5.0107,-12.58006 0,-8.20903 -5.0107,-12.47346 -5.01071,-4.37104 -14.71229,-4.37104 h -22.708072 v 33.68899 z m 1.38594,69.6168 q 12.36685,0 18.55028,-5.22393 6.29004,-5.22391 6.29004,-15.77838 0,-10.34124 -6.18344,-15.45855 -6.18341,-5.22393 -18.65688,-5.22393 h -24.094012 v 41.68479 z m 38.16665,-57.24996 q 13.21974,3.83799 20.46925,14.17923 7.24954,10.34124 7.24954,25.37335 0,23.02791 -15.56518,34.32866 -15.56515,11.30073 -47.33515,11.30073 H -151.06855 V 84.661543 h 61.621012 q 33.15594,0 47.97482,10.02141 14.92551,10.021417 14.92551,32.089837 0,11.62057 -5.43715,19.82959 -5.43714,8.10242 -15.77839,12.04701 z" />
<text
xml:space="preserve"
id="text851"
style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;white-space:pre;shape-inside:url(#rect853);fill:#000000;fill-opacity:1;stroke:none;" />
</g> </g>
<!-- Thin rim so the tile stays defined on dark browser chrome -->
<rect x="1.5" y="1.5" width="247" height="247" rx="46.5" fill="none" stroke="#3A3F48" stroke-width="3"/>
<!-- O, in the theme's bone text colour -->
<circle cx="125" cy="125" r="62" fill="none" stroke="#EDEAE3" stroke-width="32"/>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 1008 B

+35 -17
View File
@@ -1,10 +1,14 @@
/* ==========================================================================
OpenBench - pagination (modern dark theme)
========================================================================== */
.pagination { .pagination {
display: inline-flex; display: inline-flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
} }
#pagebrowse { #pagebrowser {
display: flex; display: flex;
justify-content: center; justify-content: center;
} }
@@ -15,42 +19,56 @@
.page, .ellipsis { .page, .ellipsis {
display: inline-block; display: inline-block;
padding: 6px 1rem; box-sizing: border-box;
margin: 0; padding: 0 0.85rem;
border-left: 1px solid var(--color1); margin: 0 0 0 -1px;
border-right: 1px solid var(--color1); border: 1px solid var(--line-strong);
background-color: var(--color2); /* Dark background color */ background-color: var(--color2);
color: var(--color-font2); color: var(--color-font2);
font-size: 13px;
font-variant-numeric: tabular-nums;
text-decoration: none; text-decoration: none;
cursor: pointer; cursor: pointer;
transition: background-color 0.2s; /* Add a smooth transition effect to background color */ transition: background-color 0.15s ease, color 0.15s ease, border-color 0.15s ease;
height: 24px; /* This is just an example, adjust according to your needs */ height: 30px;
line-height: 24px; /* Should be same as height */ line-height: 28px;
min-width: 1.6rem; min-width: 2rem;
text-align: center; text-align: center;
vertical-align: middle; vertical-align: middle;
} }
.page:hover { .page:hover {
background-color: var(--color3); /* Darker background color on hover */ background-color: var(--surface-hover);
border-color: #3A4862;
color: var(--color-font1);
position: relative;
} }
.previous { .previous {
border-top-left-radius: 7px; border-top-left-radius: 2px;
border-bottom-left-radius: 7px; border-bottom-left-radius: 2px;
} }
.current { .current {
background-color: var(--color3); background-color: var(--accent);
border-color: var(--accent);
color: #FFFFFF;
font-weight: 600;
position: relative;
}
.current:hover {
background-color: var(--accent);
border-color: var(--accent);
color: #FFFFFF;
} }
.next { .next {
border-top-right-radius: 7px; border-top-right-radius: 2px;
border-bottom-right-radius: 7px; border-bottom-right-radius: 2px;
} }
.ellipsis, .fa-solid { .ellipsis, .fa-solid {
/*margin: 0 4px;*/
pointer-events: none; /* Disable click events on ellipsis */ pointer-events: none; /* Disable click events on ellipsis */
vertical-align: middle; /* Ensure icons are vertically centered */ vertical-align: middle; /* Ensure icons are vertically centered */
} }
+286
View File
@@ -0,0 +1,286 @@
/* ==========================================================================
Quick search ( Ctrl+K ): a Spotlight-style palette.
Loaded after refresh.css, and uses its tokens.
========================================================================== */
html.palette-open { overflow: hidden; }
/* The shortcut hint inside the top bar button */
.topbar-kbd {
margin-left: 8px;
padding: 1px 6px;
border: 1px solid var(--line-strong);
border-radius: 5px;
color: var(--muted);
font-family: var(--font-mono, ui-monospace, "JetBrains Mono", SFMono-Regular, Menlo, monospace);
font-size: 11px;
line-height: 1.5;
}
@media (hover: none), (max-width: 900px) {
.topbar-kbd { display: none; }
}
/* Overlay */
#palette {
position: fixed;
inset: 0;
z-index: 1000;
display: flex;
justify-content: center;
align-items: flex-start;
padding: 13vh 16px 16px;
}
#palette[hidden] { display: none; }
.pl-backdrop {
position: absolute;
inset: 0;
background: rgba(8, 9, 11, 0.55);
-webkit-backdrop-filter: blur(6px);
backdrop-filter: blur(6px);
}
/* Panel */
.pl-panel {
position: relative;
display: flex;
flex-direction: column;
width: min(660px, 100%);
max-height: min(70vh, 560px);
overflow: hidden;
background: rgba(31, 34, 39, 0.9);
-webkit-backdrop-filter: blur(28px) saturate(1.4);
backdrop-filter: blur(28px) saturate(1.4);
border: 1px solid rgba(237, 234, 227, 0.1);
border-radius: 14px;
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.55), 0 0 0 0.5px rgba(0, 0, 0, 0.6);
}
@supports not ((backdrop-filter: blur(1px)) or (-webkit-backdrop-filter: blur(1px))) {
.pl-panel { background: #1F2227; }
}
/* Search field: big and quiet, like the one on macOS */
.pl-field {
display: flex;
align-items: center;
gap: 14px;
padding: 16px 20px;
}
.pl-glass {
flex: none;
color: var(--muted);
font-size: 18px;
}
#palette input.pl-input {
flex: 1;
width: 100%;
height: auto;
margin: 0;
padding: 0;
background: transparent;
border: 0;
border-radius: 0;
box-shadow: none;
outline: none;
color: var(--color-font1);
font-family: inherit;
font-size: 20px;
font-weight: 400;
line-height: 1.3;
}
#palette input.pl-input::placeholder { color: var(--muted); opacity: 1; }
/* Results */
.pl-list {
flex: 1 1 auto;
min-height: 0;
margin: 0;
padding: 6px 8px 8px;
list-style: none;
overflow-y: auto;
overscroll-behavior: contain;
border-top: 1px solid var(--line);
}
.pl-group {
padding: 10px 12px 4px;
color: var(--muted);
font-size: 12px;
font-weight: 600;
}
.pl-group:first-child { padding-top: 6px; }
.pl-item {
display: flex;
align-items: center;
gap: 12px;
padding: 7px 10px;
border-radius: 9px;
color: var(--color-font1);
cursor: pointer;
}
.pl-icon {
flex: none;
display: grid;
place-items: center;
width: 30px;
height: 30px;
border-radius: 8px;
background: var(--accent-soft);
color: var(--accent-hover);
font-size: 14px;
}
.pl-text {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 1px;
}
.pl-title {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
font-size: 15px;
line-height: 1.3;
}
.pl-title b { font-weight: 700; }
.pl-sub {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
color: var(--muted);
font-size: 12.5px;
line-height: 1.3;
}
.pl-ext {
flex: none;
color: var(--muted);
font-size: 11px;
}
/* A test's verdict */
.pl-chip {
flex: none;
padding: 2px 9px;
border-radius: 999px;
background: rgba(237, 234, 227, 0.08);
color: var(--color-font2);
font-size: 11.5px;
font-weight: 600;
}
.pl-chip[data-state="passed"] { background: rgba(110, 219, 154, 0.14); color: var(--ok); }
.pl-chip[data-state="failed"] { background: rgba(239, 123, 114, 0.14); color: var(--bad); }
.pl-chip[data-state="running"] { background: var(--accent-soft); color: var(--accent-hover); }
.pl-chip[data-state="pending"],
.pl-chip[data-state="awaiting"] { background: rgba(233, 178, 76, 0.14); color: var(--warn); }
.pl-chip[data-state="stopped"] {
background-image: repeating-linear-gradient(135deg, transparent 0, transparent 4px, rgba(237, 234, 227, 0.14) 4px, rgba(237, 234, 227, 0.14) 5.5px);
}
.pl-enter {
display: none;
flex: none;
margin-left: 2px;
font-family: inherit;
font-size: 14px;
opacity: 0.9;
}
/* The row Enter would open: filled like a selection on macOS */
.pl-item[aria-selected="true"] {
background: var(--accent);
color: #fff;
}
.pl-item[aria-selected="true"] .pl-icon { background: rgba(255, 255, 255, 0.18); color: #fff; }
.pl-item[aria-selected="true"] .pl-sub,
.pl-item[aria-selected="true"] .pl-ext { color: rgba(255, 255, 255, 0.95); }
.pl-item[aria-selected="true"] .pl-chip { background: rgba(255, 255, 255, 0.2); background-image: none; color: #fff; }
.pl-item[aria-selected="true"] .pl-enter { display: block; }
/* Footer with the keys */
.pl-foot {
display: flex;
gap: 18px;
padding: 9px 16px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 12px;
}
.pl-foot kbd {
display: inline-grid;
place-items: center;
min-width: 20px;
height: 20px;
margin-right: 6px;
padding: 0 5px;
border: 1px solid var(--line);
border-radius: 5px;
background: rgba(237, 234, 227, 0.08);
color: var(--color-font2);
font-family: var(--font-sans);
font-size: 11px;
font-weight: 500;
line-height: 1;
}
.pl-foot kbd + kbd { margin-left: -2px; }
.pl-sr {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
white-space: nowrap;
}
/* Motion: only when the palette is opened, and never for people who ask for less */
@keyframes pl-panel-in {
from { opacity: 0; transform: translateY(-8px) scale(0.985); }
to { opacity: 1; transform: none; }
}
@keyframes pl-fade-in {
from { opacity: 0; }
to { opacity: 1; }
}
#palette.is-open .pl-panel { animation: pl-panel-in 0.16s cubic-bezier(0.2, 0.8, 0.2, 1); }
#palette.is-open .pl-backdrop { animation: pl-fade-in 0.16s ease-out; }
@media (prefers-reduced-motion: reduce) {
#palette.is-open .pl-panel,
#palette.is-open .pl-backdrop { animation: none; }
}
@media (max-width: 640px) {
#palette { padding-top: 8vh; }
#palette input.pl-input { font-size: 17px; }
.pl-foot { display: none; }
}
+462
View File
@@ -0,0 +1,462 @@
/* OpenBench quick search: a Spotlight-style palette.
Opens with Ctrl+K or Cmd+K ( and with / outside of text fields ).
No dependencies. Without this file the Search button still opens /search. */
(function () {
'use strict';
var root = document.getElementById('palette');
var source = document.getElementById('palette-source');
if (!root || !source) return;
var input = root.querySelector('.pl-input');
var list = root.querySelector('.pl-list');
var status = root.querySelector('.pl-sr');
var form = document.getElementById('palette-search');
var trigger = document.getElementById('palette-open');
var isMac = /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || '');
var STATES = {
passed: 'Passed', failed: 'Failed', stopped: 'Stopped', running: 'Running',
pending: 'Pending', awaiting: 'Awaiting', deleted: 'Deleted'
};
/* Pages and actions come from the server, so they follow the login state */
var pages = Array.prototype.map.call(source.querySelectorAll('li'), function (li) {
return {
kind : 'link',
key : 'page:' + li.getAttribute('data-href'),
title : li.textContent.trim(),
href : li.getAttribute('data-href'),
icon : li.getAttribute('data-icon') || 'fa-arrow-right',
group : li.getAttribute('data-group') || 'Go to',
keywords : (li.getAttribute('data-keywords') || '').toLowerCase(),
featured : li.hasAttribute('data-featured'),
external : li.hasAttribute('data-external')
};
});
var rows = []; // what is on screen: { item, el }
var active = -1;
var moved = false; // the person has picked a row themselves
var returnTo = null;
var cache = {}; // query -> tests from the server
var lastTests = []; // the latest answer, shown while the next one loads
var inflight = null; // { timer, controller }
/* ---------- Matching ---------- */
function match(text, query) {
if (!query) return { score: 0, hits: [] };
var t = text.toLowerCase(), q = query.toLowerCase();
var at = t.indexOf(q), hits = [], i;
if (at !== -1) {
for (i = 0; i < q.length; i++) hits.push(at + i);
var boundary = at === 0 || /[\s\-_\/.]/.test(t.charAt(at - 1));
return { score: (at === 0 ? 120 : boundary ? 100 : 70) - Math.min(at, 30), hits: hits };
}
// The letters in order, so that "mch" still finds "Machines"
var from = 0, gaps = 0;
for (i = 0; i < q.length; i++) {
var found = t.indexOf(q.charAt(i), from);
if (found === -1) return null;
if (hits.length && found !== hits[hits.length - 1] + 1) gaps++;
hits.push(found);
from = found + 1;
}
return { score: Math.max(10, 50 - gaps * 8), hits: hits };
}
function liveTests(q) {
if (cache[q]) return cache[q];
// Until the answer for this exact query arrives, keep what still fits
var needle = q.toLowerCase();
return lastTests.filter(function (t) {
return (t.name + ' ' + t.author + ' ' + t.engine + ' ' + t.id).toLowerCase().indexOf(needle) !== -1;
});
}
/* ---------- What to show ---------- */
function buildGroups(q) {
var groups = [], i;
// Tests: a direct jump for numbers, then whatever the server found
var tests = liveTests(q).map(function (t) {
var m = match(t.name, q);
return {
kind: 'link', key: 'test:' + t.id, href: t.url, icon: 'fa-flask',
title: t.name, hits: m ? m.hits : [], state: t.status,
sub: '#' + t.id + ' by ' + t.author + ', ' + t.tc
};
});
var number = /^#?(\d{1,9})$/.exec(q);
if (number && !tests.some(function (t) { return t.key === 'test:' + number[1]; })) {
tests.unshift({
kind: 'link', key: 'test:' + number[1], href: '/test/' + number[1] + '/', icon: 'fa-flask',
title: 'Open test #' + number[1], sub: 'Jump straight to it', hits: []
});
}
// Pages and actions, grouped as on the server, best group first
var buckets = [], byName = {};
pages.forEach(function (page) {
var m = null;
if (!q) { if (!page.featured) return; m = { score: 0, hits: [] }; }
else {
m = match(page.title, q);
if (!m && page.keywords.indexOf(q.toLowerCase()) !== -1) m = { score: 35, hits: [] };
}
if (!m) return;
var bucket = byName[page.group];
if (!bucket) { bucket = byName[page.group] = { label: page.group, best: 0, items: [] }; buckets.push(bucket); }
bucket.best = Math.max(bucket.best, m.score);
bucket.items.push({ item: page, score: m.score, hits: m.hits });
});
var best = 0;
if (q) buckets.sort(function (a, b) { return b.best - a.best; });
buckets.forEach(function (bucket) {
if (q) bucket.items.sort(function (a, b) { return b.score - a.score; });
best = Math.max(best, bucket.best);
});
var pageGroups = buckets.map(function (bucket) {
return {
label: bucket.label,
items: bucket.items.map(function (entry) {
var item = Object.create(entry.item);
item.hits = entry.hits;
return item;
})
};
});
var testGroup = tests.length ? [{ label: 'Tests', items: tests }] : [];
// A page that starts with what was typed wins, otherwise tests come first
groups = (q && best < 100) ? testGroup.concat(pageGroups) : pageGroups.concat(testGroup);
if (q) {
groups.push({ label: 'Search', items: [{
kind: 'search', key: 'search', icon: 'fa-magnifying-glass', hits: [],
title: 'Search all tests for \u201C' + q + '\u201D', sub: 'Looks through every branch name'
}] });
}
return groups;
}
/* ---------- Drawing ---------- */
function fill(el, text, hits) {
if (!hits || !hits.length) { el.textContent = text; return; }
var marked = {}, run = '', on = false, i;
hits.forEach(function (h) { marked[h] = true; });
function flush() {
if (!run) return;
if (on) { var b = document.createElement('b'); b.textContent = run; el.appendChild(b); }
else el.appendChild(document.createTextNode(run));
run = '';
}
for (i = 0; i < text.length; i++) {
var hit = !!marked[i];
if (hit !== on) { flush(); on = hit; }
run += text.charAt(i);
}
flush();
}
function element(tag, className, text) {
var el = document.createElement(tag);
if (className) el.className = className;
if (text) el.textContent = text;
return el;
}
function buildRow(item, index) {
var li = element('li', 'pl-item');
li.id = 'pl-opt-' + index;
li.setAttribute('role', 'option');
li.setAttribute('aria-selected', 'false');
li.setAttribute('data-index', index);
var tile = element('span', 'pl-icon');
var icon = element('i', 'fa-solid ' + item.icon);
icon.setAttribute('aria-hidden', 'true');
tile.appendChild(icon);
var text = element('span', 'pl-text');
var title = element('span', 'pl-title');
fill(title, item.title, item.hits);
text.appendChild(title);
if (item.sub) text.appendChild(element('span', 'pl-sub', item.sub));
li.appendChild(tile);
li.appendChild(text);
if (item.state) {
var chip = element('span', 'pl-chip', STATES[item.state] || item.state);
chip.setAttribute('data-state', item.state);
li.appendChild(chip);
}
if (item.external) {
var out = element('i', 'fa-solid fa-arrow-up-right-from-square pl-ext');
out.setAttribute('aria-hidden', 'true');
li.appendChild(out);
}
var enter = element('kbd', 'pl-enter', '\u21B5');
enter.setAttribute('aria-hidden', 'true');
li.appendChild(enter);
return li;
}
function setActive(index, scroll) {
if (rows[active]) rows[active].el.setAttribute('aria-selected', 'false');
active = index;
if (!rows[index]) { input.removeAttribute('aria-activedescendant'); return; }
rows[index].el.setAttribute('aria-selected', 'true');
input.setAttribute('aria-activedescendant', rows[index].el.id);
if (!scroll) return;
if (index === 0) list.scrollTop = 0;
else rows[index].el.scrollIntoView({ block: 'nearest' });
}
function render() {
var q = input.value.trim();
var keep = moved && rows[active] ? rows[active].item.key : null;
list.textContent = '';
rows = [];
buildGroups(q).forEach(function (group) {
var head = element('li', 'pl-group', group.label);
head.setAttribute('role', 'presentation');
list.appendChild(head);
group.items.forEach(function (item) {
var el = buildRow(item, rows.length);
list.appendChild(el);
rows.push({ item: item, el: el });
});
});
var next = 0;
rows.forEach(function (row, i) { if (keep && row.item.key === keep) next = i; });
active = -1;
setActive(rows.length ? next : -1, false);
status.textContent = rows.length + (rows.length === 1 ? ' result' : ' results');
}
/* ---------- Asking the server for tests ---------- */
function cancel() {
if (!inflight) return;
if (inflight.timer) clearTimeout(inflight.timer);
if (inflight.controller) inflight.controller.abort();
inflight = null;
}
function request(q) {
var controller = window.AbortController ? new AbortController() : null;
inflight = { timer: null, controller: controller };
fetch('/api/quick-search/?q=' + encodeURIComponent(q), {
credentials : 'same-origin',
headers : { 'Accept': 'application/json' },
signal : controller ? controller.signal : undefined
})
.then(function (response) { return response.ok ? response.json() : { tests: [] }; })
.then(function (data) {
cache[q] = data.tests || [];
lastTests = cache[q];
if (input.value.trim() === q) render();
})
.catch(function () { /* aborted, or offline: pages still work */ });
}
function schedule() {
cancel();
var q = input.value.trim();
if (!q || cache[q]) return;
inflight = { timer: setTimeout(function () { request(q); }, 140), controller: null };
}
/* ---------- Opening, closing, choosing ---------- */
function isOpen() { return !root.hidden; }
function open() {
if (isOpen()) return;
returnTo = document.activeElement;
root.hidden = false;
root.classList.remove('is-open');
void root.offsetWidth; // restart the entrance animation
root.classList.add('is-open');
document.documentElement.classList.add('palette-open');
if (trigger) trigger.setAttribute('aria-expanded', 'true');
input.value = '';
moved = false;
render();
input.focus();
}
function close() {
if (!isOpen()) return;
cancel();
root.hidden = true;
root.classList.remove('is-open');
document.documentElement.classList.remove('palette-open');
if (trigger) trigger.setAttribute('aria-expanded', 'false');
if (returnTo && returnTo.focus && document.contains(returnTo)) returnTo.focus();
}
function choose(item, newTab) {
if (item.kind === 'search') {
form.querySelector('[name="keywords"]').value = input.value.trim();
form.submit();
return;
}
if (item.external || newTab) {
window.open(item.href, '_blank', 'noopener');
close();
return;
}
window.location.href = item.href;
close();
}
function move(step) {
if (!rows.length) return;
moved = true;
setActive((active + step + rows.length) % rows.length, true);
}
/* ---------- Events ---------- */
input.addEventListener('input', function () {
moved = false;
render();
schedule();
});
input.addEventListener('keydown', function (event) {
if (event.isComposing) return;
if (event.key === 'ArrowDown') { event.preventDefault(); move(1); }
else if (event.key === 'ArrowUp') { event.preventDefault(); move(-1); }
else if (event.key === 'Tab') { event.preventDefault(); move(event.shiftKey ? -1 : 1); }
else if (event.key === 'Enter') {
event.preventDefault();
if (rows[active]) choose(rows[active].item, event.metaKey || event.ctrlKey);
}
else if (event.key === 'Escape') { event.preventDefault(); close(); }
});
// Keep the caret in the field while the pointer works on the list
list.addEventListener('mousedown', function (event) { event.preventDefault(); });
list.addEventListener('mousemove', function (event) {
var li = event.target.closest ? event.target.closest('.pl-item') : null;
if (!li) return;
var index = parseInt(li.getAttribute('data-index'), 10);
if (index !== active) { moved = true; setActive(index, false); }
});
list.addEventListener('click', function (event) {
var li = event.target.closest ? event.target.closest('.pl-item') : null;
if (!li) return;
var row = rows[parseInt(li.getAttribute('data-index'), 10)];
if (row) choose(row.item, event.metaKey || event.ctrlKey);
});
root.querySelector('.pl-backdrop').addEventListener('click', close);
// Nothing behind the palette should take the focus
root.addEventListener('focusin', function (event) {
if (!root.querySelector('.pl-panel').contains(event.target)) input.focus();
});
function typing(target) {
if (!target || !target.tagName) return false;
return /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName) || target.isContentEditable;
}
document.addEventListener('keydown', function (event) {
var key = (event.key || '').toLowerCase();
if ((event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey && key === 'k') {
event.preventDefault();
if (isOpen()) close(); else open();
return;
}
if (key === '/' && !event.metaKey && !event.ctrlKey && !event.altKey && !isOpen() && !typing(event.target)) {
event.preventDefault();
open();
}
}, true);
if (trigger) {
trigger.setAttribute('aria-haspopup', 'dialog');
trigger.setAttribute('aria-expanded', 'false');
trigger.addEventListener('click', function (event) {
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey) return;
event.preventDefault();
open();
});
}
// Coming back with the Back button should never show an open palette
window.addEventListener('pageshow', function (event) { if (event.persisted) close(); });
Array.prototype.forEach.call(document.querySelectorAll('.topbar-kbd'), function (hint) {
hint.textContent = isMac ? '\u2318K' : 'Ctrl K';
});
})();
+290
View File
@@ -0,0 +1,290 @@
/* ==========================================================================
OpenBench - design refresh
Loaded last (after style.css, ux.css, board.css). Only overrides tokens and
a handful of rules, so the older theme stays intact. Drop the <link> in
base.html to revert everything in one step.
Direction: warm graphite surfaces, bone-coloured text, a single board-green
accent. Colour is reserved for results (green / amber / red). The LLR gauge
on running SPRT tests is the one distinctive element; the rest stays quiet.
========================================================================== */
:root {
/* Surfaces */
--color1: #14161A;
--color2: #1A1D22;
--color3: #23272D;
--surface-head: #1F2227;
--surface-hover: #252A30;
/* Lines */
--line: #2A2E35;
--line-strong: #3A3F48;
/* Text */
--color-font1: #EDEAE3;
--color-font2: #C9C6BE;
--color-font3: #A9CDB3;
--muted: #8C8F96;
/* Accent: board green. Buttons use the darker value so white text passes AA. */
--accent: #4F8160;
--accent-hover: #6BA17D;
--accent-soft: rgba(94, 139, 106, 0.16);
--link: #8FC3A0;
--link-hover: #B9E0C6;
/* Results */
--ok: #6EDB9A;
--warn: #E8B84A;
--bad: #EF7B72;
--orange: #E8955A;
--purple: #B79FE0;
--purple-soft: rgba(183, 159, 224, 0.14);
--font-sans: "Instrument Sans", system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
--radius: 3px;
--shadow-card: none;
}
::selection {
background: rgba(94, 139, 106, 0.4);
}
/* ---------- Chrome ---------- */
#topbar {
background: rgba(20, 22, 26, 0.92);
}
#topbar .brand-name {
font-weight: 650;
}
.page-title {
font-size: 26px;
font-weight: 600;
letter-spacing: -0.015em;
}
/* ---------- Labels: sentence case instead of tracked capitals ---------- */
#sidebar .nav-title,
.card-title,
.badge,
.flag,
#content .table-header th,
#content .table-small-header th,
.stat-label,
.ev-meta dt,
.ev-facts dt,
.ev-player small,
.ev-sel-stats span {
text-transform: none;
letter-spacing: 0;
}
#sidebar .nav-title {
font-size: 12.5px;
font-weight: 600;
}
.card-title {
color: var(--color-font2);
font-size: 14px;
font-weight: 600;
}
#content .table-header th,
#content .table-small-header th {
font-size: 12.5px;
font-weight: 600;
}
/* The header's accent stripe carried no information */
#content .table-header th:first-child {
border-left: 0;
}
.stat-label,
.ev-meta dt,
.ev-facts dt,
.ev-player small {
font-size: 12.5px;
}
.flag {
font-size: 11px;
font-weight: 600;
}
.badge {
font-size: 12px;
font-weight: 600;
}
/* ---------- Surfaces: borders instead of shadows ---------- */
.card,
.stat-card {
box-shadow: none;
}
/* Fleet and queue counters: number first, icon as a quiet marker */
.stat-card {
flex-direction: row-reverse;
justify-content: space-between;
align-items: flex-start;
}
.stat-icon {
width: auto;
height: auto;
background: none !important;
font-size: 14px;
}
.stat-value {
font-size: 26px;
font-weight: 600;
}
/* ---------- Colour tokens that were hardcoded in older files ---------- */
.badge-info {
border-color: rgba(94, 139, 106, 0.45);
color: #A9D4B7;
}
#content a.seg-btn.active {
box-shadow: inset 0 0 0 1px rgba(94, 139, 106, 0.5);
}
.ev-move.is-active {
border-color: rgba(94, 139, 106, 0.5);
}
.ev-white .ev-piece { background-color: #EDEAE3; }
.ev-black .ev-piece { background-color: #14161A; }
/* ==========================================================================
LLR gauge (running SPRT tests)
The track runs from the lower bound (left) to the upper bound (right).
The tall tick marks LLR = 0; the fill grows from it towards the current
LLR, so direction and distance to a decision read at a glance.
========================================================================== */
.llr {
position: relative;
min-width: 150px;
height: 6px;
margin-top: 10px;
background-color: var(--line);
border-radius: 1px;
}
/* Bound markers at both ends */
.llr::before,
.llr::after {
content: '';
position: absolute;
top: -3px;
bottom: -3px;
width: 2px;
background-color: var(--line-strong);
}
.llr::before { left: 0; }
.llr::after { right: 0; }
.llr-fill {
position: absolute;
top: 0;
bottom: 0;
background-color: var(--muted);
}
.llr-pos .llr-fill { background-color: var(--ok); }
.llr-neg .llr-fill { background-color: var(--bad); }
.llr-zero {
position: absolute;
top: -4px;
bottom: -4px;
width: 1px;
background-color: var(--color-font2);
}
.llr-scale {
display: flex;
justify-content: space-between;
margin-top: 5px;
color: var(--muted);
font-family: var(--font-mono);
font-size: 10.5px;
font-variant-numeric: tabular-nums;
line-height: 1;
}
.llr-scale b {
color: var(--color-font1);
font-weight: 500;
}
/* ==========================================================================
Result cells
A filled cell is a verdict: green passed, blue passed as a non-regression
test, amber and red failed. A cell without a fill has no verdict yet, so it
is only outlined, in warm grey that cannot be mistaken for the blue.
A stopped test keeps the outline and gains diagonal hatching, like an entry
that has been struck out.
========================================================================== */
:root {
--hatch: rgba(237, 234, 227, 0.14);
}
/* Blue: a stronger fill, so it holds its own beside the green */
#content .statblock-blue {
background-color: rgba(76, 141, 255, 0.2);
color: #A9CBFF;
}
/* No verdict yet: running, pending, awaiting artifacts, stopped.
.statblock- is the empty colour name the template renders for them, which
also covers result cells that carry no state class. */
#content .statblock.statblock-,
#content .statblock.state-running,
#content .statblock.state-pending,
#content .statblock.state-awaiting,
#content .statblock.state-stopped {
background-color: transparent;
box-shadow: inset 0 0 0 1px var(--line-strong);
color: var(--color-font2);
}
/* Nothing has been played yet */
#content .statblock.state-pending,
#content .statblock.state-awaiting {
color: var(--muted);
}
#content .statblock.state-stopped {
background-image: repeating-linear-gradient(135deg, transparent 0, transparent 6px, var(--hatch) 6px, var(--hatch) 7.5px, transparent 7.5px, transparent 9px);
}
/* Author names are shown in full; very long ones are clipped with an ellipsis */
#content td.col-author {
max-width: 14ch;
}
#content td.col-author a {
display: block;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
+286
View File
@@ -0,0 +1,286 @@
/* Tune page: layout, collapsible sections, and the parameter history chart. */
/* ---------- Layout: a main column, and a side column ---------- */
#content .workload-container.tune-page {
display: grid;
grid-template-columns: minmax(0, 1fr) 320px;
gap: 20px;
align-items: start;
}
#content .tune-page > .tune-main {
grid-column: 1;
grid-row: 1;
display: flex;
flex-direction: column;
gap: 20px;
min-width: 0;
}
#content .tune-page > .tune-side {
grid-column: 2;
grid-row: 1;
display: flex;
flex-direction: column;
gap: 16px;
min-width: 0;
}
#content .tune-main > .card,
#content .tune-side > .card {
margin: 0;
}
/* Source order is side first; this puts the story in the right order */
#content .tune-main > #spsa-panel { order: 1; }
#content .tune-main > #results { order: 2; }
#content .tune-main > #parameters { order: 3; }
@media (max-width: 1000px) {
#content .workload-container.tune-page { grid-template-columns: minmax(0, 1fr); }
#content .tune-page > .tune-main { grid-column: 1; grid-row: 1; }
#content .tune-page > .tune-side { grid-column: 1; grid-row: 2; }
}
/* ---------- Spacing inside the cards ---------- */
/* .card has no padding of its own: only its header is padded, so whatever
follows has to keep clear of the border by itself. */
#content .spsa-panel { padding-bottom: 16px; }
#content .spsa-panel > :not(.card-head) {
margin-left: 16px;
margin-right: 16px;
}
#content .spsa-panel > .card-head + * { margin-top: 14px; }
/* The Modify button ends the Actions card and used to sit 4px from its edge */
#content .workload-container #actions { padding-bottom: 16px; }
#content .workload-container #actions .llr-history-panel { margin-bottom: 0; }
/* ---------- The parameter list scrolls inside the panel ---------- */
/* With dozens of parameters the list ran the page down to the results table.
It now keeps to a bounded height; the filter and sort bar above it stays in
view. The left padding keeps focus rings from being clipped. */
#content .spsa-panel .spsa-rows {
max-height: min(60vh, 540px);
overflow-y: auto;
overscroll-behavior: contain;
scrollbar-width: thin;
margin-left: 12px;
padding-left: 4px;
padding-right: 8px;
}
/* ---------- Collapsible sections ---------- */
#content details.config-fold {
padding: 0;
}
.config-fold > summary {
display: flex;
align-items: baseline;
gap: 12px;
padding: 14px 18px;
cursor: pointer;
list-style: none;
border-radius: inherit;
}
.config-fold > summary::-webkit-details-marker { display: none; }
.config-fold > summary .card-title { margin: 0; }
.config-fold > summary:focus-visible {
outline: 2px solid var(--accent, #4c8dff);
outline-offset: -2px;
}
.config-hint {
flex: 1 1 auto;
min-width: 0;
font-size: 12.5px;
color: var(--muted, var(--color-font3, #8b95a7));
}
.config-fold > summary::after {
content: '';
flex: none;
align-self: center;
width: 7px;
height: 7px;
border-right: 1.5px solid currentColor;
border-bottom: 1.5px solid currentColor;
opacity: .6;
transform: rotate(45deg) translateY(-2px);
transition: transform .15s ease;
}
.config-fold[open] > summary::after {
transform: rotate(-135deg) translateY(-2px);
}
.config-fold[open] > summary {
border-bottom: 1px solid var(--line, #2a303a);
}
.config-fold > :not(summary) {
padding-left: 18px;
padding-right: 18px;
}
.config-fold > table { margin-top: 8px; margin-bottom: 12px; width: calc(100% - 36px); }
/* ---------- Parameter names double as "show on chart" buttons ---------- */
button.spsa-name {
display: flex;
align-items: center;
gap: 8px;
margin: 0;
padding: 0;
text-align: left;
cursor: pointer;
color: var(--spsa-ink);
background: none;
border: 0;
font-family: var(--spsa-mono);
font-size: 13.5px;
}
button.spsa-name::before {
content: '';
flex: none;
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--row-color, transparent);
opacity: 0;
}
.spsa-row.is-shown button.spsa-name::before { opacity: 1; }
.spsa-row.is-pinned button.spsa-name { text-decoration: underline; text-underline-offset: 3px; }
button.spsa-name:focus-visible {
outline: 2px solid var(--spsa-fill);
outline-offset: 3px;
border-radius: 2px;
}
/* ---------- History chart ---------- */
.spsa-history {
padding: 4px 0 18px;
}
.spsa-history-head h3 {
margin: 0;
font-size: 14px;
font-weight: 600;
color: var(--spsa-ink);
}
.spsa-history-head p {
margin: 2px 0 10px;
font-size: 13px;
color: var(--spsa-muted);
}
.spsa-chart { position: relative; width: 100%; }
.sch-plot {
position: relative;
cursor: crosshair;
touch-action: pan-y;
user-select: none;
-webkit-user-select: none;
}
.sch-plot:focus-visible {
outline: 2px solid var(--spsa-fill);
outline-offset: 4px;
}
.sch-svg { display: block; width: 100%; height: auto; overflow: visible; }
.sch-bg { fill: transparent; }
.sch-grid { stroke: rgba(197, 204, 217, .09); stroke-width: 1; shape-rendering: crispEdges; }
.sch-zero { stroke: var(--spsa-muted); stroke-width: 1; opacity: .65; shape-rendering: crispEdges; }
.sch-tick {
fill: var(--spsa-muted);
font: 500 10px var(--spsa-mono);
}
.sch-line {
fill: none;
stroke-linecap: round;
stroke-linejoin: round;
}
.sch-line.is-quiet { stroke: var(--spsa-muted); stroke-width: 1; opacity: .24; }
.sch-line.is-on { stroke-width: 2; }
.sch-label { font: 600 11px var(--spsa-mono); }
.sch-hover-line {
stroke: var(--spsa-ink);
stroke-width: 1;
stroke-dasharray: 2 2;
opacity: 0;
}
.sch-hover-line.is-active { opacity: .7; }
.sch-dot { stroke: var(--color2, #1a1d22); stroke-width: 1.5; }
.c0 { stroke: #5fa0ff; fill: #5fa0ff; }
.c1 { stroke: #6ee7b7; fill: #6ee7b7; }
.c2 { stroke: #f2c94c; fill: #f2c94c; }
.c3 { stroke: #c4a1ff; fill: #c4a1ff; }
.c4 { stroke: #ff8f84; fill: #ff8f84; }
.sch-line.c0, .sch-line.c1, .sch-line.c2, .sch-line.c3, .sch-line.c4 { fill: none; }
.sch-label.c0, .sch-label.c1, .sch-label.c2, .sch-label.c3, .sch-label.c4 { stroke: none; }
.sch-tip {
position: absolute;
left: 0;
top: 0;
z-index: 1;
min-width: 150px;
padding: 8px 10px;
background: rgba(14, 16, 20, .96);
border: 1px solid var(--line-strong, #3a3f48);
border-radius: 4px;
color: var(--spsa-ink);
font: 500 12px var(--spsa-mono);
white-space: nowrap;
pointer-events: none;
opacity: 0;
transition: opacity .12s ease;
}
.sch-tip.is-active { opacity: 1; }
.sch-tip .t-games { margin-bottom: 4px; color: var(--spsa-muted); }
.sch-tip .t-row { display: flex; align-items: center; gap: 8px; line-height: 1.6; }
.sch-tip .t-swatch { flex: none; width: 8px; height: 8px; border-radius: 50%; }
.sch-tip .t-name { margin-right: auto; padding-right: 12px; }
.sch-tip .t-delta { color: var(--spsa-muted); }
.spsa-note {
margin: 8px 0 0;
font-size: 12.5px;
color: var(--spsa-muted);
}
@media (prefers-reduced-motion: reduce) {
.sch-tip, .config-fold > summary::after { transition: none; }
}
+511
View File
@@ -0,0 +1,511 @@
/* SPSA history chart (Tune pages).
The server (mytags.spsa_history_chart) supplies every parameter's value over
time as <div class="spsa-chart" data-chart="{json}">. Each line is one
parameter, drawn as how far it has travelled from its start value, as a share
of its allowed range, so parameters with very different scales share an axis.
A few lines are highlighted at a time. By default that is the three that moved
the most. Hovering a parameter's name in the list follows that one, and
clicking a name pins it, so several can be compared. */
(function () {
'use strict';
var SVG_NS = 'http://www.w3.org/2000/svg';
var MINUS = '−';
var HEIGHT = 230;
var MARGIN = { l: 46, r: 100, t: 12, b: 22 };
var COLOURS = 5;
var MAX_ON = 8;
function svg(name, attrs, parent) {
var node = document.createElementNS(SVG_NS, name);
for (var key in attrs)
if (Object.prototype.hasOwnProperty.call(attrs, key))
node.setAttribute(key, attrs[key]);
if (parent)
parent.appendChild(node);
return node;
}
function html(name, className, parent) {
var node = document.createElement(name);
if (className)
node.className = className;
if (parent)
parent.appendChild(node);
return node;
}
function clamp(value, lo, hi) {
return Math.max(lo, Math.min(hi, value));
}
function percent(value) {
var shown = Math.abs(value) < 10 ? Math.abs(value).toFixed(1) : String(Math.round(Math.abs(value)));
return (value > 0 ? '+' : value < 0 ? MINUS : '') + shown + '%';
}
function amount(value, integer) {
return integer ? String(Math.round(value)) : value.toFixed(4);
}
function commas(value) {
return String(Math.round(value)).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
function short(name) {
return name.length > 13 ? name.slice(0, 12) + '…' : name;
}
/* ---------- Chart ---------- */
function Chart(root, data, rows) {
var self = this;
this.root = root;
this.data = data;
this.rows = rows; // list items, by parameter index
this.pinned = [];
this.hover = -1;
this.active = -1;
this.width = 0;
this.load(data);
root.textContent = '';
this.plot = html('div', 'sch-plot', root);
this.plot.tabIndex = 0;
this.plot.setAttribute('role', 'img');
this.plot.setAttribute('aria-label', 'Parameter history. Use the arrow keys to inspect the points.');
this.svg = svg('svg', { 'class': 'sch-svg', 'aria-hidden': 'true' }, this.plot);
this.tip = html('div', 'sch-tip', this.plot);
this.render();
this.bind();
}
// What is drawn follows from the server's data. Live updates call this again with newer data.
Chart.prototype.load = function (data) {
this.data = data;
// Movement from the start value, as a share of the allowed range
this.series = data.names.map(function (name, i) {
var span = (data.max[i] - data.min[i]) || 1;
return data.points.map(function (point) {
return (point[1 + i] - data.start[i]) / span * 100;
});
});
// Without a choice, follow whichever parameters moved the most
var last = this.series.map(function (line, i) {
return { index: i, size: Math.abs(line[line.length - 1]) };
});
last.sort(function (a, b) { return b.size - a.size || a.index - b.index; });
this.defaults = last.slice(0, 3).map(function (entry) { return entry.index; });
};
// Newer data, same chart: pinned lines and the point being inspected stay as they are
Chart.prototype.update = function (data) {
this.load(data);
this.render();
};
Chart.prototype.shown = function () {
var list = this.pinned.slice();
if (this.hover >= 0 && list.indexOf(this.hover) < 0)
list.push(this.hover);
if (!list.length)
list = this.defaults.slice();
return list.slice(0, MAX_ON);
};
Chart.prototype.render = function () {
var W = Math.floor(this.plot.clientWidth);
if (W < 160)
return;
this.width = W;
var H = HEIGHT, m = MARGIN;
var iw = W - m.l - m.r, ih = H - m.t - m.b;
var points = this.data.points;
var xMax = Math.max(points[points.length - 1][0], 1);
var shown = this.shown();
var series = this.series;
// Vertical range: everything that moved, and zero
var lo = 0, hi = 0;
series.forEach(function (line) {
line.forEach(function (v) {
if (v < lo) lo = v;
if (v > hi) hi = v;
});
});
var pad = Math.max((hi - lo) * 0.12, 1);
lo -= pad; hi += pad;
function sx(games) { return m.l + iw * (games / xMax); }
function sy(value) { return m.t + ih * (1 - (value - lo) / (hi - lo)); }
this.geo = { W: W, H: H, iw: iw, ih: ih, xMax: xMax, sx: sx, sy: sy };
var el = this.svg;
el.textContent = '';
el.setAttribute('viewBox', '0 0 ' + W + ' ' + H);
el.setAttribute('width', W);
el.setAttribute('height', H);
svg('rect', { 'class': 'sch-bg', x: m.l, y: m.t, width: iw, height: ih }, el);
// Horizontal grid, with the zero line emphasised
[hi, (hi + lo) / 2, lo].forEach(function (value) {
var y = sy(value);
svg('line', { 'class': 'sch-grid', x1: m.l, x2: m.l + iw, y1: y, y2: y }, el);
svg('text', { 'class': 'sch-tick', x: m.l - 8, y: y, dy: '0.32em', 'text-anchor': 'end' }, el).textContent = percent(value);
});
svg('line', { 'class': 'sch-zero', x1: m.l, x2: m.l + iw, y1: sy(0), y2: sy(0) }, el);
svg('text', { 'class': 'sch-tick', x: m.l - 8, y: sy(0), dy: '0.32em', 'text-anchor': 'end' }, el).textContent = '0';
// Games axis
[[0, 'start', m.l], [xMax / 2, 'middle', m.l + iw / 2], [xMax, 'end', m.l + iw]].forEach(function (tick) {
var label = svg('text', { 'class': 'sch-tick', x: tick[2], y: H - 5, 'text-anchor': tick[1] }, el);
label.textContent = tick[0] === 0 ? '0 games' : commas(tick[0]);
});
// Lines: the quiet ones first, so the highlighted ones sit on top
function path(line) {
return line.map(function (v, k) {
return (k ? 'L' : 'M') + sx(points[k][0]).toFixed(1) + ' ' + sy(v).toFixed(1);
}).join('');
}
series.forEach(function (line, i) {
if (shown.indexOf(i) < 0)
svg('path', { 'class': 'sch-line is-quiet', d: path(line) }, el);
});
shown.forEach(function (i, order) {
svg('path', { 'class': 'sch-line is-on c' + (order % COLOURS), d: path(series[i]) }, el);
});
// Names at the end of each highlighted line, kept apart from one another
var labels = shown.map(function (i, order) {
var line = series[i];
return { index: i, order: order, y: sy(line[line.length - 1]) };
}).sort(function (a, b) { return a.y - b.y; });
for (var k = 1; k < labels.length; k++)
if (labels[k].y - labels[k - 1].y < 13)
labels[k].y = labels[k - 1].y + 13;
labels.forEach(function (label) {
var line = series[label.index];
svg('circle', { 'class': 'sch-dot c' + (label.order % COLOURS), cx: sx(points[points.length - 1][0]), cy: sy(line[line.length - 1]), r: 3.5 }, el);
svg('text', { 'class': 'sch-label c' + (label.order % COLOURS), x: m.l + iw + 10, y: label.y, dy: '0.32em' }, el).textContent = short(this.data.names[label.index]);
}, this);
// Marker
this.hoverLine = svg('line', { 'class': 'sch-hover-line', y1: m.t, y2: m.t + ih }, el);
this.hoverDots = shown.map(function (i, order) {
return svg('circle', { 'class': 'sch-dot c' + (order % COLOURS), r: 3.5, opacity: 0 }, el);
});
this.syncRows(shown);
if (this.active >= 0)
this.setActive(this.active);
};
/* ---------- Rows in the parameter list ---------- */
Chart.prototype.syncRows = function (shown) {
var self = this;
this.rows.forEach(function (row, i) {
if (!row)
return;
var order = shown.indexOf(i);
var on = order >= 0 && (self.pinned.length || self.hover >= 0 || false);
row.classList.toggle('is-shown', on);
row.classList.toggle('is-pinned', self.pinned.indexOf(i) >= 0);
if (on)
row.style.setProperty('--row-color', ['#5fa0ff', '#6ee7b7', '#f2c94c', '#c4a1ff', '#ff8f84'][order % COLOURS]);
else
row.style.removeProperty('--row-color');
});
};
/* ---------- Inspecting a point ---------- */
Chart.prototype.nearest = function (x) {
var g = this.geo, points = this.data.points;
var target = clamp((x - MARGIN.l) / g.iw, 0, 1) * g.xMax;
var best = 0, distance = Infinity;
for (var k = 0; k < points.length; k++) {
var d = Math.abs(points[k][0] - target);
if (d < distance) { distance = d; best = k; }
}
return best;
};
Chart.prototype.setActive = function (index) {
if (!this.geo)
return;
var g = this.geo, points = this.data.points, data = this.data;
if (index < 0) {
this.active = -1;
this.hoverLine.classList.remove('is-active');
this.hoverDots.forEach(function (dot) { dot.setAttribute('opacity', 0); });
this.tip.classList.remove('is-active');
return;
}
this.active = index = clamp(index, 0, points.length - 1);
var shown = this.shown();
var x = g.sx(points[index][0]);
this.hoverLine.setAttribute('x1', x);
this.hoverLine.setAttribute('x2', x);
this.hoverLine.classList.add('is-active');
this.hoverDots.forEach(function (dot, order) {
dot.setAttribute('cx', x);
dot.setAttribute('cy', g.sy(this.series[shown[order]][index]));
dot.setAttribute('opacity', 1);
}, this);
// Tooltip: the games played, then each highlighted parameter's value there
var tip = this.tip;
tip.textContent = '';
html('div', 't-games', tip).textContent = commas(points[index][0]) + ' games';
shown.forEach(function (i, order) {
var row = html('div', 't-row', tip);
var swatch = html('span', 't-swatch c' + (order % COLOURS), row);
swatch.style.background = ['#5fa0ff', '#6ee7b7', '#f2c94c', '#c4a1ff', '#ff8f84'][order % COLOURS];
html('span', 't-name', row).textContent = data.names[i];
html('span', 't-value', row).textContent = amount(points[index][1 + i], data.integer[i]);
html('span', 't-delta', row).textContent = percent(this.series[i][index]);
}, this);
tip.classList.add('is-active');
var left = clamp(x + 12, 0, g.W - tip.offsetWidth);
if (x + 12 + tip.offsetWidth > g.W - 4)
left = clamp(x - tip.offsetWidth - 12, 0, g.W - tip.offsetWidth);
tip.style.left = left + 'px';
tip.style.top = MARGIN.t + 'px';
};
/* ---------- Events ---------- */
Chart.prototype.redraw = function () {
this.render();
};
Chart.prototype.togglePin = function (index) {
var at = this.pinned.indexOf(index);
if (at >= 0)
this.pinned.splice(at, 1);
else if (this.pinned.length < MAX_ON)
this.pinned.push(index);
this.redraw();
};
Chart.prototype.follow = function (index) {
this.hover = index;
this.redraw();
};
Chart.prototype.bind = function () {
var self = this, plot = this.plot;
function move(event) {
if (!self.geo)
return;
var box = self.svg.getBoundingClientRect();
var x = (event.clientX - box.left) * (self.geo.W / (box.width || self.geo.W));
self.setActive(self.nearest(x));
}
plot.addEventListener('pointerenter', move);
plot.addEventListener('pointermove', move);
plot.addEventListener('pointerdown', move);
plot.addEventListener('pointerleave', function (event) {
if (event.pointerType === 'mouse')
self.setActive(-1);
});
plot.addEventListener('keydown', function (event) {
var last = self.data.points.length - 1;
var step = event.shiftKey ? 10 : 1;
var index = self.active;
if (event.key === 'ArrowLeft') index = index < 0 ? last : index - step;
else if (event.key === 'ArrowRight') index = index < 0 ? last : index + step;
else if (event.key === 'Home') index = 0;
else if (event.key === 'End') index = last;
else if (event.key === 'Escape') { self.setActive(-1); return; }
else return;
event.preventDefault();
self.setActive(clamp(index, 0, last));
});
plot.addEventListener('blur', function () { self.setActive(-1); });
// Names in the list
this.rows.forEach(function (row, i) {
if (!row)
return;
var button = row.querySelector('.spsa-name');
if (!button)
return;
row.addEventListener('mouseenter', function () { self.follow(i); });
row.addEventListener('mouseleave', function () { self.follow(-1); });
button.addEventListener('focus', function () { self.follow(i); });
button.addEventListener('blur', function () { self.follow(-1); });
button.addEventListener('click', function () {
self.togglePin(i);
button.setAttribute('aria-pressed', self.pinned.indexOf(i) >= 0 ? 'true' : 'false');
});
});
// Keep the chart as wide as its panel
if ('ResizeObserver' in window) {
var queued = false;
new ResizeObserver(function () {
if (queued) return;
queued = true;
window.requestAnimationFrame(function () {
queued = false;
if (Math.floor(plot.clientWidth) !== self.width)
self.render();
});
}).observe(plot);
} else {
window.addEventListener('resize', function () {
if (Math.floor(plot.clientWidth) !== self.width)
self.render();
});
}
};
/* ---------- Start ---------- */
function note(root, text) {
root.textContent = '';
html('p', 'spsa-note', root).textContent = text;
}
var chart = null; // the chart on the page, once there is something to draw
function mount(root, raw) {
var data;
try {
data = JSON.parse(raw);
} catch (error) {
chart = null;
return note(root, 'The history could not be read.');
}
// The notice about missing history sits beside the chart, and is redone with it
var parent = root.parentNode;
Array.prototype.slice.call(parent.children).forEach(function (child) {
if (child !== root && child.classList.contains('spsa-note'))
parent.removeChild(child);
});
if (!data.names.length || data.points.length < 2 || !data.games) {
chart = null;
return note(root, 'No games have been played yet. The chart appears with the first results.');
}
if (chart && chart.root === root && root.querySelector('.sch-plot')) {
// Live update: the same chart, with newer data
chart.update(data);
} else {
var items = document.querySelectorAll('#spsa-rows .spsa-row');
var rows = [];
for (var k = 0; k < items.length; k++)
rows[parseInt(items[k].getAttribute('data-index'), 10)] = items[k];
chart = new Chart(root, data, rows);
}
if (!data.recorded) {
var message = html('p', 'spsa-note');
message.setAttribute('data-live-skip', '');
message.textContent = 'History starts recording with the next result. Until then the chart shows only the start and the current values.';
parent.appendChild(message);
}
}
function start() {
var root = document.querySelector('.spsa-chart[data-chart]');
if (root)
mount(root, root.getAttribute('data-chart'));
}
/* Live updates ( live.js ) never touch the chart itself. When a fresh page
arrives with more history, the data is handed over here instead. */
document.addEventListener('live:patched', function (event) {
var root = document.querySelector('.spsa-chart[data-chart]');
var next = event.detail && event.detail.fresh && event.detail.fresh.querySelector('.spsa-chart[data-chart]');
if (!root || !next)
return;
var raw = next.getAttribute('data-chart');
if (raw === root.getAttribute('data-chart'))
return;
root.setAttribute('data-chart', raw);
mount(root, raw);
});
if (document.readyState === 'loading')
document.addEventListener('DOMContentLoaded', start);
else
start();
})();
+225
View File
@@ -0,0 +1,225 @@
/* SPSA parameter panel (Tune pages).
One row per parameter. The track is the parameter's allowed range, the hollow
tick is where tuning started, the dot is where it is now, and the bar between
them is how far it has travelled. A parameter pressed against its limit gets
a warm dot, because that usually means the range is too tight. */
.spsa-panel {
--spsa-line: var(--line, #2a303a);
--spsa-muted: var(--muted, var(--color-font3, #8b95a7));
--spsa-ink: var(--color-font1, #e6e9ef);
--spsa-fill: var(--accent, #4c8dff);
--spsa-limit: #e8955a;
--spsa-mono: var(--font-mono, 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);
}
/* ---------- Progress ---------- */
.spsa-summary {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: end;
gap: 8px 28px;
padding: 4px 0 18px;
}
.spsa-iter { display: flex; flex-direction: column; gap: 2px; }
.spsa-big {
font-family: var(--spsa-mono);
font-size: 30px;
font-weight: 600;
line-height: 1;
color: var(--spsa-ink);
font-variant-numeric: tabular-nums;
}
.spsa-of { font-size: 13px; color: var(--spsa-muted); }
.spsa-bar {
height: 6px;
margin-bottom: 7px;
background: var(--spsa-line);
border-radius: 3px;
overflow: hidden;
}
.spsa-bar > span {
display: block;
height: 100%;
background: var(--spsa-fill);
border-radius: 3px;
}
.spsa-facts { display: flex; gap: 22px; margin: 0; }
.spsa-facts div { text-align: right; }
.spsa-facts dt { font-size: 12.5px; color: var(--spsa-muted); }
.spsa-facts dd {
margin: 0;
font-family: var(--spsa-mono);
font-size: 15px;
color: var(--spsa-ink);
font-variant-numeric: tabular-nums;
}
/* ---------- Tools ---------- */
.spsa-tools {
display: flex;
flex-wrap: wrap;
gap: 10px;
padding: 12px 0;
border-top: 1px solid var(--spsa-line);
}
.spsa-tools input[type=search],
.spsa-tools select {
min-height: 36px;
padding: 0 10px;
color: var(--spsa-ink);
background: transparent;
border: 1px solid var(--spsa-line);
border-radius: 4px;
font: inherit;
font-size: 14px;
}
.spsa-tools input[type=search] { flex: 1 1 200px; max-width: 320px; }
.spsa-tools :focus-visible,
.spsa-row:focus-visible {
outline: 2px solid var(--spsa-fill);
outline-offset: 2px;
}
/* ---------- Rows ---------- */
.spsa-rows { list-style: none; margin: 0; padding: 0; }
.spsa-row {
display: grid;
grid-template-columns: minmax(8ch, 18ch) minmax(140px, 1fr) 10ch 9ch;
align-items: center;
gap: 4px 18px;
padding: 11px 0;
border-top: 1px solid var(--spsa-line);
}
.spsa-row[hidden] { display: none; }
.spsa-name {
font-family: var(--spsa-mono);
font-size: 13.5px;
color: var(--spsa-ink);
overflow-wrap: anywhere;
}
.spsa-track-wrap { min-width: 0; }
.spsa-track {
position: relative;
height: 4px;
margin: 8px 6px 6px;
background: var(--spsa-line);
border-radius: 2px;
}
.spsa-drift {
position: absolute;
top: 0;
bottom: 0;
background: var(--spsa-fill);
opacity: .55;
}
.spsa-start {
position: absolute;
top: -5px;
width: 2px;
height: 14px;
margin-left: -1px;
background: var(--spsa-muted);
}
.spsa-now {
position: absolute;
top: 50%;
width: 12px;
height: 12px;
margin: -6px 0 0 -6px;
background: var(--spsa-fill);
border: 2px solid var(--color2, #1a1d22);
border-radius: 50%;
box-sizing: border-box;
}
.spsa-row.at-bound .spsa-now { background: var(--spsa-limit); }
.spsa-scale {
display: flex;
justify-content: space-between;
font-family: var(--spsa-mono);
font-size: 11px;
color: var(--spsa-muted);
font-variant-numeric: tabular-nums;
}
.spsa-value {
font-family: var(--spsa-mono);
font-size: 15px;
font-weight: 600;
text-align: right;
color: var(--spsa-ink);
font-variant-numeric: tabular-nums;
}
.spsa-delta {
font-family: var(--spsa-mono);
font-size: 13px;
text-align: right;
color: var(--spsa-muted);
font-variant-numeric: tabular-nums;
}
.spsa-row.at-bound .spsa-delta { color: var(--spsa-limit); }
.spsa-empty { padding: 18px 0; color: var(--spsa-muted); }
.spsa-key {
display: flex;
flex-wrap: wrap;
gap: 6px 20px;
padding-top: 12px;
border-top: 1px solid var(--spsa-line);
font-size: 12.5px;
color: var(--spsa-muted);
}
.spsa-key i {
display: inline-block;
vertical-align: middle;
margin-right: 6px;
}
.spsa-key .k-start { width: 2px; height: 12px; background: var(--spsa-muted); }
.spsa-key .k-now { width: 10px; height: 10px; border-radius: 50%; background: var(--spsa-fill); }
.spsa-key .k-limit { width: 10px; height: 10px; border-radius: 50%; background: var(--spsa-limit); }
/* ---------- Narrow screens ---------- */
@media (max-width: 720px) {
.spsa-summary { grid-template-columns: 1fr; }
.spsa-facts div { text-align: left; }
.spsa-row {
grid-template-columns: 1fr auto auto;
gap: 6px 12px;
}
.spsa-name { grid-column: 1; }
.spsa-value { grid-column: 2; }
.spsa-delta { grid-column: 3; min-width: 7ch; }
.spsa-track-wrap { grid-column: 1 / -1; }
}
+110
View File
@@ -0,0 +1,110 @@
/* SPSA parameter panel: filter by name, sort by how far a parameter moved.
Live updates ( live.js ) never replace the rows, so the order, the filter,
the pinned lines and the hover all survive a refresh. The numbers in the
rows are brought up to date here, from the page that was just fetched. */
(function () {
// The parts of a row that only show numbers ( nothing in them carries a listener )
var CELLS = ['.spsa-track-wrap', '.spsa-value', '.spsa-delta'];
function flash(el) {
el.classList.remove('live-flash');
void el.offsetWidth;
el.classList.add('live-flash');
setTimeout(function () { el.classList.remove('live-flash'); }, 1500);
}
function init() {
var list = document.getElementById('spsa-rows');
var search = document.getElementById('spsa-filter');
var order = document.getElementById('spsa-sort');
var empty = document.getElementById('spsa-empty');
if (!list || !search || !order)
return;
var rows = Array.prototype.slice.call(list.children);
function apply(keepScroll) {
var term = search.value.trim().toLowerCase();
var shown = 0;
rows.sort(function (a, b) {
if (order.value === 'drift')
return parseFloat(b.dataset.drift) - parseFloat(a.dataset.drift);
if (order.value === 'name')
return a.dataset.name.localeCompare(b.dataset.name);
return parseInt(a.dataset.index, 10) - parseInt(b.dataset.index, 10);
});
rows.forEach(function (row) {
var match = row.dataset.name.indexOf(term) !== -1;
row.hidden = !match;
shown += match ? 1 : 0;
list.appendChild(row);
});
// A new order or filter starts at the top; a refresh leaves the reader where they are
if (!keepScroll)
list.scrollTop = 0;
if (empty)
empty.hidden = shown !== 0;
}
function refresh(fresh) {
var incoming = {};
Array.prototype.forEach.call(fresh.querySelectorAll('#spsa-rows .spsa-row'), function (row) {
incoming[row.getAttribute('data-index')] = row;
});
var moved = false;
rows.forEach(function (row) {
var next = incoming[row.getAttribute('data-index')];
if (!next)
return;
if (row.getAttribute('data-drift') !== next.getAttribute('data-drift')) {
row.setAttribute('data-drift', next.getAttribute('data-drift'));
moved = true;
}
row.classList.toggle('at-bound', next.classList.contains('at-bound'));
CELLS.forEach(function (selector) {
var current = row.querySelector(selector), latest = next.querySelector(selector);
if (!current || !latest || current.innerHTML === latest.innerHTML)
return;
current.innerHTML = latest.innerHTML;
if (selector !== '.spsa-track-wrap')
flash(current);
});
});
// Sorted by how far they moved: the order itself may have changed
if (moved && order.value === 'drift')
apply(true);
}
search.addEventListener('input', function () { apply(false); });
order.addEventListener('change', function () { apply(false); });
document.addEventListener('live:patched', function (event) {
if (event.detail && event.detail.fresh)
refresh(event.detail.fresh);
});
}
if (document.readyState === 'loading')
document.addEventListener('DOMContentLoaded', init);
else
init();
})();
+1006 -354
View File
File diff suppressed because it is too large. Load diff
+136
View File
@@ -0,0 +1,136 @@
/* ==========================================================================
OpenBench - small UI helpers (progressive enhancement only).
Nothing here changes what the site does: it highlights the current page in
the navigation, closes the mobile menu, shows a toast after copying text and
lets message banners be dismissed.
========================================================================== */
(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;
}
/* ---------- Navigation: mark the link for the current page ---------- */
function highlightNavigation() {
var here = normalise(window.location.pathname);
// The front page is served from both / and /index
if (here === '/')
here = '/index';
var best = null;
var bestLength = -1;
document.querySelectorAll('#sidebar a[href^="/"]').forEach(function (link) {
var target = normalise(new URL(link.getAttribute('href'), window.location.origin).pathname);
var matches = here === target || here.indexOf(target + '/') === 0;
if (matches && target.length > bestLength) {
best = link;
bestLength = target.length;
}
});
if (best) {
best.classList.add('active');
best.setAttribute('aria-current', 'page');
}
}
/* ---------- Mobile navigation ---------- */
function setSidebar(open) {
document.body.classList.toggle('sidebar-open', open);
var toggle = document.getElementById('sidebar-toggle');
if (toggle)
toggle.setAttribute('aria-expanded', String(open));
}
function initSidebar() {
var backdrop = document.getElementById('sidebar-backdrop');
if (backdrop)
backdrop.addEventListener('click', function () { setSidebar(false); });
document.addEventListener('keydown', function (event) {
if (event.key === 'Escape')
setSidebar(false);
});
document.querySelectorAll('#sidebar a').forEach(function (link) {
link.addEventListener('click', function () { setSidebar(false); });
});
}
/* ---------- Toast ---------- */
var toastTimer = null;
function toast(message) {
var element = document.getElementById('toast');
if (!element)
return;
element.textContent = message;
element.classList.add('show');
window.clearTimeout(toastTimer);
toastTimer = window.setTimeout(function () {
element.classList.remove('show');
}, 1800);
}
// Give copy_text() (see copy_text.js) some visible feedback
function wrapCopyText() {
if (typeof window.copy_text !== 'function' || window.copy_text.wrapped)
return;
var original = window.copy_text;
window.copy_text = function () {
var result = original.apply(this, arguments);
toast('Copied to clipboard');
return result;
};
window.copy_text.wrapped = true;
}
/* ---------- Dismissible banners ---------- */
function initBanners() {
document.addEventListener('click', function (event) {
var button = event.target.closest('.banner-close');
if (!button)
return;
var banner = button.closest('.banner');
if (banner)
banner.remove();
});
}
ready(function () {
highlightNavigation();
initSidebar();
initBanners();
wrapCopyText();
});
})();
+764
View File
@@ -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;
}
}
+149
View File
@@ -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();
});
})();
+124
View File
@@ -0,0 +1,124 @@
/* ==========================================================================
OpenBench - workload page: LLR history graph
(the panel itself, its label and the placeholder are styled in style.css)
========================================================================== */
#content .llr-history-loader {
width: 100%;
}
#content .llr-history-placeholder {
width: 100%;
height: 124px;
}
#content .llrg-plot {
position: relative;
cursor: crosshair;
touch-action: pan-y;
user-select: none;
-webkit-user-select: none;
}
#content .llrg-plot:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 4px;
}
#content .llrg-svg {
display: block;
width: 100%;
height: auto;
overflow: visible;
}
.llrg-bg {
fill: var(--color1);
stroke: var(--line-strong);
stroke-width: 1;
}
.llrg-grid {
stroke: rgba(197, 204, 217, 0.09);
stroke-width: 1;
shape-rendering: crispEdges;
}
.llrg-zero {
stroke: #6E7FA6;
stroke-width: 1;
opacity: 0.7;
}
.llrg-bound {
stroke: var(--bad);
stroke-width: 1;
stroke-dasharray: 4 3;
opacity: 0.8;
}
.llrg-tick {
fill: var(--muted);
font: 500 10px var(--font-mono);
}
.llrg-line {
fill: none;
stroke-width: 2;
stroke-linecap: round;
stroke-linejoin: round;
}
.llrg-line-pos { stroke: var(--ok); }
.llrg-line-neg { stroke: var(--bad); }
.llrg-hover-line {
stroke: var(--color-font1);
stroke-width: 1;
stroke-dasharray: 2 2;
opacity: 0;
}
.llrg-hover-dot {
fill: var(--color-font1);
stroke-width: 1.5;
opacity: 0;
}
.llrg-hover-line.active,
.llrg-hover-dot.active {
opacity: 0.85;
}
.llrg-hover-dot.llrg-pos { stroke: var(--ok); }
.llrg-hover-dot.llrg-neg { stroke: var(--bad); }
#content .llrg-tip {
position: absolute;
left: 0;
top: 0;
z-index: 1;
padding: 0.2rem 0.5rem 0.18rem;
background-color: rgba(11, 14, 20, 0.96);
border: 1px solid var(--line-strong);
border-radius: var(--radius);
color: var(--color-font1);
font-family: var(--font-mono);
font-size: 0.72rem;
white-space: nowrap;
pointer-events: none;
opacity: 0;
transform: translateY(2px);
transition: opacity 0.12s ease, transform 0.12s ease;
}
#content .llrg-tip.active {
opacity: 1;
transform: translateY(0);
}
@media (prefers-reduced-motion: reduce) {
#content .llrg-tip {
transition: none;
}
}
+171 -3
View File
@@ -22,6 +22,7 @@ import html
import json import json
import re, django import re, django
import OpenBench.config, OpenBench.utils, OpenBench.stats, OpenBench.models import OpenBench.config, OpenBench.utils, OpenBench.stats, OpenBench.models
import OpenBench.git_hosts
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
@@ -53,14 +54,17 @@ def gitDiffLink(test):
if test.dev_engine in engines and engines[test.dev_engine]['private']: if test.dev_engine in engines and engines[test.dev_engine]['private']:
repo = OpenBench.config.OPENBENCH_CONFIG['engines'][test.dev_engine]['source'] repo = OpenBench.config.OPENBENCH_CONFIG['engines'][test.dev_engine]['source']
elif OpenBench.git_hosts.is_gitea(test.dev_repo):
repo = test.dev_repo # Gitea sources point at this server's /giteaSource/
else: else:
repo = OpenBench.utils.path_join(*test.dev.source.split('/')[:-2]) repo = OpenBench.utils.path_join(*test.dev.source.split('/')[:-2])
if test.test_mode == 'SPSA': if test.test_mode == 'SPSA':
if OpenBench.git_hosts.is_gitea(repo):
return OpenBench.utils.path_join(repo, 'commit', test.dev.sha)
return OpenBench.utils.path_join(repo, 'compare', test.dev.sha[:8]) return OpenBench.utils.path_join(repo, 'compare', test.dev.sha[:8])
return OpenBench.utils.path_join(repo, 'compare', return OpenBench.git_hosts.compare_url(repo, test.base.sha[:8], test.dev.sha[:8])
'{0}..{1}'.format( test.base.sha[:8], test.dev.sha[:8]))
def shortStatBlock(test): def shortStatBlock(test):
@@ -204,7 +208,7 @@ def machine_name(machine_id):
return machine.info['machine_name'] return machine.info['machine_name']
except: return 'None' except: return 'None'
def llr_history_graph(test, width=320, height=112): def _llr_history_graph_static(test, width=320, height=112):
if test.test_mode != 'SPRT': if test.test_mode != 'SPRT':
return '' return ''
@@ -407,6 +411,36 @@ def llr_history_graph(test, width=320, height=112):
return mark_safe(svg) return mark_safe(svg)
def llr_history_graph(test):
"""Data for the LLR history chart, which is drawn in the browser by llr_history.js"""
import html as _html
import json as _json
from django.utils.safestring import mark_safe as _mark_safe
if test.test_mode != 'SPRT':
return ''
history = [list(point) for point in OpenBench.utils.get_llr_history(test)]
# The line starts at the origin, and ends on the current state of the test
if not history or history[0][0] > 0:
history.insert(0, [0, 0.0, False])
if history[-1][0] != test.games or history[-1][1] != test.currentllr:
history.append([test.games, test.currentllr, False])
data = {
'history' : [[int(p[0]), round(float(p[1]), 4), bool(p[2]) if len(p) > 2 else False] for p in history],
'lower' : float(test.lowerllr),
'upper' : float(test.upperllr),
'current' : float(test.currentllr),
'games' : int(test.games),
'finished' : bool(test.finished),
}
payload = _html.escape(_json.dumps(data, separators=(',', ':')), quote=True)
return _mark_safe('<div class="llr-chart" data-chart="%s"></div>' % payload)
register = django.template.Library() register = django.template.Library()
register.filter('oneDigitPrecision', oneDigitPrecision) register.filter('oneDigitPrecision', oneDigitPrecision)
register.filter('twoDigitPrecision', twoDigitPrecision) register.filter('twoDigitPrecision', twoDigitPrecision)
@@ -514,6 +548,138 @@ def spsa_optimal_values(workload):
return '\n'.join(lines) return '\n'.join(lines)
def spsa_param_panel(workload):
# Data for the visual parameter panel on a Tune's page. Positions are
# percentages along each parameter's [min, max] range, and every string is
# formatted here so a locale can never turn a decimal point into a comma.
spsa = workload.spsa
pairs = max(spsa['pairs_per'] * 2, 1)
total = int(spsa['iterations'])
complete = int(workload.games / pairs)
iteration = 1 + workload.games / pairs
c_compression = iteration ** spsa['Gamma']
r_compression = (spsa['A'] + iteration) ** spsa['Alpha']
def place(value, lo, span):
return max(0.0, min(100.0, (value - lo) / span * 100.0))
# Maintain the original order, if there was one
keys = sorted(
spsa['parameters'].keys(),
key=lambda x: spsa['parameters'][x].get('index', -1)
)
entries = []
for name in keys:
param = spsa['parameters'][name]
is_float = bool(param['float'])
lo, hi = float(param['min']), float(param['max'])
span = (hi - lo) or 1.0
value, start = float(param['value']), float(param['start'])
now_pos = place(value, lo, span)
start_pos = place(start, lo, span)
c = max(param['c'] / c_compression, 0.00 if is_float else 0.50)
r = param['a'] / r_compression / c ** 2
fmt = '%.4f' if is_float else '%d'
dfmt = '%+.4f' if is_float else '%+d'
shown_value = value if is_float else round(value)
shown_start = start if is_float else round(start)
bound = ''
if now_pos <= 1.0: bound = 'min'
elif now_pos >= 99.0: bound = 'max'
entries.append({
'name' : name,
'value' : fmt % shown_value,
'start' : fmt % shown_start,
'min' : fmt % lo,
'max' : fmt % hi,
'delta' : dfmt % (shown_value - shown_start),
'moved' : shown_value != shown_start,
'bound' : bound,
'now' : '%.2f' % now_pos,
'from' : '%.2f' % start_pos,
'left' : '%.2f' % min(now_pos, start_pos),
'width' : '%.2f' % abs(now_pos - start_pos),
'drift' : '%.3f' % (abs(value - start) / span * 100.0),
'c' : '%.4f' % c,
'r' : '%.4f' % r,
})
return {
'params' : entries,
'count' : len(entries),
'moved' : sum(1 for e in entries if e['moved']),
'complete' : complete,
'iterations' : total,
'pct' : '%.1f' % (max(0.0, min(100.0, complete / total * 100.0)) if total else 0.0),
'games' : int(workload.games),
}
def spsa_history_chart(workload):
# Data for the Tune page's history chart, drawn in the browser by spsa_chart.js
# Rows are [ games, value, value, ... ], in the same order as the parameter panel
spsa = workload.spsa
keys = sorted(spsa['parameters'].keys(), key=lambda x: spsa['parameters'][x].get('index', -1))
params = [spsa['parameters'][key] for key in keys]
start = [float(p['start']) for p in params]
current = [float(p['value']) for p in params]
games = int(workload.games)
stored = OpenBench.utils.load_spsa_history(workload)
rows = []
if stored:
column = { name : index for index, name in enumerate(stored.get('names', [])) }
for point in stored.get('points', []):
row = [int(point[0])]
for key, fallback in zip(keys, start):
index = column.get(key)
row.append(point[1 + index] if index is not None and 1 + index < len(point) else fallback)
rows.append(row)
# The line starts at the start values, and ends on the current state
if not rows or rows[0][0] != 0:
rows.insert(0, [0] + start)
if rows[-1][0] == games and games > 0:
rows[-1] = [games] + current
elif rows[-1][0] < games:
rows.append([games] + current)
# Never send more than a few hundred points to the browser
limit = 200
if len(rows) > limit:
step = (len(rows) - 1) / float(limit - 1)
keep = sorted(set(int(round(i * step)) for i in range(limit)) | { len(rows) - 1 })
rows = [rows[i] for i in keep]
data = {
'names' : keys,
'start' : start,
'min' : [float(p['min']) for p in params],
'max' : [float(p['max']) for p in params],
'integer' : [not p['float'] for p in params],
'points' : [[row[0]] + [round(float(v), 4) for v in row[1:]] for row in rows],
'recorded' : bool(stored),
'games' : games,
}
payload = html.escape(json.dumps(data, separators=(',', ':')), quote=True)
return mark_safe('<div class="spsa-chart" data-chart="%s"></div>' % payload)
def book_download_link(workload): def book_download_link(workload):
if workload.book_name in OpenBench.config.OPENBENCH_CONFIG['books']: if workload.book_name in OpenBench.config.OPENBENCH_CONFIG['books']:
return OpenBench.config.OPENBENCH_CONFIG['books'][workload.book_name]['source'] return OpenBench.config.OPENBENCH_CONFIG['books'][workload.book_name]['source']
@@ -579,6 +745,8 @@ register.filter('spsa_param_digest', spsa_param_digest)
register.filter('spsa_param_digest_headers', spsa_param_digest_headers) register.filter('spsa_param_digest_headers', spsa_param_digest_headers)
register.filter('spsa_original_input', spsa_original_input) register.filter('spsa_original_input', spsa_original_input)
register.filter('spsa_optimal_values', spsa_optimal_values) register.filter('spsa_optimal_values', spsa_optimal_values)
register.filter('spsa_param_panel', spsa_param_panel)
register.filter('spsa_history_chart', spsa_history_chart)
register.filter('book_download_link', book_download_link) register.filter('book_download_link', book_download_link)
register.filter('network_download_link', network_download_link) register.filter('network_download_link', network_download_link)
+106
View File
@@ -0,0 +1,106 @@
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# 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'
info = { 'pct' : int(max(0.0, min(1.0, fraction)) * 100), 'tone' : tone }
# Data for the LLR gauge: the track runs lower -> upper bound, the fill
# grows from LLR = 0 towards the current LLR. Strings are formatted here
# so locale settings can never turn a decimal point into a comma.
if lower < 0 < upper:
span = upper - lower
pos = max(0.0, min(1.0, (current - lower) / span)) * 100
zero = (0.0 - lower) / span * 100
info.update({
'gauge' : True,
'llr' : '%.2f' % current,
'lower' : '%.2f' % lower,
'upper' : '%.2f' % upper,
'zero' : '%.1f' % zero,
'left' : '%.1f' % min(pos, zero),
'width' : '%.1f' % abs(pos - zero),
})
return info
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)
+381
View File
@@ -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<score>[+-]?(?:M\d+|\d+(?:\.\d+)?))/(?P<depth>\d+)(?:\s+(?P<time>\d+(?:\.\d+)?)s)?')
RESULT_TOKENS = ('1-0', '0-1', '1/2-1/2', '*')
def _eval_tone(score):
if score.startswith('-'):
return 'neg'
if score.lstrip('+') in ('0', '0.0', '0.00'):
return ''
return 'pos'
def parse_pgn(text):
# Split the first game into its headers, and its movetext
headers, body, reading_headers = [], [], True
for raw in text.splitlines():
line = raw.strip()
if body and line.startswith('[Event '):
break # A second game, which we do not show
if reading_headers:
match = HEADER_RE.match(line)
if match:
headers.append((match.group(1), match.group(2)))
continue
if not line:
reading_headers = not headers
continue
reading_headers = False
if line:
body.append(line)
header_map = dict(headers)
# Games from a FEN, or from a Black to move book entry, number differently
start_black, first_number = False, 1
fen = header_map.get('FEN', '')
if fen:
fields = fen.split()
start_black = len(fields) >= 2 and fields[1] == 'b'
if len(fields) >= 6 and fields[5].isdigit():
first_number = int(fields[5])
moves, final_note = [], ''
for token in TOKEN_RE.findall(' '.join(body)):
if token.startswith('{'):
comment = token[1:-1].strip()
if not comment or not moves:
continue
match = EVAL_RE.match(comment)
if match:
score = match.group('score')
if score[0] not in '+-':
score = '+' + score
moves[-1]['eval' ] = score
moves[-1]['tone' ] = _eval_tone(score)
moves[-1]['depth'] = match.group('depth')
moves[-1]['time' ] = (match.group('time') or '') and match.group('time') + 's'
elif comment.lower() == 'book':
moves[-1]['eval'] = 'book'
else:
final_note = comment
if not moves[-1]['note']:
moves[-1]['note'] = comment
continue
# Variations, NAGs, move numbers, and results are not moves
if token.startswith(('(', '$')) or token in RESULT_TOKENS or NUMBER_RE.match(token):
continue
index = len(moves) + (1 if start_black else 0)
moves.append({
'ply' : len(moves),
'num' : first_number + index // 2,
'color' : 'w' if index % 2 == 0 else 'b',
'san' : token,
'eval' : '',
'tone' : '',
'depth' : '',
'time' : '',
'note' : '',
'final' : False,
})
if moves:
moves[-1]['final'] = True
# One row per full move, for the move list
rows = []
for move in moves:
if not rows or rows[-1]['num'] != move['num']:
rows.append({ 'num' : move['num'], 'w' : None, 'b' : None })
rows[-1][move['color']] = move
return {
'white' : header_map.get('White', '?'),
'black' : header_map.get('Black', '?'),
'result' : header_map.get('Result', '*'),
'termination' : header_map.get('Termination', ''),
'time_control' : header_map.get('TimeControl', ''),
'date' : header_map.get('Date', ''),
'duration' : header_map.get('GameDuration', ''),
'fen' : fen,
'start_fen' : fen or START_FEN,
'variant' : header_map.get('Variant', ''),
'chess960' : 'fischer' in header_map.get('Variant', '').lower() or '960' in header_map.get('Variant', ''),
'headers' : headers,
'rows' : rows,
'moves' : moves,
'ply_count' : len(moves),
'final_note' : final_note,
}
# Plain text logs ( compiler output, bench failures, ... )
MAX_LOG_LINES = 5000
CLEAN_RE = re.compile(r'\b0\s+(errors?|warnings?)\b', re.IGNORECASE)
ERROR_RE = re.compile(
r'\b(errors?|fatal|failed|failure|undefined reference|segmentation fault|traceback|exception|illegal move)\b',
re.IGNORECASE)
WARN_RE = re.compile(r'\b(warnings?|deprecated|stalled|timed? ?out|disconnect\w*)\b', re.IGNORECASE)
def classify_log_line(text):
if CLEAN_RE.search(text):
return 'info'
if ERROR_RE.search(text):
return 'bad'
if WARN_RE.search(text):
return 'warn'
return 'info'
def parse_log(content):
lines = content.splitlines()
total = len(lines)
skipped = max(0, total - MAX_LOG_LINES) # Errors are usually at the end
lines = lines[skipped:]
parsed, errors, warnings = [], 0, 0
for number, text in enumerate(lines, start=skipped + 1):
level = classify_log_line(text)
errors += level == 'bad'
warnings += level == 'warn'
parsed.append({ 'n' : number, 'text' : text, 'level' : level })
return {
'lines' : parsed,
'total' : total,
'errors' : errors,
'warnings' : warnings,
'skipped' : skipped,
}
def event_context(event, content):
kind = 'empty'
if content and content.strip():
kind = 'pgn' if PGN_PROBE_RE.search(content) else 'log'
context = {
'event' : event,
'content' : content,
'kind' : kind,
'tone' : event_tone(event.summary),
'back_url' : '/errors/' if event.machine_id else '/events/',
'back_label' : 'Errors' if event.machine_id else 'Events',
'game' : None,
'moves_json' : [],
'game_json' : None,
'log' : None,
'download_name' : 'event%d.%s' % (event.id, 'pgn' if kind == 'pgn' else 'log'),
}
try:
if kind == 'pgn':
context['game'] = parse_pgn(content)
context['moves_json'] = context['game']['moves']
context['game_json'] = {
'startFen' : context['game']['start_fen'],
'chess960' : context['game']['chess960'],
'white' : context['game']['white'],
'black' : context['game']['black'],
'note' : context['game']['final_note'] or context['game']['termination'],
}
elif kind == 'log':
context['log'] = parse_log(content)
except Exception:
# A strange log should never break the page. Fall back to plain text
context['kind'] = 'log'
context['game'] = None
context['moves_json'] = []
context['game_json'] = None
context['log'] = parse_log(content)
return context
+7 -1
View File
@@ -18,10 +18,14 @@
# # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import django.urls, OpenBench.views import django.urls, OpenBench.views, OpenBench.seo
urlpatterns = [ urlpatterns = [
# Files for search engines
django.urls.path(r'robots.txt', OpenBench.seo.robots_txt),
django.urls.path(r'sitemap.xml', OpenBench.seo.sitemap_xml),
# Links for account management # Links for account management
django.urls.path(r'register/', OpenBench.views.register), django.urls.path(r'register/', OpenBench.views.register),
django.urls.path(r'login/', OpenBench.views.login), django.urls.path(r'login/', OpenBench.views.login),
@@ -79,6 +83,7 @@ urlpatterns = [
django.urls.path(r'clientWorkerInfo/', OpenBench.views.client_worker_info), django.urls.path(r'clientWorkerInfo/', OpenBench.views.client_worker_info),
django.urls.path(r'clientGetWorkload/', OpenBench.views.client_get_workload), django.urls.path(r'clientGetWorkload/', OpenBench.views.client_get_workload),
django.urls.path(r'clientGetNetwork/<str:engine>/<str:name>/', OpenBench.views.client_get_network), django.urls.path(r'clientGetNetwork/<str:engine>/<str:name>/', OpenBench.views.client_get_network),
django.urls.path(r'giteaSource/', OpenBench.views.gitea_source),
django.urls.path(r'clientBenchError/', OpenBench.views.client_bench_error), django.urls.path(r'clientBenchError/', OpenBench.views.client_bench_error),
django.urls.path(r'clientSubmitNPS/', OpenBench.views.client_submit_nps), django.urls.path(r'clientSubmitNPS/', OpenBench.views.client_submit_nps),
django.urls.path(r'clientSubmitError/', OpenBench.views.client_submit_error), django.urls.path(r'clientSubmitError/', OpenBench.views.client_submit_error),
@@ -94,6 +99,7 @@ urlpatterns = [
django.urls.path(r'api/buildinfo/', OpenBench.views.api_build_info), django.urls.path(r'api/buildinfo/', OpenBench.views.api_build_info),
django.urls.path(r'api/pgns/<int:pgn_id>/', OpenBench.views.api_pgns), django.urls.path(r'api/pgns/<int:pgn_id>/', OpenBench.views.api_pgns),
django.urls.path(r'api/test/<int:id>/llr-history/', OpenBench.views.test_llr_history), django.urls.path(r'api/test/<int:id>/llr-history/', OpenBench.views.test_llr_history),
django.urls.path(r'api/quick-search/', OpenBench.views.api_quick_search),
# Redirect anything else to the Index # Redirect anything else to the Index
django.urls.path(r'', OpenBench.views.index), django.urls.path(r'', OpenBench.views.index),
+67 -8
View File
@@ -286,6 +286,61 @@ def get_llr_history(test, max_points=LLR_HISTORY_SAMPLE_POINTS):
return compact_history return compact_history
SPSA_HISTORY_MAX_POINTS = 1500
def spsa_history_path(test_id):
return os.path.join(MEDIA_ROOT, 'spsa_history', '%d.json' % (test_id))
def spsa_param_names(test):
# Maintain the original order, if there was one
return sorted(
test.spsa['parameters'].keys(),
key=lambda x: test.spsa['parameters'][x].get('index', -1)
)
def load_spsa_history(test):
# { 'names' : [ ... ], 'points' : [ [ games, value, value, ... ], ... ] }
path = spsa_history_path(test.id)
if not os.path.exists(path):
return None
try:
with open(path) as fin:
history = json.load(fin)
return history if history.get('points') else None
except Exception:
return None
def record_spsa_history(test):
names = spsa_param_names(test)
history = load_spsa_history(test) or {}
# Parameters were renamed, or reordered. Start over
if history.get('names') != names:
history = { 'names' : names, 'points' : [] }
point = [int(test.games)]
point += [round(float(test.spsa['parameters'][name]['value']), 4) for name in names]
points = history['points']
if points and points[-1][0] == point[0]:
points[-1] = point
else:
points.append(point)
# Keep the file bounded: drop every other point, but always keep the latest
if len(points) > SPSA_HISTORY_MAX_POINTS:
last = points[-1]
points = points[::2]
if points[-1] is not last:
points.append(last)
history['points'] = points
write_json_file(spsa_history_path(test.id), history)
def extract_option(options, option): def extract_option(options, option):
match = re.search(r'(?<={0}=")[^"]*'.format(option), options) match = re.search(r'(?<={0}=")[^"]*'.format(option), options)
@@ -381,16 +436,12 @@ def branch_is_out_of_date(test):
if test.dev_engine != test.base_engine: if test.dev_engine != test.base_engine:
return False return False
# Format the request to the Github endpoint import OpenBench.git_hosts
base = 'https://api.github.com/repos/'
base = test.dev_repo.replace('github.com', 'api.github.com/repos')
url = path_join(base, 'compare', '%s...%s' % (test.dev.sha, test.base.sha))
try: try:
# Out of date if ahead_by is non-zero # Out of date if the base has commits that the dev branch lacks
headers = read_git_credentials(test.dev_engine) headers = OpenBench.git_hosts.api_headers(test.dev_engine, test.dev_repo)
data = requests.get(url, headers=headers).json() return OpenBench.git_hosts.commits_ahead(test.dev_repo, test.dev.sha, test.base.sha, headers) > 0
return data.get('ahead_by', 0) > 0
except: except:
# If something went wrong, just ignore it # If something went wrong, just ignore it
@@ -575,6 +626,7 @@ def update_test(request, machine):
test = Test.objects.select_for_update().get(id=test_id) test = Test.objects.select_for_update().get(id=test_id)
should_record_llr = False should_record_llr = False
should_record_spsa = False
if test.finished or test.deleted: if test.finished or test.deleted:
return { 'stop' : True } return { 'stop' : True }
@@ -625,6 +677,7 @@ def update_test(request, machine):
param['value'] = max(param['min'], min(param['max'], x)) param['value'] = max(param['min'], min(param['max'], x))
test.finished = test.games >= 2 * test.spsa['pairs_per'] * test.spsa['iterations'] test.finished = test.games >= 2 * test.spsa['pairs_per'] * test.spsa['iterations']
should_record_spsa = True
elif test.test_mode == 'DATAGEN': elif test.test_mode == 'DATAGEN':
@@ -633,6 +686,12 @@ def update_test(request, machine):
test.save() test.save()
if should_record_spsa:
try:
record_spsa_history(test)
except Exception:
pass # History is a nicety, and must never fail a result upload
if should_record_llr: if should_record_llr:
record_llr_history(test) record_llr_history(test)
+80 -9
View File
@@ -25,7 +25,9 @@ import django.shortcuts
import django.contrib.auth import django.contrib.auth
import OpenBench.config import OpenBench.config
import OpenBench.git_hosts
import OpenBench.utils import OpenBench.utils
import OpenBench.uiutils
from OpenBench.workloads.create_workload import create_workload from OpenBench.workloads.create_workload import create_workload
from OpenBench.workloads.get_workload import get_workload from OpenBench.workloads.get_workload import get_workload
@@ -231,7 +233,10 @@ def profile_config(request):
for (engine, current_repo) in profile.repos.items(): for (engine, current_repo) in profile.repos.items():
repo_name = request.POST.get('engine-repo-%s' % (engine), '').removesuffix('/') repo_name = request.POST.get('engine-repo-%s' % (engine), '').removesuffix('/')
repo = 'https://github.com/%s' % (repo_name) repo = repo_name if repo_name.startswith('https://') else 'https://github.com/%s' % (repo_name)
if repo_name and not OpenBench.git_hosts.is_valid_repo(repo):
return redirect(request, '/profile/', error='Repositories must be on Github or a configured Gitea server')
if repo != current_repo and repo_name: if repo != current_repo and repo_name:
changes += 'Updated Engine: %s to use %s\n' % (engine, repo) changes += 'Updated Engine: %s to use %s\n' % (engine, repo)
@@ -245,8 +250,8 @@ def profile_config(request):
if engine_name != 'None' and engine_repo: if engine_name != 'None' and engine_repo:
if not engine_repo.startswith('https://github.com/'): if not OpenBench.git_hosts.is_valid_repo(engine_repo):
return redirect(request, '/profile/', error='Repositories must be on Github') return redirect(request, '/profile/', error='Repositories must be on Github or a configured Gitea server')
if not profile.engine: if not profile.engine:
profile.engine = engine_name profile.engine = engine_name
@@ -417,16 +422,25 @@ def search(request):
def users(request): def users(request):
data = { 'profiles' : Profile.objects.select_related('user').order_by('-games', '-tests') } data = OpenBench.uiutils.users_context(request)
return render(request, 'users.html', data) return render(request, 'users.html', data)
def event(request, id): def event(request, id):
try: log_event = LogEvent.objects.filter(id=id).first()
with open(os.path.join(MEDIA_ROOT, LogEvent.objects.get(id=id).log_file)) as fin: if log_event is None:
return render(request, 'event.html', { 'content' : fin.read() }) return redirect(request, '/errors/', error='No such event exists')
except:
return redirect(request, '/index/', error='No logs for event exist') # Not every event has a log attached ( admin actions, some bench failures )
content = ''
if log_event.log_file:
try:
with open(os.path.join(MEDIA_ROOT, log_event.log_file), encoding='utf-8', errors='replace') as fin:
content = fin.read()
except OSError:
content = ''
return render(request, 'event.html', OpenBench.uiutils.event_context(log_event, content))
def events_actions(request, page=1): def events_actions(request, page=1):
@@ -575,6 +589,41 @@ def test_llr_history(request, id):
return HttpResponse(str(llr_history_graph(test)), content_type='text/plain; charset=utf-8') return HttpResponse(str(llr_history_graph(test)), content_type='text/plain; charset=utf-8')
def api_quick_search(request):
## Feeds the Ctrl+K palette: up to eight workloads that match a branch name,
## an author, an engine, or a workload id, newest first.
if OPENBENCH_CONFIG['require_login_to_view'] and not request.user.is_authenticated:
return JsonResponse({ 'tests' : [] }, status=403)
from OpenBench.templatetags.mytags import prettyName
from OpenBench.templatetags.uitags import test_status
query = request.GET.get('q', '').strip().lstrip('#')[:64]
if not query:
return JsonResponse({ 'tests' : [] })
match = Q(dev__name__icontains=query) | Q(author__icontains=query) | Q(dev_engine__icontains=query)
if query.isdigit() and len(query) <= 9:
match |= Q(id=int(query))
found = list(Test.objects.select_related('dev').filter(match).exclude(deleted=True).order_by('-id')[:8])
# An exact workload id is always the first hit
if query.isdigit():
found.sort(key=lambda test: str(test.id) != query)
return JsonResponse({ 'tests' : [{
'id' : test.id,
'name' : prettyName(test.dev.name),
'author' : test.author.capitalize(),
'engine' : test.dev_engine,
'tc' : test.dev_time_control,
'status' : test_status(test),
'url' : '/%s/%d/' % ('tune' if test.test_mode == 'SPSA' else 'test', test.id),
} for test in found] })
def create_test(request): def create_test(request):
return create_workload(request, 'TEST') return create_workload(request, 'TEST')
@@ -757,6 +806,28 @@ def client_worker_info(request):
# Pass back the Machine Id, and Secret Token for this session # Pass back the Machine Id, and Secret Token for this session
return JsonResponse({ 'machine_id' : machine.id, 'secret' : machine.secret }) return JsonResponse({ 'machine_id' : machine.id, 'secret' : machine.secret })
def gitea_source(request):
# Workers download sources with a plain GET. The link carries a signature
# made at test creation, so only repo/sha pairs this server handed out work.
repo = request.GET.get('repo', '')
sha = request.GET.get('sha' , '')
sig = request.GET.get('sig' , '')
if not OpenBench.git_hosts.verify_source_request(repo, sha, sig):
return django.http.HttpResponseForbidden('Invalid source link')
try:
upstream = OpenBench.git_hosts.open_gitea_archive(repo, sha)
except Exception:
import traceback; traceback.print_exc()
return HttpResponse('Unable to fetch the source archive', status=502)
owner, name = OpenBench.git_hosts.owner_and_name(repo)
response = django.http.StreamingHttpResponse(upstream.iter_content(chunk_size=1 << 16), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename="%s-%s.zip"' % (name, sha[:8])
return response
@csrf_exempt @csrf_exempt
def client_get_network(request, engine, name): def client_get_network(request, engine, name):
+34 -33
View File
@@ -42,6 +42,7 @@ import requests
import traceback import traceback
import OpenBench.config import OpenBench.config
import OpenBench.git_hosts
import OpenBench.utils import OpenBench.utils
from OpenBench.models import * from OpenBench.models import *
@@ -245,9 +246,10 @@ def verify_draw_adj(errors, request, field):
except: errors.append('Invalid Draw Adjudication Setting. Try "None"?') except: errors.append('Invalid Draw Adjudication Setting. Try "None"?')
def verify_github_repo(errors, request, field): def verify_github_repo(errors, request, field):
pattern = r'^https:\/\/github\.com\/[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+\/?$' try: assert OpenBench.git_hosts.is_valid_repo(request.POST[field])
try: assert re.match(pattern, request.POST[field]) except:
except: errors.append('Sources must be found on https://github.com/<User>/<Repo>') hosts = ', '.join('%s<User>/<Repo>' % (prefix) for prefix in OpenBench.git_hosts.repo_prefixes())
errors.append('Sources must be found on %s' % (hosts))
def verify_network(errors, request, field, field_name, engine_field): def verify_network(errors, request, field, field_name, engine_field):
try: try:
@@ -353,19 +355,26 @@ def collect_github_info(errors, request, field):
# Get branch name / commit sha / tag, and the API path for it # Get branch name / commit sha / tag, and the API path for it
branch = request.POST['{0}_branch'.format(field)] branch = request.POST['{0}_branch'.format(field)]
bysha = bool(re.search('^[0-9a-fA-F]{40}$', branch))
# All API requests will share this common path. Some engines are private. # All API requests will share this common path. Some engines are private.
base = request.POST['%s_repo' % (field)].replace('github.com', 'api.github.com/repos') repo = request.POST['%s_repo' % (field)]
base = OpenBench.git_hosts.api_base(repo)
engine = request.POST['%s_engine' % (field)] engine = request.POST['%s_engine' % (field)]
private = OpenBench.config.OPENBENCH_CONFIG['engines'][engine]['private'] private = OpenBench.config.OPENBENCH_CONFIG['engines'][engine]['private']
gitea = OpenBench.git_hosts.is_gitea(repo)
headers = {} headers = {}
## Step 1: Verify the target of the API requests ## Step 1: Verify the target of the API requests
## [A] We will not attempt to reach any site other than api.github.com ## [A] We will not attempt to reach any site other than api.github.com,
## or a Gitea server listed under "gitea_hosts" in the config
## [B] Private engines may only use their main repo for sources of tests ## [B] Private engines may only use their main repo for sources of tests
## [C] Determine which, if any, credentials we want to pass along ## [C] Determine which, if any, credentials we want to pass along
# Private engines rely on Github Actions artifacts, which Gitea does not offer
if private and gitea:
errors.append('Private engines must be hosted on Github')
return (None, None)
# Private engines must have a token stored in credentials.enginename # Private engines must have a token stored in credentials.enginename
if private and not (headers := OpenBench.utils.read_git_credentials(engine)): if private and not (headers := OpenBench.utils.read_git_credentials(engine)):
errors.append('Server does not have access tokens for this engine') errors.append('Server does not have access tokens for this engine')
@@ -377,59 +386,51 @@ def collect_github_info(errors, request, field):
return (None, None) return (None, None)
# Avoid leaking our credentials to other websites # Avoid leaking our credentials to other websites
if not base.startswith('https://api.github.com/'): if not OpenBench.git_hosts.is_valid_repo(repo):
errors.append('OpenBench may only reach Github\'s API') errors.append('OpenBench may only reach Github\'s API or a configured Gitea server')
return (None, None) return (None, None)
## Step 2: Connect to the Github API for the given Branch or Commit SHA. # Gitea servers get their own token if there is one, and nothing else.
# Without a token the repository has to be readable anonymously.
if gitea:
headers = OpenBench.git_hosts.gitea_headers()
## Step 2: Connect to the Github or Gitea API for the given Branch or Commit SHA.
## [A] We will attempt to parse the most recent commit message for a ## [A] We will attempt to parse the most recent commit message for a
## bench, unless one was supplied. ## bench, unless one was supplied.
## [B] We will translate any branch name into a commit SHA for later use, ## [B] We will translate any branch name into a commit SHA for later use,
## so we may compare branches and generate diff URLs ## so we may compare branches and generate diff URLs
## [C] If the engine is public, we will construct the URL to download the ## [C] If the engine is public, we will construct the URL to download the
## source code from Github into a .zip file. ## source code into a .zip file. Gitea sources go through this server.
## [D] If the engine is private, we will carry onto Step 3. ## [D] If the engine is private, we will carry onto Step 3.
try: # Fetch data from the Github API try: # Resolve the branch, tag, or commit sha
commit = OpenBench.git_hosts.fetch_commit(repo, branch, headers)
# Lookup branch or commit sha, but will fail for tags assert commit['message'] is not None and commit['sha']
url = OpenBench.utils.path_join(base, 'commits' if bysha else 'branches', branch) assert private or commit['tree']
data = requests.get(url, headers=headers).json()
# Check to see if the branch name was actually a tag name
if not bysha and 'commit' not in data:
url = OpenBench.utils.path_join(base, 'commits', branch)
data = requests.get(url, headers=headers).json()
# Actual branches have to go one layer deeper
elif not bysha: data = data['commit']
# Check that all the data we need going forward is present
assert 'message' in data['commit'] and 'sha' in data
assert private or 'sha' in data['commit']['tree']
except: # Unable to find for whatever reason except: # Unable to find for whatever reason
traceback.print_exc() traceback.print_exc()
errors.append('%s could not be found' % (branch or 'Branch')) hint = ' (no Gitea token on the server, so the repository must be public)' if gitea and not headers else ''
errors.append('%s could not be found%s' % (branch or 'Branch', hint))
return (None, None) return (None, None)
# Extract the bench from the web form, or from the commit message # Extract the bench from the web form, or from the commit message
if not (bench := determine_bench(request, field, data['commit']['message'])): if not (bench := determine_bench(request, field, commit['message'])):
errors.append('Unable to parse a Bench for %s' % (branch)) errors.append('Unable to parse a Bench for %s' % (branch))
return (None, None) return (None, None)
# Public Engines: Construct the .zip download and return everything # Public Engines: Construct the .zip download and return everything
if not private: if not private:
treeurl = data['commit']['tree']['sha'] + '.zip' source = OpenBench.git_hosts.source_url(request, repo, commit)
source = OpenBench.utils.path_join(request.POST['%s_repo' % (field)], 'archive', treeurl) return (source, branch, commit['sha'], bench), True
return (source, branch, data['sha'], bench), True
## Step 3: Construct the URL for the API request to list all Artifacts ## Step 3: Construct the URL for the API request to list all Artifacts
## [A] OpenBench artifacts are always run via a file named openbench.yml ## [A] OpenBench artifacts are always run via a file named openbench.yml
## [B] These should contain combinations for windows/linux, avx2/avx512, popcnt/pext ## [B] These should contain combinations for windows/linux, avx2/avx512, popcnt/pext
## [C] If those artifacts are not found, we flag the test as awaiting, and try later. ## [C] If those artifacts are not found, we flag the test as awaiting, and try later.
url, has_all = fetch_artifact_url(base, engine, headers, data['sha']) url, has_all = fetch_artifact_url(base, engine, headers, commit['sha'])
return (url, branch, data['sha'], bench), has_all return (url, branch, data['sha'], bench), has_all
def requests_illegal_fork(request, field): def requests_illegal_fork(request, field):
+15 -2
View File
@@ -20,9 +20,9 @@ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: keep the secret key used in production secret!
# SECURITY WARNING: don't run with debug turned on in production! # SECURITY WARNING: don't run with debug turned on in production!
SECRET_KEY = '@!zw2l8til1(0eb_nk+1w!(n78gqm&u)s)_v7#k6iseia@g9q0' SECRET_KEY = '@!zw2l8til1(0eb_nk+1w!(n78gqm&u)s)_v7#k6iseia@g9q0'
DEBUG = True DEBUG = False
ALLOWED_HOSTS = ['*'] ALLOWED_HOSTS = ['bench.rektdie.com']
HTML_MINIFY = True HTML_MINIFY = True
APPEND_SLASH = True APPEND_SLASH = True
@@ -132,3 +132,16 @@ USE_TZ = True
# https://docs.djangoproject.com/en/2.0/howto/static-files/ # https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/' STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
CSRF_TRUSTED_ORIGINS = ['https://bench.rektdie.com']
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
+5 -5
View File
@@ -1,7 +1,7 @@
<div class="mt-3" id="pagebrowse"> <nav class="mt-3" id="pagebrowser" aria-label="Pagination">
{% if paging.prev != paging.next %} {% if paging.prev != paging.next %}
<div class="pagination"> <div class="pagination">
<a class="page previous" href="/{{ paging.url }}/{{ paging.prev }}"> <a class="page previous" href="/{{ paging.url }}/{{ paging.prev }}" aria-label="Previous page">
<i class="fa-solid fa-arrow-left"></i> <i class="fa-solid fa-arrow-left"></i>
</a> </a>
<div class="pages"> <div class="pages">
@@ -9,15 +9,15 @@
{% if page == "..." %} {% if page == "..." %}
<span class="page ellipsis"><i class="fa-solid fa-fw fa-1x fa-ellipsis"></i></span> <span class="page ellipsis"><i class="fa-solid fa-fw fa-1x fa-ellipsis"></i></span>
{% elif page == paging.page %} {% elif page == paging.page %}
<a class="page current" href="/{{ paging.url }}/{{ page }}">{{ page }}</a> <a class="page current" href="/{{ paging.url }}/{{ page }}" aria-current="page">{{ page }}</a>
{% else %} {% else %}
<a class="page" href="/{{ paging.url }}/{{ page }}">{{ page }}</a> <a class="page" href="/{{ paging.url }}/{{ page }}">{{ page }}</a>
{% endif %} {% endif %}
{% endfor %} {% endfor %}
</div> </div>
<a class="page next" href="/{{ paging.url }}/{{ paging.next }}"> <a class="page next" href="/{{ paging.url }}/{{ paging.next }}" aria-label="Next page">
<i class="fa-solid fa-arrow-right"></i> <i class="fa-solid fa-arrow-right"></i>
</a> </a>
</div> </div>
{% endif %} {% endif %}
</div> </nav>
+82
View File
@@ -0,0 +1,82 @@
<!-- Quick search palette ( Ctrl+K ). Driven by palette.js, styled by palette.css.
Without JavaScript the Search button in the top bar still opens /search. -->
<div id="palette" role="dialog" aria-modal="true" aria-label="Quick search" hidden>
<div class="pl-backdrop"></div>
<div class="pl-panel">
<div class="pl-field">
<i class="fa-solid fa-magnifying-glass pl-glass" aria-hidden="true"></i>
<input class="pl-input" type="text" role="combobox" aria-expanded="true" aria-controls="pl-list"
aria-autocomplete="list" aria-label="Search" autocomplete="off" autocapitalize="off"
spellcheck="false" enterkeyhint="go" placeholder="Search tests, pages and actions">
</div>
<ul class="pl-list" id="pl-list" role="listbox" aria-label="Results"></ul>
<div class="pl-foot" aria-hidden="true">
<span><kbd>&uarr;</kbd><kbd>&darr;</kbd>move</span>
<span><kbd>&crarr;</kbd>open</span>
<span><kbd>esc</kbd>close</span>
</div>
<div class="pl-sr" aria-live="polite"></div>
</div>
<!-- Pages and actions. Only the featured ones are listed before anything is typed -->
<ul id="palette-source" hidden>
<li data-group="Go to" data-href="/index" data-icon="fa-house" data-keywords="home tests overview" data-featured>Index</li>
<li data-group="Go to" data-href="/greens" data-icon="fa-heart" data-keywords="passed wins" data-featured>Greens</li>
<li data-group="Go to" data-href="/search" data-icon="fa-sliders" data-keywords="filter find tests" data-featured>Advanced search</li>
<li data-group="Go to" data-href="/machines" data-icon="fa-microchip" data-keywords="workers clients fleet" data-featured>Machines</li>
<li data-group="Go to" data-href="/users" data-icon="fa-users" data-keywords="people contributors">Users</li>
<li data-group="Go to" data-href="/events" data-icon="fa-circle-exclamation" data-keywords="log actions">Events</li>
<li data-group="Go to" data-href="/errors" data-icon="fa-triangle-exclamation" data-keywords="crash failures log">Errors</li>
<li data-group="Go to" data-href="/networks" data-icon="fa-circle-nodes" data-keywords="nets nnue">Networks</li>
<li data-group="Create" data-href="/newTest" data-icon="fa-plus" data-keywords="new sprt test" data-featured>Create test</li>
<li data-group="Create" data-href="/newTune" data-icon="fa-vial" data-keywords="new spsa tune" data-featured>Create tune</li>
<li data-group="Create" data-href="/newDatagen" data-icon="fa-database" data-keywords="new data generation">Create datagen</li>
<li data-group="Create" data-href="/newNetwork" data-icon="fa-upload" data-keywords="new network net nnue">Upload net</li>
{% if user.is_authenticated %}
<li data-group="Account" data-href="/profile/" data-icon="fa-user" data-keywords="settings password email">Profile</li>
<li data-group="Account" data-href="/logout/" data-icon="fa-right-from-bracket" data-keywords="sign out">Log out</li>
{% else %}
<li data-group="Account" data-href="/login" data-icon="fa-right-to-bracket" data-keywords="sign in">Log in</li>
<li data-group="Account" data-href="/register" data-icon="fa-registered" data-keywords="sign up account">Register</li>
{% endif %}
<li data-group="Links" data-href="{{config.client_repo_url}}" data-icon="fa-brands fa-github" data-keywords="source client code" data-external>OpenBench on GitHub</li>
{% for engine, data in config.engines.items %}
<li data-group="Links" data-href="{{data.source}}" data-icon="fa-chess-knight" data-keywords="engine source repository" data-external>{{engine}} source</li>
{% endfor %}
</ul>
<!-- Hands a free text search over to the existing /search/ page, with every filter left open -->
<form id="palette-search" method="POST" action="/search/" hidden>
{% csrf_token %}
<input type="hidden" name="keywords" value="">
<input type="hidden" name="author" value="">
<input type="hidden" name="engine" value="">
<input type="hidden" name="opening-book" value="">
<input type="hidden" name="test-mode" value="">
<input type="hidden" name="syzygy-wdl" value="">
<input type="hidden" name="tc-type" value="">
<input type="hidden" name="tc-value-select" value="=">
<input type="hidden" name="tc-value-input" value="">
<input type="hidden" name="threads-select" value="&gt;=">
<input type="hidden" name="threads-input" value="1">
<input type="hidden" name="show-greens" value="">
<input type="hidden" name="show-blues" value="">
<input type="hidden" name="show-yellows" value="">
<input type="hidden" name="show-reds" value="">
<input type="hidden" name="show-stopped" value="">
</form>
</div>
+10
View File
@@ -0,0 +1,10 @@
<thead>
<tr class="table-header">
<th>Author</th>
<th>Engine</th>
<th>Test</th>
<th class="textcenter">Diff</th>
<th>Time Control</th>
<th>Result</th>
</tr>
</thead>
+22 -11
View File
@@ -1,15 +1,26 @@
{% load mytags %} {% load mytags uitags %}
<td><a href="/user/{{test.author}}">{{test.author|capfirst|slice:":6"}}</a></td> <td class="col-author"><a href="/user/{{test.author}}" title="{{test.author|capfirst}}">{{test.author|capfirst}}</a></td>
<td>{{test.dev_engine}}</td> <td class="col-engine">{{test.dev_engine}}</td>
<td> <td class="col-test">
<a href="{{test|workload_url}}">{{test|prettyDevName}}</a> <a href="{{test|workload_url}}">{{test|prettyDevName}}</a>
{% if test.error %} <span style="color: red; cursor: pointer" title="Crash or illegal move">*</span> {% endif %} {% if test.error %}<span class="flag flag-error" title="Crash or illegal move">crash</span>{% endif %}
{% if test|test_is_fischer %} <span style="color: green; cursor: pointer" title="Fischer random chess">*</span> {% endif %} {% if test|test_is_fischer %}<span class="flag flag-frc" title="Fischer random chess">frc</span>{% endif %}
{% with progress=test|progress_info %}
{% if progress.gauge %}
<div class="llr llr-{{ progress.tone }}" role="meter" aria-label="LLR" aria-valuemin="{{ progress.lower }}" aria-valuemax="{{ progress.upper }}" aria-valuenow="{{ progress.llr }}" title="LLR {{ progress.llr }} (bounds {{ progress.lower }} to {{ progress.upper }})">
<span class="llr-fill" style="left: {{ progress.left }}%; width: {{ progress.width }}%"></span>
<span class="llr-zero" style="left: {{ progress.zero }}%"></span>
</div>
<div class="llr-scale"><span>{{ progress.lower }}</span><b>{{ progress.llr }}</b><span>{{ progress.upper }}</span></div>
{% elif progress %}
<div class="ob-progress ob-progress-{{ progress.tone }}" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ progress.pct }}" title="{{ progress.pct }}%"><span style="width: {{ progress.pct }}%"></span></div>
{% endif %}
{% endwith %}
</td> </td>
<td class="textcenter"><a href="{{test|gitDiffLink}}">diff</a></td> <td class="col-diff textcenter"><a href="{{test|gitDiffLink}}">diff</a></td>
<td> <td class="col-tc">
{{test.dev_time_control}} {{test.dev_time_control}}
{% if test|test_is_time_odds %} <span style="color: yellow; cursor: pointer" title="Time odds">*</span> {% endif %} {% if test|test_is_time_odds %}<span class="flag flag-time" title="Time odds">time odds</span>{% endif %}
{% if test|test_is_smp_odds %} <span style="color: orange; cursor: pointer" title="Thread odds">*</span> {% endif %} {% if test|test_is_smp_odds %}<span class="flag flag-smp" title="Thread odds">thread odds</span>{% endif %}
</td> </td>
<td class='statblock statblock-{{test|testResultColour}}'><strong>{{test|shortStatBlock|linebreaksbr}}</strong></td> <td class='statblock statblock-{{test|testResultColour}} state-{{ test|test_status }} col-result'><strong>{{test|shortStatBlock|linebreaksbr}}</strong></td>
+169 -88
View File
@@ -5,24 +5,52 @@
{% load static %} {% load static %}
<head> <head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#14161A">
<meta name="color-scheme" content="dark">
<link rel="icon" type="image/svg+xml" href="{% static 'logo.svg' %}?{{ static_version }}"> <link rel="icon" type="image/svg+xml" href="{% static 'logo.svg' %}?{{ static_version }}">
<link rel="stylesheet" href="{% static 'style.css' %}?{{ static_version }}"> <link rel="stylesheet" href="{% static 'style.css' %}?{{ static_version }}">
<link rel="stylesheet" href="{% static 'base.css' %}?{{ static_version }}"> <link rel="stylesheet" href="{% static 'base.css' %}?{{ static_version }}">
<link rel="stylesheet" href="{% static 'form.css' %}?{{ static_version }}"> <link rel="stylesheet" href="{% static 'form.css' %}?{{ static_version }}">
<link rel="stylesheet" href="{% static 'paging.css' %}?{{ static_version }}"> <link rel="stylesheet" href="{% static 'paging.css' %}?{{ static_version }}">
<link rel="stylesheet" href="{% static 'ux.css' %}?{{ static_version }}">
<link rel="stylesheet" href="{% static 'board.css' %}?{{ static_version }}">
<link rel="stylesheet" href="{% static 'refresh.css' %}?{{ static_version }}">
<link rel="stylesheet" href="{% static 'palette.css' %}?{{ static_version }}">
<link rel="stylesheet" href="{% static 'live.css' %}?{{ static_version }}">
<link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css' rel='stylesheet'> <link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css' rel='stylesheet'>
<link rel="preconnect" href="https://fonts.gstatic.com"> <link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Courier+Prime&display=swap" rel="stylesheet"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Instrument+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<title>RektBench</title> <title>{% block title %}RektBench - Distributed SPRT Testing for Chess Engines{% endblock %}</title>
<meta name="description" content="{% block description %}RektBench is a distributed SPRT testing framework for chess engines: live tests, results, networks and worker machines.{% endblock %}">
<meta name="robots" content="{% block robots %}index, follow{% endblock %}">
<link rel="canonical" href="{{ request.scheme }}://{{ request.get_host }}{{ request.path }}">
<meta property="og:site_name" content="RektBench">
<meta property="og:type" content="website">
<meta property="og:title" content="RektBench">
<meta property="og:description" content="Distributed SPRT testing framework for chess engines.">
<meta property="og:url" content="{{ request.scheme }}://{{ request.get_host }}{{ request.path }}">
<meta name="twitter:card" content="summary">
<script type="application/ld+json">
{"@context": "https://schema.org", "@type": "WebSite", "name": "RektBench", "alternateName": "Rekt Bench", "url": "{{ request.scheme }}://{{ request.get_host }}/"}
</script>
{% block scripts %} {% block scripts %}
{% endblock %} {% endblock %}
<script src="{% static 'ui.js' %}?{{ static_version }}" defer></script>
<script src="{% static 'ux.js' %}?{{ static_version }}" defer></script>
<script src="{% static 'palette.js' %}?{{ static_version }}" defer></script>
<script src="{% static 'live.js' %}?{{ static_version }}" defer></script>
<script> <script>
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
@@ -37,7 +65,8 @@
}; };
for (var i = 0; i < timestamps.length; i++) { for (var i = 0; i < timestamps.length; i++) {
var date = new Date(1000 * timestamps[i].innerHTML); var epoch = timestamps[i].getAttribute('data-epoch');
var date = new Date(1000 * (epoch !== null ? epoch : timestamps[i].innerHTML));
timestamps[i].innerHTML = date.toLocaleString(undefined, options); timestamps[i].innerHTML = date.toLocaleString(undefined, options);
} }
} }
@@ -59,109 +88,161 @@
}, false); }, false);
function toggle_sidebar() { function toggle_sidebar() {
document.body.classList.toggle('sidebar-open') var open = document.body.classList.toggle('sidebar-open');
var toggle = document.getElementById('sidebar-toggle');
if (toggle)
toggle.setAttribute('aria-expanded', String(open));
} }
</script> </script>
</head> </head>
<body> <body>
<div id="sidebar"> <a class="skip-link" href="#content">Skip to content</a>
<ul> <header id="topbar">
<li class="header">Admin</li>
<button id="sidebar-toggle" type="button" onclick="toggle_sidebar()"
aria-label="Toggle navigation" aria-controls="sidebar" aria-expanded="false">
<i class="fa-solid fa-bars fa-fw"></i>
</button>
<a class="brand" href="/">
<img class="brand-logo" src="{% static 'logo.svg' %}?{{ static_version }}" alt="" width="26" height="26">
<span class="brand-name">RektBench</span>
<span class="brand-sub">Testing Framework</span>
</a>
<div class="topbar-spacer"></div>
<nav class="topbar-actions" aria-label="Quick actions">
<a class="topbar-btn" id="palette-open" href="/search" title="Search tests" aria-keyshortcuts="Control+K Meta+K">
<i class="fa-solid fa-magnifying-glass fa-fw"></i><span>Search</span><kbd class="topbar-kbd" aria-hidden="true">Ctrl K</kbd>
</a>
<a class="topbar-btn topbar-btn-primary" href="/newTest" title="Create a new test">
<i class="fa-solid fa-plus fa-fw"></i><span>Create Test</span>
</a>
{% if user.is_authenticated %} {% if user.is_authenticated %}
<li><a href="/logout/"><i class="fa-solid fa-right-from-bracket fa-fw"></i> Logout</a></li> <a class="topbar-btn" href="/profile/" title="Profile">
<li><a href="/profile/"><i class="fa-solid fa-user fa-fw"></i> Profile</a></li> <i class="fa-solid fa-user fa-fw"></i><span>{{ user.username|capfirst }}</span>
</a>
{% else %} {% else %}
<li><a href="/login"><i class="fa-solid fa-right-to-bracket fa-fw"></i> Login</a></li> <a class="topbar-btn" href="/login" title="Login">
<li><a href="/register"><i class="fa-solid fa-registered fa-fw"></i> Register</a></li> <i class="fa-solid fa-right-to-bracket fa-fw"></i><span>Login</span>
</a>
{% endif %} {% endif %}
</ul> </nav>
<hr> </header>
<ul> <div id="layout">
<li class="header">Tests</li>
<li><a href="/index"><i class="fa-solid fa-house fa-fw"></i> Index</a></li>
<li><a href="/greens"><i class="fa-solid fa-heart fa-fw"></i> Greens</a></li>
<li><a href="/search"><i class="fa-solid fa-magnifying-glass fa-fw"></i> Search</a></li>
</ul>
<hr> <nav id="sidebar" aria-label="Main navigation">
<ul> <div class="nav-section">
<li class="header">Actions</li> <div class="nav-title">Account</div>
<li><a href="/newTest"><i class="fa-solid fa-plus fa-fw"></i> Create Test</a></li> <ul>
<li><a href="/newTune"><i class="fa-solid fa-vial fa-fw"></i> Create Tune</a></li> {% if user.is_authenticated %}
<li><a href="/newDatagen"><i class="fa-solid fa-database fa-fw"></i> Create Datagen</a></li> <li><a href="/profile/"><i class="fa-solid fa-user fa-fw"></i> Profile</a></li>
<li><a href="/newNetwork"><i class="fa-solid fa-upload fa-fw"></i> Upload Net</a></li> <li><a href="/logout/"><i class="fa-solid fa-right-from-bracket fa-fw"></i> Logout</a></li>
</ul> {% else %}
<li><a href="/login"><i class="fa-solid fa-right-to-bracket fa-fw"></i> Login</a></li>
<hr> <li><a href="/register"><i class="fa-solid fa-registered fa-fw"></i> Register</a></li>
{% endif %}
<ul> </ul>
<li class="header">Info</li>
<li><a href="/users"><i class="fa-solid fa-users fa-fw"></i> Users</a></li>
<li><a href="/events"><i class="fa-solid fa-circle-exclamation fa-fw"></i> Events</a></li>
<li><a href="/errors"><i class="fa-solid fa-exclamation-triangle fa-fw"></i> Errors</a></li>
<li><a href="/machines"><i class="fa-solid fa-microchip fa-fw"></i> Machines</a></li>
<li><a href="/networks"><i class="fa-solid fa-circle-nodes fa-fw"></i> Networks</a></li>
</ul>
<hr>
<ul>
<li class="header">Support</li>
<li><a href="{{config.client_repo_url}}"><i class="fa-brands fa-github fa-fw"></i> OpenBench</a></li>
<li><a href="https://discord.gg/9MVg7fBTpM"><i class="fa-brands fa-discord fa-fw"></i> Discord</a></li>
</ul>
<hr>
<ul>
<li class="header">Engines</li>
{% for engine, data in config.engines.items %}
<li><a href="{{data.source}}">{{engine}}</a></li>
{% endfor %}
</ul>
<hr>
</div>
<div id="content-parent">
<div id="content" class="pb-5">
<div id="content-header">
<button id="sidebar-toggle" onclick="toggle_sidebar()">
<i class="fa-solid fa-bars fa-fw"></i>
</button>
<h2>
<a class="site-title" href="/">RektBench&nbsp;Testing&nbsp;Framework</a>
</h2>
</div> </div>
{% if request.session.error_message %} <div class="nav-section">
<div class="error-message"> <div class="nav-title">Tests</div>
<pre>{{request.session.error_message}}</pre> <ul>
</div> <li><a href="/index"><i class="fa-solid fa-house fa-fw"></i> Index</a></li>
{% endif %} <li><a href="/greens"><i class="fa-solid fa-heart fa-fw"></i> Greens</a></li>
<li><a href="/search"><i class="fa-solid fa-magnifying-glass fa-fw"></i> Search</a></li>
</ul>
</div>
{% if request.session.warning_message %} <div class="nav-section">
<div class="warning-message"> <div class="nav-title">Actions</div>
<pre>{{request.session.warning_message}}</pre> <ul>
</div> <li><a href="/newTest"><i class="fa-solid fa-plus fa-fw"></i> Create Test</a></li>
{% endif %} <li><a href="/newTune"><i class="fa-solid fa-vial fa-fw"></i> Create Tune</a></li>
<li><a href="/newDatagen"><i class="fa-solid fa-database fa-fw"></i> Create Datagen</a></li>
<li><a href="/newNetwork"><i class="fa-solid fa-upload fa-fw"></i> Upload Net</a></li>
</ul>
</div>
{% if request.session.status_message %} <div class="nav-section">
<div class="status-message"> <div class="nav-title">Info</div>
<pre>{{request.session.status_message}}</pre> <ul>
</div> <li><a href="/users"><i class="fa-solid fa-users fa-fw"></i> Users</a></li>
{% endif %} <li><a href="/events"><i class="fa-solid fa-circle-exclamation fa-fw"></i> Events</a></li>
<li><a href="/errors"><i class="fa-solid fa-triangle-exclamation fa-fw"></i> Errors</a></li>
<li><a href="/machines"><i class="fa-solid fa-microchip fa-fw"></i> Machines</a></li>
<li><a href="/networks"><i class="fa-solid fa-circle-nodes fa-fw"></i> Networks</a></li>
</ul>
</div>
<div class="nav-section">
<div class="nav-title">Support</div>
<ul>
<li><a href="{{config.client_repo_url}}"><i class="fa-brands fa-github fa-fw"></i> OpenBench</a></li>
<li><a href="https://discord.gg/9MVg7fBTpM"><i class="fa-brands fa-discord fa-fw"></i> Discord</a></li>
</ul>
</div>
<div class="nav-section">
<div class="nav-title">Engines</div>
<ul>
{% for engine, data in config.engines.items %}
<li><a href="{{data.source}}"><i class="fa-solid fa-chess-knight fa-fw"></i> {{engine}}</a></li>
{% endfor %}
</ul>
</div>
</nav>
<div id="sidebar-backdrop"></div>
<main id="content-parent">
<div id="content">
{% if request.session.error_message %}
<div class="banner error-message" role="alert">
<i class="fa-solid fa-circle-exclamation banner-icon"></i>
<pre>{{request.session.error_message}}</pre>
<button class="banner-close" type="button" aria-label="Dismiss"><i class="fa-solid fa-xmark"></i></button>
</div>
{% endif %}
{% if request.session.warning_message %}
<div class="banner warning-message" role="alert">
<i class="fa-solid fa-triangle-exclamation banner-icon"></i>
<pre>{{request.session.warning_message}}</pre>
<button class="banner-close" type="button" aria-label="Dismiss"><i class="fa-solid fa-xmark"></i></button>
</div>
{% endif %}
{% if request.session.status_message %}
<div class="banner status-message" role="status">
<i class="fa-solid fa-circle-check banner-icon"></i>
<pre>{{request.session.status_message}}</pre>
<button class="banner-close" type="button" aria-label="Dismiss"><i class="fa-solid fa-xmark"></i></button>
</div>
{% endif %}
<div class="page-head">{% block page_head %}{% endblock %}</div>
{% block content %}
{% endblock %}
</div>
</main>
{% block content %}
{% endblock %}
</div>
</div> </div>
<div id="toast" role="status" aria-live="polite"></div>
{% include "OpenBench/Blocks/palette.html" %}
</body> </body>
</html> </html>
+20 -14
View File
@@ -15,15 +15,27 @@
document.addEventListener( document.addEventListener(
'DOMContentLoaded', function () { 'DOMContentLoaded', function () {
change_engine('{{ profile.engine }}', 'dev', '{{workload}}'); change_engine('{{ profile.engine }}', 'dev', '{{workload}}');
enforce_default_text('dev_repo', 'https://github.com/'); enforce_default_text('dev_repo', ['https://github.com/'{% for host in config.gitea_hosts %}, '{{host}}/'{% endfor %}]);
enforce_default_text('base_repo', 'https://github.com/'); enforce_default_text('base_repo', ['https://github.com/'{% for host in config.gitea_hosts %}, '{{host}}/'{% endfor %}]);
}, false }, false
); );
</script> </script>
{% endblock %} {% endblock %}
{% block page_head %}<div><h1 class="page-title">{{submit_text}}</h1><p class="page-sub">Pick a preset to fill in the defaults, then adjust anything below.</p></div>{% endblock %}
{% block content %} {% block content %}
<!-- Presets are generated by create_workload.js, based on the selected Engine -->
<div class="form">
<div class="col-full">
<h3>Presets</h3>
<div id="test-mode-buttons">
<!-- Generated based on the selected Engine -->
</div>
</div>
</div>
<form method="POST" action="{{submit_endpoint}}"> <form method="POST" action="{{submit_endpoint}}">
{% csrf_token %} {% csrf_token %}
@@ -121,7 +133,7 @@
<h3> SPSA Input </h3> <h3> SPSA Input </h3>
<div class="row"> <div class="row">
<textarea style="margin-left:24px" id="spsa_inputs" name="spsa_inputs" rows=9></textarea> <textarea id="spsa_inputs" name="spsa_inputs" rows=9></textarea>
</div> </div>
{% endif %} {% endif %}
@@ -187,7 +199,7 @@
</div> </div>
<div class="row"> <div class="row">
<label for="test_mode"> Play Reverses </label> <label for="datagen_play_reverses"> Play Reverses </label>
<select id="datagen_play_reverses" name="datagen_play_reverses"> <select id="datagen_play_reverses" name="datagen_play_reverses">
<option value="YES"> Yes </option> <option value="YES"> Yes </option>
<option selected value="NO"> No </option> <option selected value="NO"> No </option>
@@ -226,7 +238,7 @@
</div> </div>
<div class="row"> <div class="row">
<label for="throughput"> Throughput </label> <input value="1000" id="throughput" , name="throughput"> <label for="throughput"> Throughput </label> <input value="1000" id="throughput" name="throughput">
</div> </div>
{% if workload == "TEST" or workload == "DATAGEN" %} {% if workload == "TEST" or workload == "DATAGEN" %}
@@ -269,15 +281,9 @@
</div> </div>
</div> </div>
<input type="submit" class="anchorbutton btn-start mt-3 mw-84" name="submit" value="{{submit_text}}"> <div class="form-actions">
<input type="submit" class="anchorbutton btn-blue" name="submit" value="{{submit_text}}">
</div>
</form> </form>
<div class="form">
<div class="col-full">
<div id="test-mode-buttons">
<!-- Generated based on the selected Engine -->
</div>
</div>
</div>
{% endblock %} {% endblock %}
+37 -20
View File
@@ -1,30 +1,47 @@
{% extends "OpenBench/base.html" %} {% extends "OpenBench/base.html" %}
{% load uitags %}
{% block page_head %}<div><h1 class="page-title">Errors</h1><p class="page-sub">Crashes and illegal moves reported by workers</p></div>{% endblock %}
{% block content %} {% block content %}
<table class="hoverable"> <section class="card">
<table class="hoverable">
<tr class="table-header"> <tr class="table-header">
<th>Date</th> <th>Date</th>
<th>#</th> <th>Machine</th>
<th>User</th> <th>User</th>
<th>Test</th> <th>Test</th>
<th>Summary</th> <th>Type</th>
<th>Logs</th> <th>Log</th>
</tr>
{% for event in events %}
<tr>
<td class="timestamp">{{event.created|date:'U'}}</td>
<td><a href="/machines/{{event.machine_id}}">{{event.machine_id}}</a></td>
<td>{{event.author|capfirst}}</td>
<td><a href="/test/{{event.test_id}}">{{event.test_name}}</a></td>
<td>{{event.summary}}</td>
<td>{% if event.log_file %}<a href='/event/{{event.id}}'>View</a>{% endif %}</td>
</tr> </tr>
{% endfor %}
</table> {% for event in events %}
<tr{% if event.log_file %} data-href="/event/{{ event.id }}/"{% endif %}>
<td class="timestamp">{{ event.created|date:'U' }}</td>
<td><a href="/machines/{{ event.machine_id }}">#{{ event.machine_id }}</a></td>
<td>{{ event.author|capfirst }}</td>
<td>
<a href="/test/{{ event.test_id }}">{{ event.test_name }}</a>
{% if event.test_time_control %}<span class="tc-chip">{{ event.test_time_control }}</span>{% endif %}
</td>
<td><span class="badge badge-{{ event.summary|event_tone }}">{{ event.summary }}</span></td>
<td>
{% if event.log_file %}
<a class="ev-open" href="/event/{{ event.id }}/">View <i class="fa-solid fa-arrow-right-long"></i></a>
{% else %}
<span class="muted">&mdash;</span>
{% endif %}
</td>
</tr>
{% empty %}
<tr class="empty-row"><td colspan="6"><i class="fa-regular fa-circle-check"></i>No errors have been reported.</td></tr>
{% endfor %}
</table>
</section>
{% include "OpenBench/Blocks/pagebrowser.html" %} {% include "OpenBench/Blocks/pagebrowser.html" %}
+285 -6
View File
@@ -1,7 +1,286 @@
<!DOCTYPE html> {% extends "OpenBench/base.html" %}
<html lang="en"> {% load static %}
<body>
<pre>{{content}}</pre> {% block scripts %}
</body> <script src="{% static 'chess.js' %}?{{ static_version }}" defer></script>
</html> <script src="{% static 'board.js' %}?{{ static_version }}" defer></script>
<script src="{% static 'event_viewer.js' %}?{{ static_version }}" defer></script>
{% endblock %}
{% block page_head %}
<div data-nav="{{ back_url }}">
<a class="crumb" href="{{ back_url }}"><i class="fa-solid fa-arrow-left fa-fw"></i>{{ back_label }}</a>
<h1 class="page-title">Event #{{ event.id }}</h1>
<p class="page-sub">{{ event.summary|default:"No summary" }}</p>
</div>
{% if kind != 'empty' %}
<div class="page-actions">
<button type="button" class="anchorbutton btn-start" id="ev-copy"><i class="fa-regular fa-copy"></i>Copy</button>
<button type="button" class="anchorbutton btn-start" id="ev-download" data-filename="{{ download_name }}"><i class="fa-solid fa-download"></i>Download</button>
</div>
{% endif %}
{% endblock %}
{% block content %}
<dl class="ev-meta">
<div>
<dt>Type</dt>
<dd><span class="badge badge-{{ tone }}">{{ event.summary|default:"Event" }}</span></dd>
</div>
<div>
<dt>When</dt>
<dd class="timestamp">{{ event.created|date:'U' }}</dd>
</div>
<div>
<dt>User</dt>
<dd>{% if event.author %}<a href="/user/{{ event.author }}">{{ event.author|capfirst }}</a>{% else %}&mdash;{% endif %}</dd>
</div>
<div>
<dt>Machine</dt>
<dd>{% if event.machine_id %}<a href="/machines/{{ event.machine_id }}/">#{{ event.machine_id }}</a>{% else %}&mdash;{% endif %}</dd>
</div>
<div>
<dt>Test</dt>
<dd>{% if event.test_id %}<a href="/test/{{ event.test_id }}/">#{{ event.test_id }}</a>{% else %}&mdash;{% endif %}</dd>
</div>
</dl>
{% if kind == 'pgn' %}
<section class="card">
<header class="card-head">
<h2 class="card-title">Game</h2>
<span class="mono muted">{{ game.ply_count }} plies</span>
</header>
<div class="ev-versus">
<div class="ev-player ev-white">
<strong title="{{ game.white }}">{{ game.white }}</strong>
<small><i class="ev-piece"></i>White</small>
</div>
<div class="ev-result mono">{{ game.result }}</div>
<div class="ev-player ev-black">
<strong title="{{ game.black }}">{{ game.black }}</strong>
<small><i class="ev-piece"></i>Black</small>
</div>
</div>
{% if game.termination or game.final_note %}
<div class="ev-callout ev-callout-{{ tone }}">
<i class="fa-solid fa-circle-exclamation fa-fw"></i>
<div class="ev-callout-body">
<strong>{{ game.termination|default:event.summary }}</strong>
{% if game.final_note %}{{ game.final_note }}{% endif %}
</div>
</div>
{% endif %}
<dl class="ev-facts">
{% if game.time_control %}<div><dt>Time control</dt><dd class="mono">{{ game.time_control }}</dd></div>{% endif %}
{% if game.date %}<div><dt>Date</dt><dd class="mono">{{ game.date }}</dd></div>{% endif %}
{% if game.duration %}<div><dt>Duration</dt><dd class="mono">{{ game.duration }}</dd></div>{% endif %}
{% if game.chess960 %}<div><dt>Variant</dt><dd class="mono">Chess960</dd></div>{% endif %}
{% if game.fen %}<div><dt>Start FEN</dt><dd class="mono">{{ game.fen }}</dd></div>{% endif %}
</dl>
{% if game.headers %}
<details class="ev-headers">
<summary>All PGN headers ({{ game.headers|length }})</summary>
<table>
{% for key, value in game.headers %}
<tr><td>{{ key }}</td><td class="mono">{{ value }}</td></tr>
{% endfor %}
</table>
</details>
{% endif %}
</section>
{% if game.rows %}
<div class="bd-layout">
<section class="card bd-card">
<header class="card-head">
<h2 class="card-title">Board</h2>
{% if game.chess960 %}<span class="badge badge-info">Chess960</span>{% endif %}
</header>
<div class="bd-body">
<div class="bd-grid">
<div class="bd-player is-black" id="bd-top">
<i class="ev-piece"></i>
<strong class="bd-name">{{ game.black }}</strong>
<span class="bd-caps"></span>
<span class="bd-mat"></span>
</div>
<div class="bd-eval" id="bd-eval" aria-hidden="true">
<div class="bd-eval-fill"></div>
<span class="bd-eval-label on-white">&ndash;</span>
</div>
<div class="bd-board" id="bd-board"><noscript><p class="bd-nojs">The board needs JavaScript.</p></noscript></div>
<div class="bd-player is-white" id="bd-bottom">
<i class="ev-piece"></i>
<strong class="bd-name">{{ game.white }}</strong>
<span class="bd-caps"></span>
<span class="bd-mat"></span>
</div>
</div>
<p class="bd-status" id="bd-status">&nbsp;</p>
<div class="bd-controls">
<button type="button" class="bd-btn" id="bd-first" title="First position (Home)" aria-label="First position"><i class="fa-solid fa-backward-step"></i></button>
<button type="button" class="bd-btn" id="bd-prev" title="Previous move (Left arrow)" aria-label="Previous move"><i class="fa-solid fa-chevron-left"></i></button>
<button type="button" class="bd-btn bd-btn-main" id="bd-play" title="Play or pause (Space)" aria-label="Play"><i class="fa-solid fa-play"></i></button>
<button type="button" class="bd-btn" id="bd-next" title="Next move (Right arrow)" aria-label="Next move"><i class="fa-solid fa-chevron-right"></i></button>
<button type="button" class="bd-btn" id="bd-last" title="Last position (End)" aria-label="Last position"><i class="fa-solid fa-forward-step"></i></button>
<button type="button" class="bd-btn bd-btn-flip" id="bd-flip" title="Flip the board (F)" aria-label="Flip the board"><i class="fa-solid fa-retweet"></i></button>
</div>
<div class="bd-fen">
<span class="bd-fen-label">FEN</span>
<code id="bd-fen"></code>
<button type="button" class="bd-btn bd-btn-icon" id="bd-copy" title="Copy FEN" aria-label="Copy FEN"><i class="fa-regular fa-copy"></i></button>
</div>
</div>
</section>
<div class="ev-right">
<div class="ev-right-inner">
<section class="card ev-moves-card">
<header class="card-head">
<h2 class="card-title">Moves</h2>
<span class="count">{{ game.ply_count }}</span>
</header>
<div class="ev-sel">
<div class="ev-sel-main">
<span class="ev-sel-label mono" id="sel-label"></span>
<span class="ev-sel-san mono" id="sel-san">&ndash;</span>
<span class="ev-sel-counter mono" id="sel-counter"></span>
</div>
<div class="ev-sel-stats">
<div><span>Eval</span><strong class="mono" id="sel-eval">&ndash;</strong></div>
<div><span>Depth</span><strong class="mono" id="sel-depth">&ndash;</strong></div>
<div><span>Time</span><strong class="mono" id="sel-time">&ndash;</strong></div>
</div>
<p class="ev-sel-note" id="sel-note" hidden></p>
</div>
<div class="ev-movelist" id="ev-movelist" role="listbox" aria-label="Moves">
{% for row in game.rows %}
<div class="ev-row">
<span class="ev-num">{{ row.num }}.</span>
{% if row.w %}
<button type="button" class="ev-move{% if row.w.final %} is-final{% endif %}" role="option" data-ply="{{ row.w.ply }}">
<span class="ev-san">{{ row.w.san }}</span>{% if row.w.eval %}<em class="ev-eval {{ row.w.tone }}">{{ row.w.eval }}</em>{% endif %}
</button>
{% else %}
<span class="ev-move ev-empty">&hellip;</span>
{% endif %}
{% if row.b %}
<button type="button" class="ev-move{% if row.b.final %} is-final{% endif %}" role="option" data-ply="{{ row.b.ply }}">
<span class="ev-san">{{ row.b.san }}</span>{% if row.b.eval %}<em class="ev-eval {{ row.b.tone }}">{{ row.b.eval }}</em>{% endif %}
</button>
{% else %}
<span class="ev-move ev-empty"></span>
{% endif %}
</div>
{% endfor %}
</div>
<footer class="ev-moves-foot">
<span><kbd>&larr;</kbd> <kbd>&rarr;</kbd> step</span>
<span><kbd>Space</kbd> play</span>
<span><kbd>F</kbd> flip</span>
</footer>
</section>
<section class="card bd-graph-card" id="bd-graph-card">
<header class="card-head">
<h2 class="card-title">Evaluation</h2>
<span class="mono muted" id="bd-graph-label"></span>
</header>
<div class="bd-graph-wrap">
<div class="bd-graph" id="bd-graph"></div>
</div>
</section>
</div>
</div>
</div>
{% else %}
<section class="card">
<div class="empty-state">
<i class="fa-solid fa-chess-pawn"></i>
<p>This game has no moves recorded.</p>
</div>
</section>
{% endif %}
{{ moves_json|json_script:"ev-moves" }}
{{ game_json|json_script:"ev-game" }}
{% elif kind == 'log' %}
<section class="card">
<header class="card-head">
<h2 class="card-title">Log</h2>
<div class="ev-tools">
<span class="badge">{{ log.total }} lines</span>
{% if log.errors %}<span class="badge badge-bad">{{ log.errors }} error{{ log.errors|pluralize }}</span>{% endif %}
{% if log.warnings %}<span class="badge badge-warn">{{ log.warnings }} warning{{ log.warnings|pluralize }}</span>{% endif %}
<input type="search" id="log-filter" class="ev-input" placeholder="Filter lines" aria-label="Filter log lines" autocomplete="off">
<label class="ev-toggle"><input type="checkbox" id="log-issues"> Issues only</label>
<label class="ev-toggle"><input type="checkbox" id="log-wrap"> Wrap lines</label>
</div>
</header>
{% if log.skipped %}
<div class="ev-log-note">Showing the last {{ log.lines|length }} of {{ log.total }} lines. Download has the full log.</div>
{% endif %}
<div class="ev-logbody" id="log-body" role="log" tabindex="0" aria-label="Log output">
{% for line in log.lines %}<div class="ev-line ev-line-{{ line.level }}" data-level="{{ line.level }}"><span class="ev-ln">{{ line.n }}</span><span class="ev-lt">{{ line.text }}</span></div>{% endfor %}
<div class="empty-state" id="log-empty" hidden><p>No lines match.</p></div>
</div>
</section>
{% else %}
<section class="card">
<div class="empty-state">
<i class="fa-regular fa-file-lines"></i>
<p>No log was attached to this event.</p>
</div>
</section>
{% endif %}
{% if kind != 'empty' %}{{ content|json_script:"ev-raw" }}{% endif %}
{% endblock %}
+2
View File
@@ -1,5 +1,7 @@
{% extends "OpenBench/base.html" %} {% extends "OpenBench/base.html" %}
{% block page_head %}<div><h1 class="page-title">Events</h1><p class="page-sub">Recent activity across all workloads</p></div>{% endblock %}
{% block content %} {% block content %}
<table class="hoverable"> <table class="hoverable">
+122 -54
View File
@@ -1,67 +1,135 @@
{% extends "OpenBench/base.html" %} {% extends "OpenBench/base.html" %}
{% load mytags %} {% load mytags uitags %}
{% block page_head %}<div><h1 class="page-title">Tests</h1><p class="page-sub">Pending, active and finished workloads</p></div>{% endblock %}
{% block content %} {% block content %}
<table class="test-list stripes hoverable"> <!-- Overview cards for the front page of the Index, and of User pages -->
{% if status and paging.page == 1 %}
{% with fleet=status|fleet_stats %}
<div class="stat-grid">
<div class="stat-card">
<span class="stat-icon"><i class="fa-solid fa-bolt"></i></span>
<div>
<div class="stat-value">{{ active|length }}</div>
<div class="stat-label">Running</div>
</div>
</div>
<div class="stat-card stat-yellow">
<span class="stat-icon"><i class="fa-solid fa-hourglass-half"></i></span>
<div>
<div class="stat-value">{{ pending|length }}</div>
<div class="stat-label">Pending approval</div>
</div>
</div>
{% if fleet %}
<div class="stat-card stat-green">
<span class="stat-icon"><i class="fa-solid fa-microchip"></i></span>
<div>
<div class="stat-value">{{ fleet.machines }}</div>
<div class="stat-label">Machines online</div>
<div class="stat-sub">{{ fleet.threads }} threads &middot; {{ fleet.mnps }} MNPS</div>
</div>
</div>
{% endif %}
</div>
{% endwith %}
{% endif %}
<!-- Only show Pending tests for the front page of the Index --> <!-- Only show Pending tests for the front page of the Index -->
{% if paging.page == 1 %} {% if paging.page == 1 %}
<!-- Currently Pending tests (Waiting to be approved) -->
{% if pending %}
<tr class="table-header"><th colspan='6'>Pending</th></tr>
{% for test in pending %}
<tr>
{% include "OpenBench/Blocks/testsummary.html" %}
</tr>
{% endfor %}
<tr class="table-spacer"><th colspan='6'></th></tr>
{% endif %}
<!-- Currently Awaiting tests (Waiting for Artifacts) -->
{% if awaiting %}
<tr class="table-header"><th colspan='6'>Awaiting Artifacts</th></tr>
{% for test in awaiting %}
<tr>
{% include "OpenBench/Blocks/testsummary.html" %}
</tr>
{% endfor %}
<tr class="table-spacer"><th colspan='6'></th></tr>
{% endif %}
<!-- Currently Running tests (Waiting to be completed) -->
{% if active %}
<tr class="table-header"><th colspan='6'>Active {{status}}</th></tr>
{% for test in active %}
<!-- Add two empty rows ( for the colouring scheme ) when changing prio -->
{% with prev_test=active|previous:forloop.counter0 %}
{% if prev_test and prev_test.priority != test.priority %}
<tr class="table-spacer-small"><th colspan='6'></th></tr>
<tr class="table-spacer-small"><th colspan='6'></th></tr>
{% endif %}
{% endwith %}
<tr>
{% include "OpenBench/Blocks/testsummary.html" %}
</tr>
{% endfor %}
<tr class="table-spacer"><th colspan='6'></th></tr>
{% endif %}
<!-- Currently Pending tests (Waiting to be approved) -->
{% if pending %}
<section class="card">
<header class="card-head">
<h2 class="card-title">Pending</h2>
<span class="count">{{ pending|length }}</span>
</header>
<table class="test-list stripes hoverable">
{% include "OpenBench/Blocks/testhead.html" %}
<tbody>
{% for test in pending %}
<tr>
{% include "OpenBench/Blocks/testsummary.html" %}
</tr>
{% endfor %}
</tbody>
</table>
</section>
{% endif %} {% endif %}
<!-- Tests which have already finished --> <!-- Currently Awaiting tests (Waiting for Artifacts) -->
<tr class="table-header"><th colspan='6'>Finished</th></tr> {% if awaiting %}
{% for test in completed %} <section class="card">
<tr> <header class="card-head">
{% include "OpenBench/Blocks/testsummary.html" %} <h2 class="card-title">Awaiting Artifacts</h2>
</tr> <span class="count">{{ awaiting|length }}</span>
{% endfor %} </header>
<table class="test-list stripes hoverable">
{% include "OpenBench/Blocks/testhead.html" %}
<tbody>
{% for test in awaiting %}
<tr>
{% include "OpenBench/Blocks/testsummary.html" %}
</tr>
{% endfor %}
</tbody>
</table>
</section>
{% endif %}
</table> <!-- Currently Running tests (Waiting to be completed) -->
{% if active %}
<section class="card">
<header class="card-head">
<h2 class="card-title">Active {{status}}</h2>
<span class="count">{{ active|length }}</span>
</header>
<table class="test-list stripes hoverable">
{% include "OpenBench/Blocks/testhead.html" %}
<tbody>
{% for test in active %}
<!-- Add two empty rows ( for the colouring scheme ) when changing prio -->
{% with prev_test=active|previous:forloop.counter0 %}
{% if prev_test and prev_test.priority != test.priority %}
<tr class="table-spacer-small"><td colspan='6'></td></tr>
<tr class="table-spacer-small"><td colspan='6'></td></tr>
{% endif %}
{% endwith %}
<tr>
{% include "OpenBench/Blocks/testsummary.html" %}
</tr>
{% endfor %}
</tbody>
</table>
</section>
{% endif %}
{% endif %}
<!-- Tests which have already finished -->
<section class="card">
<header class="card-head">
<h2 class="card-title">Finished</h2>
</header>
<table class="test-list stripes hoverable">
{% include "OpenBench/Blocks/testhead.html" %}
<tbody>
{% for test in completed %}
<tr>
{% include "OpenBench/Blocks/testsummary.html" %}
</tr>
{% empty %}
<tr class="empty-row"><td colspan="6"><i class="fa-regular fa-folder-open"></i>No finished tests yet.</td></tr>
{% endfor %}
</tbody>
</table>
</section>
{% include "OpenBench/Blocks/pagebrowser.html" %} {% include "OpenBench/Blocks/pagebrowser.html" %}
+18 -12
View File
@@ -1,20 +1,26 @@
{% extends "OpenBench/base.html" %} {% extends "OpenBench/base.html" %}
{% block page_head %}<div><h1 class="page-title">Login</h1><p class="page-sub">Sign in to create and manage tests.</p></div>{% endblock %}
{% block content %} {% block content %}
<form method="POST" action="/login/"> <div class="auth-wrap">
{% csrf_token %} <form method="POST" action="/login/">
<div class="form"> {% csrf_token %}
<div class="col"> <div class="form">
<div class="row"> <div class="col">
<label type="text">Username</label> <input type="text" name="username"><br> <div class="row">
<label for="username">Username</label>
<input id="username" type="text" name="username" autocomplete="username" autofocus>
</div>
<div class="row">
<label for="password">Password</label>
<input id="password" type="password" name="password" autocomplete="current-password">
</div>
<input type="submit" name="submit" value="Login" class="anchorbutton btn-blue w-100">
</div> </div>
<div class="row">
<label type="text">Password</label> <input type="password" name="password"><br>
</div>
<input type="submit" name="submit" value="Login" class="anchorbutton btn-blue w-100">
</div> </div>
</div> </form>
</form> </div>
{% endblock %} {% endblock %}
+4 -2
View File
@@ -6,11 +6,13 @@
{% load static %} {% load static %}
{% endblock %} {% endblock %}
{% block page_head %}<div><h1 class="page-title">Machine {{ machine.id }}</h1><p class="page-sub">{{ machine.info.machine_name }}</p></div><div class="page-actions"><a class="anchorbutton btn-start" href="/machines"><i class="fa-solid fa-arrow-left fa-fw"></i> All machines</a></div>{% endblock %}
{% block content %} {% block content %}
<div id="config" style="display: block; overflow-x: auto;"> <div id="config" class="card">
<table class="test-config left-align wrappable" style="table-layout: auto; width: 100%;"> <table class="test-config left-align wrappable">
<tr><td class="td-label">User</td><td>{{machine.user.username}}</td></tr> <tr><td class="td-label">User</td><td>{{machine.user.username}}</td></tr>
<tr><td class="td-label">Machine Name</td><td>{{machine.info.machine_name}}</td></tr> <tr><td class="td-label">Machine Name</td><td>{{machine.info.machine_name}}</td></tr>
+2
View File
@@ -2,6 +2,8 @@
{% load mytags %} {% load mytags %}
{% block page_head %}<div><h1 class="page-title">Machines</h1><p class="page-sub">Workers that have connected to this server</p></div>{% endblock %}
{% block content %} {% block content %}
<table class="hoverable"> <table class="hoverable">
+4 -2
View File
@@ -2,6 +2,8 @@
{% load static %} {% load static %}
{% block page_head %}<div><h1 class="page-title">Edit Network</h1><p class="page-sub">{{network.name}}</p></div>{% endblock %}
{% block content %} {% block content %}
<form method="POST" action="/networks/{{network.engine}}/EDIT/{{network.sha256}}/"> <form method="POST" action="/networks/{{network.engine}}/EDIT/{{network.sha256}}/">
@@ -44,7 +46,7 @@
<option value="TRUE"> True </option> <option value="TRUE"> True </option>
<option selected value="FALSE"> False </option> <option selected value="FALSE"> False </option>
{% endif %} {% endif %}
<select> </select>
</div> </div>
<div class="row"> <div class="row">
@@ -57,7 +59,7 @@
<option value="TRUE"> True </option> <option value="TRUE"> True </option>
<option selected value="FALSE"> False </option> <option selected value="FALSE"> False </option>
{% endif %} {% endif %}
<select> </select>
</div> </div>
<input class="anchorbutton btn-blue w-100" type="submit" value="Update Network"> <input class="anchorbutton btn-blue w-100" type="submit" value="Update Network">
+6 -4
View File
@@ -18,6 +18,8 @@
{% endblock %} {% endblock %}
{% block page_head %}<div><h1 class="page-title">Networks</h1><p class="page-sub">Click a column header to sort</p></div><div class="page-actions"><a class="anchorbutton btn-blue" href="/newNetwork"><i class="fa-solid fa-upload fa-fw"></i> Upload Network</a></div>{% endblock %}
{% block content %} {% block content %}
<table id="network-table" class="hoverable"> <table id="network-table" class="hoverable">
@@ -27,7 +29,7 @@
<th class="cursor" onclick="sort_networks(['engine'])">Engine</th> <th class="cursor" onclick="sort_networks(['engine'])">Engine</th>
<th class="cursor" onclick="sort_networks(['author'])">Author</th> <th class="cursor" onclick="sort_networks(['author'])">Author</th>
<th class="cursor" onclick="sort_networks(['name'])">Name</th> <th class="cursor" onclick="sort_networks(['name'])">Name</th>
<th class="cursor" onclick="sort_networks(['sha256'])")>Hash</th> <th class="cursor" onclick="sort_networks(['sha256'])">Hash</th>
<th></th> <th></th>
<th></th> <th></th>
</tr> </tr>
@@ -51,7 +53,7 @@
<td> <td>
<a href="/networks/{{network.engine}}/EDIT/{{network.sha256}}"> <a href="/networks/{{network.engine}}/EDIT/{{network.sha256}}">
<i class="fa-solid fa-pen-to-square" style="color: grey;"></i> <i class="fa-solid fa-pen-to-square icon-action"></i>
</a> </a>
</td> </td>
@@ -59,11 +61,11 @@
{% if not network.default and not network.was_default %} {% if not network.default and not network.was_default %}
<a onclick="return confirm('YOU ARE DELETING THIS NETWORK FILE FOREVER')" <a onclick="return confirm('YOU ARE DELETING THIS NETWORK FILE FOREVER')"
href="/networks/{{network.engine}}/DELETE/{{network.sha256}}"> href="/networks/{{network.engine}}/DELETE/{{network.sha256}}">
<i class="fa-solid fa-trash-can" style="color: #A03030;"></i></a> <i class="fa-solid fa-trash-can icon-danger"></i></a>
{% else %} {% else %}
<a onclick="return alert('You must unset the default and previous-default flags manually before deleting')" <a onclick="return alert('You must unset the default and previous-default flags manually before deleting')"
href="/networks/{{network.engine}}/EDIT/{{network.sha256}}"> href="/networks/{{network.engine}}/EDIT/{{network.sha256}}">
<i class="fa-solid fa-trash-can" style="color: grey;"></i></a> <i class="fa-solid fa-trash-can icon-action"></i></a>
{% endif %} {% endif %}
</td> </td>
</tr> </tr>
+14 -10
View File
@@ -7,16 +7,19 @@
<script src="{% static 'default_text.js' %}?{{ static_version }}"></script> <script src="{% static 'default_text.js' %}?{{ static_version }}"></script>
<script> <script>
enforce_default_text('new-engine-repo', 'https://github.com/'); enforce_default_text('new-engine-repo', ['https://github.com/'{% for host in config.gitea_hosts %}, '{{host}}/'{% endfor %}]);
</script> </script>
{% endblock %} {% endblock %}
{% block page_head %}<div><h1 class="page-title">Profile</h1><p class="page-sub">{{ profile.user.username|capfirst }}</p></div>{% endblock %}
{% block content %} {% block content %}
<form method="POST" action="/profile/"> <form method="POST" action="/profile/">
{% csrf_token %} {% csrf_token %}
<div class="form"> <div class="form">
<div class="col"> <div class="col">
<h3>Account</h3>
<div class="row"> <div class="row">
<label for="username">Username</label> <label for="username">Username</label>
<input id="username" readonly value="{{ profile.user.username }}"> <input id="username" readonly value="{{ profile.user.username }}">
@@ -26,39 +29,40 @@
<input id="email" value="{{ profile.user.email }}" name="email"> <input id="email" value="{{ profile.user.email }}" name="email">
</div> </div>
<h3>Change password</h3>
<div class="row"> <div class="row">
<label for="password1">New Password</label> <label for="password1">New Password</label>
<input id="password1" type="password" name="password1"> <input id="password1" type="password" name="password1" autocomplete="new-password">
</div> </div>
<div class="row"> <div class="row">
<label for="password2">New Password</label> <label for="password2">Repeat Password</label>
<input id="password2" type="password" name="password2"> <input id="password2" type="password" name="password2" autocomplete="new-password">
</div> </div>
<input class="anchorbutton btn-blue w-100" type="submit" value="Update Profile"> <input class="anchorbutton btn-blue w-100" type="submit" value="Update Profile">
</div> </div>
</div> </div>
</form> </form>
<br>
<form method="POST" action="/profileConfig/"> <form method="POST" action="/profileConfig/">
{% csrf_token %} {% csrf_token %}
<div class="form"> <div class="form">
<div class="col" id="engines-container"> <div class="col" id="engines-container">
<h3>Engines</h3>
<!-- Display engines which have repos already defined --> <!-- Display engines which have repos already defined -->
{% for engine, repo in profile.repos.items %} {% for engine, repo in profile.repos.items %}
<div class="row" id="engine-row-{{ engine }}"> <div class="row" id="engine-row-{{ engine }}">
<label for="engine-repo-{{engine}}">{{ engine }}</label> <label for="engine-repo-{{engine}}">{{ engine }}</label>
<input id="engine-repo-{{engine}}" type="text" name="engine-repo-{{engine}}" value="{{ repo|removePrefix:'https://github.com/' }}"> <input id="engine-repo-{{engine}}" type="text" name="engine-repo-{{engine}}" value="{{ repo|removePrefix:'https://github.com/' }}">
<span> <span title="Default engine">
<input id="radio-{{engine}}" type="radio" name="default-status" value="{{engine}}" <input id="radio-{{engine}}" type="radio" name="default-status" value="{{engine}}"
{% if profile.engine == engine %}checked{% endif %}> {% if profile.engine == engine %}checked{% endif %}>
</span> </span>
<span onclick="deleteRow(event)"> <span onclick="deleteRow(event)" title="Remove engine">
<i class="fa-solid fa-trash-can" style="color: #A00000;" data-engine="{{engine}}" ></i> <i class="fa-solid fa-trash-can" data-engine="{{engine}}" ></i>
</span> </span>
</div> </div>
{% endfor %} {% endfor %}
@@ -110,4 +114,4 @@
</script> </script>
{% endblock %} {% endblock %}
+26 -18
View File
@@ -1,26 +1,34 @@
{% extends "OpenBench/base.html" %} {% extends "OpenBench/base.html" %}
{% block page_head %}<div><h1 class="page-title">Register</h1><p class="page-sub">Create an account to start testing.</p></div>{% endblock %}
{% block content %} {% block content %}
<form id="registerForm" method="POST" action="/register/"> <div class="auth-wrap">
{% csrf_token %} <form id="registerForm" method="POST" action="/register/">
<div class="form"> {% csrf_token %}
<div class="col"> <div class="form">
<div class="row"> <div class="col">
<label>Username</label><input name="username"> <div class="row">
<label for="register-username">Username</label>
<input id="register-username" name="username" autocomplete="username" autofocus>
</div>
<div class="row">
<label for="register-password1">Password</label>
<input id="register-password1" type="password" name="password1" autocomplete="new-password">
</div>
<div class="row">
<label for="register-password2">Confirm Password</label>
<input id="register-password2" type="password" name="password2" autocomplete="new-password">
</div>
<div class="row">
<label for="register-email">Email</label>
<input id="register-email" name="email" autocomplete="email">
</div>
<input class="anchorbutton btn-blue w-100" type="submit" name="submit" value="Create User">
</div> </div>
<div class="row">
<label>Password</label><input type="password" name="password1">
</div>
<div class="row">
<label>Password</label><input type="password" name="password2">
</div>
<div class="row">
<label>Email</label><input name="email">
</div>
<input class="anchorbutton btn-blue w-100" type="submit" name="submit" value="Create User">
</div> </div>
</div> </form>
</form> </div>
{% endblock %} {% endblock %}
+84 -56
View File
@@ -27,19 +27,25 @@
{% endblock %} {% endblock %}
{% block page_head %}<div><h1 class="page-title">Search Tests</h1>{% if not tests %}<p class="page-sub">Leave a filter empty to match everything.</p>{% endif %}</div>{% endblock %}
{% block content %} {% block content %}
{% if not tests %} {% if not tests %}
<form method="POST" action="/search/"> <form method="POST" action="/search/">
{% csrf_token %} {% csrf_token %}
<div class="form"> <div class="form">
<div class="col"> <div class="col">
<h3>Who &amp; what</h3>
<div class="row"> <div class="row">
<label for="keywords">Keywords</label> <label for="keywords">Keywords</label>
<input id="keywords" name="keywords" placeholder="Seperated By Spaces"><br> <input id="keywords" name="keywords" placeholder="Seperated By Spaces">
</div> </div>
<div class="row"> <div class="row">
<label for="author">Author</label> <label for="author">Author</label>
<input id="author" name="author" placeholder="All Authors By Default"><br> <input id="author" name="author" placeholder="All Authors By Default">
</div> </div>
<div class="row"> <div class="row">
<label for="engine">Engine</label> <label for="engine">Engine</label>
@@ -48,9 +54,8 @@
{% for name, data in config.engines.items %} {% for name, data in config.engines.items %}
<option value="{{name}}">{{name}}</option> <option value="{{name}}">{{name}}</option>
{% endfor %} {% endfor %}
</select><br> </select>
</div> </div>
<br>
<div class="row"> <div class="row">
<label for="opening-book">Opening Book</label> <label for="opening-book">Opening Book</label>
<select id="opening-book" name="opening-book"> <select id="opening-book" name="opening-book">
@@ -58,15 +63,15 @@
{% for name, data in config.books.items %} {% for name, data in config.books.items %}
<option value="{{name}}">{{name}}</option> <option value="{{name}}">{{name}}</option>
{% endfor %} {% endfor %}
</select><br> </select>
</div> </div>
<div class="row"> <div class="row">
<label for="test-mode">Test Mode</label> <label for="test-mode">Test Mode</label>
<select id="test-mode" name="test-mode"> <select id="test-mode" name="test-mode">
<option value="" selected>All Test Types</option> <option value="" selected>All Test Types</option>
<option value="SPRT">SPRT</option> <option value="SPRT">SPRT</option>
<option value="GAMES">FIXED</option> <option value="GAMES">FIXED</option>
</select><br> </select>
</div> </div>
<div class="row"> <div class="row">
<label for="syzygy-wdl">Syzygy WDL</label> <label for="syzygy-wdl">Syzygy WDL</label>
@@ -78,8 +83,15 @@
<option value="5-MAN"> 5-Man </option> <option value="5-MAN"> 5-Man </option>
<option value="4-MAN"> 4-Man </option> <option value="4-MAN"> 4-Man </option>
<option value="3-MAN"> 3-Man </option> <option value="3-MAN"> 3-Man </option>
</select><br> </select>
</div> </div>
</div>
<div class="col">
<h3>Time &amp; threads</h3>
<div class="row"> <div class="row">
<label for="tc-type">Time Type</label> <label for="tc-type">Time Type</label>
<select id="tc-type" name="tc-type" onchange="changed_timecontrol()"> <select id="tc-type" name="tc-type" onchange="changed_timecontrol()">
@@ -89,71 +101,87 @@
<option value="FIXED-TIME">Fixed Time</option> <option value="FIXED-TIME">Fixed Time</option>
<option value="FISCHER">Fischer</option> <option value="FISCHER">Fischer</option>
<option value="CYCLIC">Cyclic</option> <option value="CYCLIC">Cyclic</option>
</select><br> </select>
</div> </div>
<div class="row"> <div class="row">
<label for="tc-value-input">Time Value</label> <label for="tc-value-input">Time Value</label>
<select id="tc-value-select" name="tc-value-select" style="margin-right: 8px; flex-grow: 0"> <select id="tc-value-select" name="tc-value-select" aria-label="Time value comparison" style="flex-grow: 0">
<option value="=" selected>==</option> <option value="=" selected>=</option>
<option value=">=">&gt;=</option> <option value=">=">&gt;=</option>
<option value="<=">&lt;=</option> <option value="<=">&lt;=</option>
</select> </select>
<input id="tc-value-input" name="tc-value-input"><br> <input id="tc-value-input" name="tc-value-input">
</div> </div>
<div class="row"> <div class="row">
<label for="threads-input">Threads</label> <label for="threads-input">Threads</label>
<select id="threads-select" name="threads-select" style="margin-right: 8px; flex-grow: 0"> <select id="threads-select" name="threads-select" aria-label="Threads comparison" style="flex-grow: 0">
<option value="=">==</option> <option value="=">==</option>
<option value=">=" selected>&gt;=</option> <option value=">=" selected>&gt;=</option>
<option value="<=">&lt;=</option> <option value="<=">&lt;=</option>
</select> </select>
<input id="threads-input" name="threads-input" value="1"><br> <input id="threads-input" name="threads-input" value="1">
</div> </div>
<br>
<div class="row"> <h3>Show results</h3>
<div class="col">
<div class="row"> <div class="chips">
<label for="show-greens">Greens</label> <label class="chip chip-green" for="show-greens">
<input checked type="checkbox" id="show-greens" name="show-greens" value=""> <input checked type="checkbox" id="show-greens" name="show-greens" value="">Greens
</div> </label>
<div class="row"> <label class="chip chip-blue" for="show-blues">
<label for="show-blues">Blues</label> <input checked type="checkbox" id="show-blues" name="show-blues" value="">Blues
<input checked type="checkbox" id="show-blues" name="show-blues" value=""> </label>
</div> <label class="chip chip-yellow" for="show-yellows">
</div> <input checked type="checkbox" id="show-yellows" name="show-yellows" value="">Yellows
<div class="col"> </label>
<div class="row"> <label class="chip chip-red" for="show-reds">
<label for="show-yellows">Yellows</label> <input checked type="checkbox" id="show-reds" name="show-reds" value="">Reds
<input checked type="checkbox" id="show-yellows" name="show-yellows" value=""> </label>
</div> <label class="chip" for="show-stopped">
<div class="row"> <input checked type="checkbox" id="show-stopped" name="show-stopped" value="">Stopped
<label for="show-stopped">Stopped</label> </label>
<input checked type="checkbox" id="show-stopped" name="show-stopped" value=""> <label class="chip" for="show-deleted">
</div> <input type="checkbox" id="show-deleted" name="show-deleted" value="">Deleted
</div> </label>
<div class="col">
<div class="row">
<label for="show-reds">Reds</label>
<input checked type="checkbox" id="show-reds" name="show-reds" value="">
</div>
<div class="row">
<label for="show-deleted">Deleted</label>
<input type="checkbox" id="show-deleted" name="show-deleted" value="">
</div>
</div>
</div> </div>
<input type="submit" class="anchorbutton btn-blue w-100" name="submit" value="Search Tests">
</div> </div>
</div>
<div class="form-actions">
<input type="submit" class="anchorbutton btn-blue" name="submit" value="Search Tests">
</div> </div>
</form> </form>
{% endif %} {% endif %}
<table class="test-list stripes hoverable"> {% if tests %}
{% for test in tests %} <section class="card">
<tr> <header class="card-head">
<td class="datestamp">{{test.creation|date:"U"}}</td> <h2 class="card-title">Results</h2>
{% include "OpenBench/Blocks/testsummary.html" %} <span class="count">{{ tests|length }}</span>
</tr> </header>
{% endfor %} <table class="test-list stripes hoverable">
</table> <thead>
<tr class="table-header">
<th>Date</th>
<th>Author</th>
<th>Engine</th>
<th>Test</th>
<th class="textcenter">Diff</th>
<th>Time Control</th>
<th>Result</th>
</tr>
</thead>
<tbody>
{% for test in tests %}
<tr>
<td class="datestamp col-date">{{test.creation|date:"U"}}</td>
{% include "OpenBench/Blocks/testsummary.html" %}
</tr>
{% endfor %}
</tbody>
</table>
</section>
{% endif %}
{% endblock %} {% endblock %}
+3 -1
View File
@@ -27,6 +27,8 @@
{% endblock %} {% endblock %}
{% block page_head %}<div><h1 class="page-title">Upload Network</h1><p class="page-sub">Share a network file with the workers</p></div>{% endblock %}
{% block content %} {% block content %}
<form method="post" enctype="multipart/form-data" id="network-form"> <form method="post" enctype="multipart/form-data" id="network-form">
@@ -56,6 +58,6 @@
<input type="submit" class="anchorbutton btn-blue w-100" value="Upload"> <input type="submit" class="anchorbutton btn-blue w-100" value="Upload">
</div> </div>
</div> </div>
<form> </form>
{% endblock %} {% endblock %}
+111 -18
View File
@@ -2,30 +2,123 @@
{% load mytags %} {% load mytags %}
{% block page_head %}
<div>
<h1 class="page-title">Users</h1>
<p class="page-sub">Contributors and approvers, with games split by time control</p>
</div>
<div class="page-actions">
<div class="seg" role="group" aria-label="Rank users by">
<a class="seg-btn{% if sort == 'total' %} active{% endif %}" href="?sort=total">All games</a>
<a class="seg-btn{% if sort == 'stc' %} active{% endif %}" href="?sort=stc">STC</a>
<a class="seg-btn{% if sort == 'ltc' %} active{% endif %}" href="?sort=ltc">LTC</a>
<a class="seg-btn{% if sort == 'tests' %} active{% endif %}" href="?sort=tests">Tests</a>
</div>
</div>
{% endblock %}
{% block content %} {% block content %}
<table class="hoverable"> <div class="stat-grid">
<div class="stat-card stat-green">
<span class="stat-icon"><i class="fa-solid fa-users"></i></span>
<div>
<div class="stat-value">{{ summary.users|insertCommas }}</div>
<div class="stat-label">Contributors</div>
</div>
</div>
<div class="stat-card">
<span class="stat-icon"><i class="fa-solid fa-chess"></i></span>
<div>
<div class="stat-value">{{ summary.total|insertCommas }}</div>
<div class="stat-label">Total games</div>
</div>
</div>
<div class="stat-card">
<span class="stat-icon"><i class="fa-solid fa-bolt"></i></span>
<div>
<div class="stat-value">{{ summary.stc|insertCommas }}</div>
<div class="stat-label">STC games</div>
<div class="stat-sub">{{ summary.stc_share }}% of classified games</div>
</div>
</div>
<div class="stat-card stat-purple">
<span class="stat-icon"><i class="fa-solid fa-hourglass-half"></i></span>
<div>
<div class="stat-value">{{ summary.ltc|insertCommas }}</div>
<div class="stat-label">LTC games</div>
<div class="stat-sub">{{ summary.ltc_share }}% of classified games</div>
</div>
</div>
</div>
<tr class="table-header"> <section class="card">
<th>Username</th> <header class="card-head">
<th>Games</th> <h2 class="card-title">Games by time control</h2>
<th>Tests</th> <div class="legend">
<th>Engine</th> <span><i class="dot dot-stc"></i>STC</span>
<th>Created</th> <span><i class="dot dot-ltc"></i>LTC</span>
</tr> {% if show_other %}<span><i class="dot dot-other"></i>Other</span>{% endif %}
</div>
</header>
<div class="split-overview">
<div class="splitbar splitbar-lg">
<span class="splitbar-stc" style="width: {{ summary.stc_share }}%"></span>
<span class="splitbar-ltc" style="width: {{ summary.ltc_share }}%"></span>
<span class="splitbar-other" style="width: {{ summary.oth_share }}%"></span>
</div>
<p class="muted-small">
STC is a Fischer time control with a base time under {{ stc_limit }} seconds, like 10+0.1.
LTC is {{ stc_limit }} seconds or more, like 60+0.6.
Fixed nodes, depth, movetime, and cyclic controls count as Other.
Games are credited to the user whose machines played them.
</p>
</div>
</section>
{% for profile in profiles %} <section class="card">
{% if profile.games or profile.tests or profile.approver %} <table class="hoverable">
<tr class="table-header">
<th>#</th>
<th>Username</th>
<th class="numeric{% if sort == 'total' %} sorted{% endif %}">Games</th>
<th class="numeric{% if sort == 'stc' %} sorted{% endif %}">STC</th>
<th class="numeric{% if sort == 'ltc' %} sorted{% endif %}">LTC</th>
{% if show_other %}<th class="numeric">Other</th>{% endif %}
<th>Split</th>
<th class="numeric{% if sort == 'tests' %} sorted{% endif %}">Tests</th>
<th>Engine</th>
<th>Created</th>
</tr>
{% for row in rows %}
<tr> <tr>
<td><a href="/user/{{profile.user.username}}">{{profile.user.username|capfirst}}</a></td> <td class="rank">{{ forloop.counter }}</td>
<td style="text-align: right">{{profile.games|insertCommas}}</td> <td>
<td style="text-align: right">{{profile.tests|insertCommas}}</td> <a href="/user/{{ row.username }}">{{ row.username|capfirst }}</a>
<td>{{profile.engine}}</td> {% if row.approver %}<span class="badge badge-info">approver</span>{% endif %}
<td class="timestamp">{{profile.user.date_joined|date:'U'}}</td> </td>
<td class="numeric">{{ row.total|insertCommas }}</td>
<td class="numeric num-stc">{{ row.stc|insertCommas }}</td>
<td class="numeric num-ltc">{{ row.ltc|insertCommas }}</td>
{% if show_other %}<td class="numeric">{{ row.other|insertCommas }}</td>{% endif %}
<td>
<div class="splitbar" title="STC {{ row.stc_share }}% / LTC {{ row.ltc_share }}%{% if show_other %} / Other {{ row.oth_share }}%{% endif %}">
<span class="splitbar-stc" style="width: {{ row.stc_share }}%"></span>
<span class="splitbar-ltc" style="width: {{ row.ltc_share }}%"></span>
<span class="splitbar-other" style="width: {{ row.oth_share }}%"></span>
</div>
</td>
<td class="numeric">{{ row.tests|insertCommas }}</td>
<td>{{ row.engine }}</td>
<td class="timestamp">{{ row.joined|date:'U' }}</td>
</tr> </tr>
{% endif %} {% empty %}
{% endfor %} <tr class="empty-row"><td colspan="10"><i class="fa-regular fa-user"></i>No users yet.</td></tr>
{% endfor %}
</table> </table>
</section>
{% endblock %} {% endblock %}
+121 -238
View File
@@ -4,198 +4,28 @@
{% load static %} {% load static %}
{% block scripts %} {% block scripts %}
<link rel="stylesheet" href="{% static 'workload.css' %}?{{ static_version }}">
<link rel="stylesheet" href="{% static 'spsa_panel.css' %}?{{ static_version }}">
<link rel="stylesheet" href="{% static 'spsa_chart.css' %}?{{ static_version }}">
<script src="{% static 'spsa_chart.js' %}?{{ static_version }}" defer></script>
<script src="{% static 'spsa_panel.js' %}?{{ static_version }}" defer></script>
<script src="{% static 'copy_text.js' %}?{{ static_version }}"></script> <script src="{% static 'copy_text.js' %}?{{ static_version }}"></script>
<script> <script src="{% static 'llr_history.js' %}?{{ static_version }}" defer></script>
document.addEventListener('DOMContentLoaded', function() {
var llrHistoryRequest = null;
function initializeLlrHistoryWidget(widget) {
if (!widget || widget.dataset.initialized === 'true') return;
widget.dataset.initialized = 'true';
var history = JSON.parse(widget.dataset.history || '[]');
if (!history.length) return;
var realPoints = history.filter(function(point) { return !point.estimated; });
var peakGames = {};
for (var r = 1; r < realPoints.length - 1; r++) {
var prev = realPoints[r - 1];
var curr = realPoints[r];
var next = realPoints[r + 1];
var isPeak = curr.llr > prev.llr && curr.llr > next.llr;
var isValley = curr.llr < prev.llr && curr.llr < next.llr;
if (isPeak || isValley) {
peakGames[curr.games] = true;
}
}
var svg = widget.querySelector('.llr-history-graph');
var plot = widget.querySelector('.llr-history-plot');
var hoverLine = widget.querySelector('.llr-hover-line');
var hoverPoint = widget.querySelector('.llr-hover-point');
var tooltip = widget.querySelector('.llr-history-tooltip');
var viewBox = svg.viewBox.baseVal;
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function setActivePoint(point) {
hoverLine.setAttribute('x1', point.x);
hoverLine.setAttribute('x2', point.x);
hoverPoint.setAttribute('cx', point.x);
hoverPoint.setAttribute('cy', point.y);
hoverPoint.classList.toggle('llr-hover-point-positive', point.llr >= 0);
hoverPoint.classList.toggle('llr-hover-point-negative', point.llr < 0);
tooltip.textContent = point.games + ' games | LLR ' + (point.estimated ? '≈' : '') + point.llr.toFixed(2);
tooltip.classList.add('active');
var left = clamp((point.x / viewBox.width) * plot.clientWidth + 8, 8, plot.clientWidth - tooltip.offsetWidth - 8);
var top = clamp((point.y / viewBox.height) * svg.clientHeight - tooltip.offsetHeight - 8, 2, svg.clientHeight - tooltip.offsetHeight - 2);
tooltip.style.left = left + 'px';
tooltip.style.top = top + 'px';
}
function clearActivePoint() {
tooltip.classList.remove('active');
hoverLine.classList.remove('active');
hoverPoint.classList.remove('active', 'llr-hover-point-positive', 'llr-hover-point-negative');
}
function nearestPoint(clientX) {
var rect = svg.getBoundingClientRect();
var localX = ((clientX - rect.left) / rect.width) * viewBox.width;
var best = history[0];
var bestDistance = Math.abs(best.x - localX);
var bestPeak = null;
var bestPeakDistance = Infinity;
for (var i = 0; i < history.length; i++) {
var distance = Math.abs(history[i].x - localX);
if (distance < bestDistance) {
best = history[i];
bestDistance = distance;
}
if (!history[i].estimated && peakGames[history[i].games] && distance < bestPeakDistance) {
bestPeak = history[i];
bestPeakDistance = distance;
}
}
if (bestPeak && bestPeakDistance <= 5) {
return bestPeak;
}
return best;
}
svg.addEventListener('mousemove', function(event) {
setActivePoint(nearestPoint(event.clientX));
hoverLine.classList.add('active');
hoverPoint.classList.add('active');
});
svg.addEventListener('mouseleave', function() {
clearActivePoint();
});
svg.addEventListener('mouseenter', function(event) {
setActivePoint(nearestPoint(event.clientX));
hoverLine.classList.add('active');
hoverPoint.classList.add('active');
});
clearActivePoint();
}
function initializeLlrHistoryWidgets(root) {
(root || document).querySelectorAll('.llr-history-widget').forEach(function(widget) {
initializeLlrHistoryWidget(widget);
});
}
function ensureLlrHistoryWidget() {
var existing = document.querySelector('.llr-history-widget');
if (existing) {
initializeLlrHistoryWidget(existing);
return Promise.resolve(existing);
}
var container = document.getElementById('llr-history-container');
if (!container || !container.dataset.historyUrl) {
return Promise.resolve(null);
}
if (llrHistoryRequest) {
return llrHistoryRequest;
}
llrHistoryRequest = fetch(container.dataset.historyUrl, {
credentials: 'same-origin'
}).then(function(response) {
if (!response.ok) {
throw new Error('Unable to load history graph');
}
return response.text();
}).then(function(markup) {
container.innerHTML = markup;
container.removeAttribute('data-history-url');
var widget = container.querySelector('.llr-history-widget');
initializeLlrHistoryWidget(widget);
llrHistoryRequest = null;
return widget;
}).catch(function() {
container.innerHTML = '<div class="llr-history-placeholder llr-history-placeholder-error">Unable to load history graph.</div>';
llrHistoryRequest = null;
return null;
});
return llrHistoryRequest;
}
function queueLlrHistoryWidgetLoad() {
var container = document.getElementById('llr-history-container');
if (!container || !container.dataset.historyUrl) return;
function requestGraphAfterPaint() {
window.requestAnimationFrame(function() {
window.requestAnimationFrame(function() {
setTimeout(function() {
ensureLlrHistoryWidget();
}, 250);
});
});
}
if (document.readyState === 'complete') {
requestGraphAfterPaint();
return;
}
window.addEventListener('load', requestGraphAfterPaint, { once: true });
}
initializeLlrHistoryWidgets(document);
queueLlrHistoryWidgetLoad();
});
</script>
{% endblock %} {% endblock %}
{% block page_head %}<div><h1 class="page-title">{{ type|title }} #{{ workload.id }}</h1><p class="page-sub">{{ workload.dev.name|prettyName }} &middot; by {{ workload.author|capfirst }}</p></div><div class="page-actions">{% if workload.deleted %}<span class="badge badge-muted">Deleted</span>{% elif workload.passed %}<span class="badge badge-ok">Passed</span>{% elif workload.failed %}<span class="badge badge-bad">Failed</span>{% elif workload.finished %}<span class="badge badge-info">Finished</span>{% elif not workload.approved %}<span class="badge badge-warn">Awaiting approval</span>{% else %}<span class="badge badge-info"><i class="fa-solid fa-circle-notch fa-spin"></i> Running</span>{% endif %}</div>{% endblock %}
{% block content %} {% block content %}
<div class="workload-container"> <div class="workload-container{% if type == "TUNE" %} tune-page{% endif %}">
{% if type == "TUNE" %}<div class="tune-side">{% endif %}
<div id="config" style="display: block; overflow-x: auto;"> {% if type == "TUNE" %}<details id="config" class="card config-fold"><summary><span class="card-title">Settings</span><span class="config-hint">Engine, network, book</span></summary>{% else %}<div id="config" class="card">{% endif %}
<table class="test-config left-align wrappable" style="table-layout: auto; width: 100%;"> {% if type != "TUNE" %}<header class="card-head"><h2 class="card-title">Configuration</h2></header>{% endif %}
<table class="test-config left-align wrappable">
<tr><td class="td-label">Author</td><td>{{workload.author|capfirst}}</td></tr> <tr><td class="td-label">Author</td><td>{{workload.author|capfirst}}</td></tr>
<tr><td class="td-label">Creation</td><td class="timestamp">{{workload.creation|date:'U'}}</td></tr> <tr><td class="td-label">Creation</td><td><time class="timestamp" data-epoch="{{workload.creation|date:'U'}}" datetime="{{workload.creation|date:'c'}}">{{workload.creation|date:'Y-m-d H:i'}}</time></td></tr>
<!-- All of the Dev Engine ( or Sole Engine ) information --> <!-- All of the Dev Engine ( or Sole Engine ) information -->
<tr><td class="td-label">{{dev_text}} Source</td><td><a href="{{workload.dev_repo}}">{{workload.dev_repo}}</a></td></tr> <tr><td class="td-label">{{dev_text}} Source</td><td><a href="{{workload.dev_repo}}">{{workload.dev_repo}}</a></td></tr>
@@ -242,54 +72,55 @@
{% endif %} {% endif %}
</table> </table>
</div> {% if type == "TUNE" %}</details>{% else %}</div>{% endif %}
<div id="actions" class="ml-3"> <div id="actions" class="card">
<header class="card-head"><h2 class="card-title">Actions</h2></header>
<!-- Dev vs Base [Git Diff Link] --> <!-- Dev vs Base [Git Diff Link] -->
<h4><a href="{{workload|gitDiffLink}}">{{workload|git_diff_text}}</a></h4> <a class="diff-link" href="{{workload|gitDiffLink}}"><i class="fa-solid fa-code-compare fa-fw"></i> {{workload|git_diff_text}}</a>
<div class="anchor-container"> <div class="anchor-container">
<!-- Approve Button: For Admins, or Cross-approvers --> <!-- Approve Button: For Admins, or Cross-approvers -->
{% if not workload.approved and profile.approver and profile.user.username != workload.author %} {% if not workload.approved and profile.approver and profile.user.username != workload.author %}
<a class="anchorbutton btn-blue" href="/{{type|lower}}/{{workload.id}}/APPROVE">Approve</a> <a class="anchorbutton btn-blue" href="/{{type|lower}}/{{workload.id}}/APPROVE"><i class="fa-solid fa-check fa-fw"></i> Approve</a>
{% elif not workload.approved and request.user.is_superuser %} {% elif not workload.approved and request.user.is_superuser %}
<a class="anchorbutton btn-blue" href="/{{type|lower}}/{{workload.id}}/APPROVE">Approve</a> <a class="anchorbutton btn-blue" href="/{{type|lower}}/{{workload.id}}/APPROVE"><i class="fa-solid fa-check fa-fw"></i> Approve</a>
{% else %} {% else %}
<a class="anchorbutton btn-disabled">Approve</a> <span class="anchorbutton btn-disabled" aria-disabled="true"><i class="fa-solid fa-check fa-fw"></i> Approve</span>
{% endif %} {% endif %}
<!-- Restart Button: For Approvers or Workload Authors of finished workloads --> <!-- Restart Button: For Approvers or Workload Authors of finished workloads -->
{% if workload.finished and not workload.passed and not workload.failed and profile.approver %} {% if workload.finished and not workload.passed and not workload.failed and profile.approver %}
<a class="anchorbutton btn-yellow" href="/{{type|lower}}/{{workload.id}}/RESTART">Restart</a> <a class="anchorbutton btn-yellow" href="/{{type|lower}}/{{workload.id}}/RESTART"><i class="fa-solid fa-rotate-right fa-fw"></i> Restart</a>
{% elif workload.finished and not workload.passed and not workload.failed and profile.user.username == workload.author %} {% elif workload.finished and not workload.passed and not workload.failed and profile.user.username == workload.author %}
<a class="anchorbutton btn-yellow" href="/{{type|lower}}/{{workload.id}}/RESTART">Restart</a> <a class="anchorbutton btn-yellow" href="/{{type|lower}}/{{workload.id}}/RESTART"><i class="fa-solid fa-rotate-right fa-fw"></i> Restart</a>
{% elif workload.finished %} {% elif workload.finished %}
<a class="anchorbutton btn-disabled">Restart</a> <span class="anchorbutton btn-disabled" aria-disabled="true"><i class="fa-solid fa-rotate-right fa-fw"></i> Restart</span>
{% endif %} {% endif %}
<!-- Stop Button: For Approvers or Workload Authors of active workloads --> <!-- Stop Button: For Approvers or Workload Authors of active workloads -->
{% if not workload.finished and profile.approver %} {% if not workload.finished and profile.approver %}
<a class="anchorbutton btn-yellow" href="/{{type|lower}}/{{workload.id}}/STOP">Stop</a> <a class="anchorbutton btn-yellow" href="/{{type|lower}}/{{workload.id}}/STOP"><i class="fa-solid fa-stop fa-fw"></i> Stop</a>
{% elif not workload.finished and profile.user.username == workload.author %} {% elif not workload.finished and profile.user.username == workload.author %}
<a class="anchorbutton btn-yellow" href="/{{type|lower}}/{{workload.id}}/STOP">Stop</a> <a class="anchorbutton btn-yellow" href="/{{type|lower}}/{{workload.id}}/STOP"><i class="fa-solid fa-stop fa-fw"></i> Stop</a>
{% elif not workload.finished %} {% elif not workload.finished %}
<a class="anchorbutton btn-disabled">Stop</a> <span class="anchorbutton btn-disabled" aria-disabled="true"><i class="fa-solid fa-stop fa-fw"></i> Stop</span>
{% endif %} {% endif %}
<!-- Delete/Restore Button: For Approvers or Workload Authors --> <!-- Delete/Restore Button: For Approvers or Workload Authors -->
{% if profile.approver or profile.user.username == workload.author %} {% if profile.approver or profile.user.username == workload.author %}
{% if workload.deleted %} {% if workload.deleted %}
<a class="anchorbutton btn-preset" href="/{{type|lower}}/{{workload.id}}/RESTORE">Restore</a> <a class="anchorbutton btn-preset" href="/{{type|lower}}/{{workload.id}}/RESTORE"><i class="fa-solid fa-rotate-left fa-fw"></i> Restore</a>
{% else %} {% else %}
<a class="anchorbutton btn-red" href="/{{type|lower}}/{{workload.id}}/DELETE">Delete</a> <a class="anchorbutton btn-red" href="/{{type|lower}}/{{workload.id}}/DELETE"><i class="fa-solid fa-trash-can fa-fw"></i> Delete</a>
{% endif %} {% endif %}
{% else %} {% else %}
{% if workload.deleted %} {% if workload.deleted %}
<a class="anchorbutton btn-disabled">Restore</a> <span class="anchorbutton btn-disabled" aria-disabled="true"><i class="fa-solid fa-rotate-left fa-fw"></i> Restore</span>
{% else %} {% else %}
<a class="anchorbutton btn-disabled">Delete</a> <span class="anchorbutton btn-disabled" aria-disabled="true"><i class="fa-solid fa-trash-can fa-fw"></i> Delete</span>
{% endif %} {% endif %}
{% endif %} {% endif %}
</div> </div>
@@ -297,21 +128,21 @@
<!-- Copy Button: Copy the current results statblock --> <!-- Copy Button: Copy the current results statblock -->
{% if type == "TEST" or type == "DATAGEN" %} {% if type == "TEST" or type == "DATAGEN" %}
<div class="anchor-container"> <div class="anchor-container">
<a class="mt-1 anchorbutton btn-blue" onclick="copy_text('long-statblock', true)">Copy Stat Block</a> <button type="button" class="mt-1 anchorbutton btn-start" onclick="copy_text('long-statblock', true)"><i class="fa-regular fa-copy fa-fw"></i> Copy Stat Block</button>
</div> </div>
{% endif %} {% endif %}
<!-- Copy Button (DC): Copy the current results statblock --> <!-- Copy Button (DC): Copy the current results statblock -->
{% if type == "TEST" or type == "DATAGEN" %} {% if type == "TEST" or type == "DATAGEN" %}
<div class="anchor-container"> <div class="anchor-container">
<a class="mt-1 anchorbutton btn-blue" onclick="copy_text('long-statblock', true, true)">Copy Stat Block (DC Block)</a> <button type="button" class="mt-1 anchorbutton btn-start" onclick="copy_text('long-statblock', true, true)"><i class="fa-regular fa-copy fa-fw"></i> Copy Stat Block (DC Block)</button>
</div> </div>
{% endif %} {% endif %}
<!-- PGN Download Button --> <!-- PGN Download Button -->
{% if workload.upload_pgns != "FALSE" %} {% if workload.upload_pgns != "FALSE" %}
<div class="anchor-container"> <div class="anchor-container">
<a class="mt-1 anchorbutton btn-blue" href="/api/pgns/{{workload.id}}/">Download PGN Archive</a> <a class="mt-1 anchorbutton btn-start" href="/api/pgns/{{workload.id}}/"><i class="fa-solid fa-download fa-fw"></i> Download PGN Archive</a>
</div> </div>
{% endif %} {% endif %}
@@ -319,7 +150,7 @@
{% if type == "TUNE" %} {% if type == "TUNE" %}
<div class="anchor-container"> <div class="anchor-container">
<pre id="spsa-input" style="display: none">{{workload|spsa_original_input}}</pre> <pre id="spsa-input" style="display: none">{{workload|spsa_original_input}}</pre>
<a class="mt-1 anchorbutton btn-blue" onclick="copy_text('spsa-input', false)">Copy SPSA Inputs</a> <button type="button" class="mt-1 anchorbutton btn-start" onclick="copy_text('spsa-input', false)"><i class="fa-regular fa-copy fa-fw"></i> Copy SPSA Inputs</button>
</div> </div>
{% endif %} {% endif %}
@@ -327,11 +158,11 @@
{% if type == "TUNE" %} {% if type == "TUNE" %}
<div class="anchor-container"> <div class="anchor-container">
<pre id="spsa-output" style="display: none">{{workload|spsa_optimal_values}}</pre> <pre id="spsa-output" style="display: none">{{workload|spsa_optimal_values}}</pre>
<a class="mt-1 anchorbutton btn-blue" onclick="copy_text('spsa-output', false)">Copy SPSA Outputs</a> <button type="button" class="mt-1 anchorbutton btn-start" onclick="copy_text('spsa-output', false)"><i class="fa-regular fa-copy fa-fw"></i> Copy SPSA Outputs</button>
</div> </div>
{% endif %} {% endif %}
<!-- Elo, (SPRT/LRR if SPRT, otherwise CONF), Games --> <!-- Elo, (SPRT/LLR if SPRT, otherwise CONF), Games -->
{% if type == "TEST" %} {% if type == "TEST" %}
<pre class="long-statblock" id="long-statblock">{{workload|longStatBlock|linebreaksbr}}</pre> <pre class="long-statblock" id="long-statblock">{{workload|longStatBlock|linebreaksbr}}</pre>
{% elif type == "TUNE" %} {% elif type == "TUNE" %}
@@ -340,8 +171,8 @@
<pre class="long-statblock" id="long-statblock">{{workload|longStatBlock|linebreaksbr}}</pre> <pre class="long-statblock" id="long-statblock">{{workload|longStatBlock|linebreaksbr}}</pre>
{% endif %} {% endif %}
<!-- Forum to modify the Priority, Throughput, or (Tests only) Workload Size --> <h3 class="section-label">Adjust</h3>
<form method="POST" action="/{{type|lower}}/{{workload.id}}/MODIFY"> <form class="modify-form" method="POST" action="/{{type|lower}}/{{workload.id}}/MODIFY">
{% csrf_token %} {% csrf_token %}
<div class="form"> <div class="form">
<div class="col-full"> <div class="col-full">
@@ -373,27 +204,12 @@
</div> </div>
</form> </form>
<!-- LLR history for SPRT tests: fetched lazily, and drawn by llr_history.js -->
{% if workload.test_mode == "SPRT" %} {% if workload.test_mode == "SPRT" %}
<div class="llr-history-panel" title="LLR history over the lifetime of the test"> <div class="llr-history-panel" title="LLR history over the lifetime of the test">
<div class="llr-history-label">LLR History</div> <div class="llr-history-label">LLR History</div>
<div id="llr-history-container" class="llr-history-loader" data-history-url="{{llr_history_endpoint}}"> <div id="llr-history-container" class="llr-history-loader" data-history-url="{{llr_history_endpoint}}">
<div class="llr-history-chart"> <div class="llr-history-placeholder">Loading history graph...</div>
<div class="llr-history-yaxis">
<div></div>
<div></div>
<div></div>
</div>
<div class="llr-history-main">
<div class="llr-history-plot">
<div class="llr-history-placeholder">Loading history graph...</div>
</div>
<div class="llr-history-xaxis">
<div>0</div>
<div></div>
<div>{{workload.games}} g</div>
</div>
</div>
</div>
</div> </div>
</div> </div>
{% endif %} {% endif %}
@@ -401,7 +217,72 @@
<!-- SPSA Paramater Summary, for Tunes --> <!-- SPSA Paramater Summary, for Tunes -->
{% if type == "TUNE" %} {% if type == "TUNE" %}
<div id="parameters" class="w-100 mt-3" style="float:left;"> </div><!-- /tune-side -->
<div class="tune-main">
{% with panel=workload|spsa_param_panel %}
<section id="spsa-panel" class="card spsa-panel">
<header class="card-head"><h2 class="card-title">Tuning progress</h2></header>
<div class="spsa-summary">
<div class="spsa-iter">
<span class="spsa-big">{{ panel.complete }}</span>
<span class="spsa-of">of {{ panel.iterations }} iterations</span>
</div>
<div class="spsa-bar" role="progressbar" aria-label="Iterations completed" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ panel.pct }}"><span style="width: {{ panel.pct }}%"></span></div>
<dl class="spsa-facts">
<div><dt>Parameters</dt><dd>{{ panel.count }}</dd></div>
<div><dt>Moved</dt><dd>{{ panel.moved }}</dd></div>
<div><dt>Games</dt><dd>{{ panel.games|insertCommas }}</dd></div>
</dl>
</div>
<div class="spsa-history">
<div class="spsa-history-head">
<h3>Movement since the start</h3>
<p>Each line is one parameter, as a share of its allowed range. Point at a name below to follow it, or click it to keep it on the chart.</p>
</div>
{{ workload|spsa_history_chart }}
</div>
<div class="spsa-tools">
<input id="spsa-filter" type="search" placeholder="Filter parameters" aria-label="Filter parameters by name" autocomplete="off">
<select id="spsa-sort" aria-label="Sort parameters">
<option value="index">Original order</option>
<option value="drift">Moved the most</option>
<option value="name">Name</option>
</select>
</div>
<ol id="spsa-rows" class="spsa-rows">
{% for p in panel.params %}
<li class="spsa-row{% if p.bound %} at-bound{% endif %}" data-name="{{ p.name|lower }}" data-drift="{{ p.drift }}" data-index="{{ forloop.counter0 }}">
<button type="button" class="spsa-name" aria-pressed="false" title="Show on the chart">{{ p.name }}</button>
<div class="spsa-track-wrap">
<div class="spsa-track" role="img" aria-label="{{ p.name }} is {{ p.value }}, within {{ p.min }} to {{ p.max }}, started at {{ p.start }}{% if p.bound %}, at its {{ p.bound }} limit{% endif %}" title="Start {{ p.start }}, now {{ p.value }}, C {{ p.c }}, R {{ p.r }}{% if p.bound %}. At its {{ p.bound }} limit.{% endif %}">
<span class="spsa-drift" style="left: {{ p.left }}%; width: {{ p.width }}%"></span>
<span class="spsa-start" style="left: {{ p.from }}%"></span>
<span class="spsa-now" style="left: {{ p.now }}%"></span>
</div>
<div class="spsa-scale"><span>{{ p.min }}</span><span>{{ p.max }}</span></div>
</div>
<span class="spsa-value">{{ p.value }}</span>
<span class="spsa-delta">{% if p.moved %}{{ p.delta }}{% else %}unchanged{% endif %}</span>
</li>
{% endfor %}
</ol>
<p id="spsa-empty" class="spsa-empty" hidden>No parameter matches that name.</p>
<div class="spsa-key">
<span><i class="k-start"></i>Start value</span>
<span><i class="k-now"></i>Current value</span>
<span><i class="k-limit"></i>At a limit of its range</span>
</div>
</section>
{% endwith %}
<details id="parameters" class="card config-fold">
<summary><span class="card-title">Parameter details</span><span class="config-hint">Start, limits, C and R</span></summary>
<table class="stripes wrappable"> <table class="stripes wrappable">
<tr class="table-header"> <tr class="table-header">
@@ -419,24 +300,25 @@
<td> {{ element }} </td> <td> {{ element }} </td>
{% endif %} {% endif %}
{% endfor %} {% endfor %}
<tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
</div> </details>
{% endif %} {% endif %}
<div id="results" class="w-100 mt-3" style="float:left;"> {% if type == "TUNE" %}<details id="results" class="card config-fold"><summary><span class="card-title">Results by Machine</span><span class="config-hint">{{ results|length }} machine{{ results|length|pluralize }}, games and results</span></summary>{% else %}<div id="results" class="card">
<header class="card-head"><h2 class="card-title">Results by Machine</h2></header>{% endif %}
<table class="stripes wrappable"> <table class="stripes wrappable">
<tr class="table-header"> <tr class="table-header">
<th>#</th> <th>#</th>
<th>User</th> <th>User</th>
<th>Updated</th> <th>Updated</th>
<th style="width: 45px">Games</th> <th class="numeric">Games</th>
<th style="width: 45px">Won</th> <th class="numeric">Won</th>
<th style="width: 45px">Lost</th> <th class="numeric">Lost</th>
<th style="width: 45px">Drawn</th> <th class="numeric">Drawn</th>
<th style="width: 45px">Time</th> <th class="numeric">Time</th>
<th style="width: 45px">Crash</th> <th class="numeric">Crash</th>
</tr> </tr>
{% for result in results %} {% for result in results %}
@@ -444,7 +326,7 @@
<tr {% if result.active %} class="active-highlight" {% endif %}> <tr {% if result.active %} class="active-highlight" {% endif %}>
<td><a href="/machines/{{result.data.machine.id}}">{{result.data.machine.id}}</a></td> <td><a href="/machines/{{result.data.machine.id}}">{{result.data.machine.id}}</a></td>
<td>{{result.data.machine.user.username|capfirst}}</td> <td>{{result.data.machine.user.username|capfirst}}</td>
<td class="timestamp">{{result.data.updated|date:'U'}}</td> <td><time class="timestamp" data-epoch="{{result.data.updated|date:'U'}}" datetime="{{result.data.updated|date:'c'}}">{{result.data.updated|date:'Y-m-d H:i'}}</time></td>
<td class="numeric">{{result.data.games}}</td> <td class="numeric">{{result.data.games}}</td>
<td class="numeric">{{result.data.wins}}</td> <td class="numeric">{{result.data.wins}}</td>
<td class="numeric">{{result.data.losses}}</td> <td class="numeric">{{result.data.losses}}</td>
@@ -454,8 +336,9 @@
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
</div> {% if type == "TUNE" %}</details>{% else %}</div>{% endif %}
{% if type == "TUNE" %}</div><!-- /tune-main -->{% endif %}
</div> </div>
{% endblock %} {% endblock %}
+1 -1
View File
@@ -1,4 +1,4 @@
Django==4.2.1 Django==4.2.1
django-htmlmin==0.11.0 django-htmlmin==0.11.0
requests requests
scipy==1.9.0 scipy==1.18.1