Compare commits

...
2 Commits
Author SHA1 Message Date
sistav 3f8dacfe1c Add openings 2026-07-08 21:24:56 -04:00
sistav 9c5c599a26 Fix changes for blunder analysis
a
2026-07-08 21:12:54 -04:00
13 changed files with 163 additions and 97 deletions

No files matched your search

+2
View File
@@ -1,2 +1,4 @@
app/__pycache__ app/__pycache__
*.db *.db
data/
docker-compose.yml
+3
View File
@@ -18,4 +18,7 @@ ENV DATA_DIR=/app/data
EXPOSE 8000 EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/api/health', timeout=4)"
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
+33 -12
View File
@@ -1,5 +1,6 @@
import io import io
import math
import os import os
import shutil import shutil
@@ -15,14 +16,32 @@ MAX_PLIES = int(os.environ.get("MAX_PLIES", "500"))
MATE_SCORE_CP = 100_000 MATE_SCORE_CP = 100_000
def classify(loss_cp: int) -> str: def _opening_name(headers) -> str | None:
if loss_cp <= 10: url = headers.get("ECOUrl", "")
slug = url.rstrip("/").rsplit("/", 1)[-1]
words = []
for token in slug.split("-"):
if token[:1].isdigit():
break
words.append(token)
return " ".join(words) or headers.get("ECO") or None
def _win_pct(cp: int) -> float:
return 50 + 50 * (2 / (1 + math.exp(-0.00368208 * cp)) - 1)
def classify(eval_before: int, eval_after: int, mover_is_white: bool) -> str:
before = _win_pct(eval_before)
after = _win_pct(eval_after)
drop = (before - after) if mover_is_white else (after - before)
if drop <= 2:
return "best" return "best"
if loss_cp <= 50: if drop <= 10:
return "good" return "good"
if loss_cp <= 100: if drop <= 20:
return "inaccuracy" return "inaccuracy"
if loss_cp <= 200: if drop <= 30:
return "mistake" return "mistake"
return "blunder" return "blunder"
@@ -34,6 +53,9 @@ async def analyze_pgn(pgn_text: str, username: str | None = None, depth: int = D
white = game.headers.get("White", "") white = game.headers.get("White", "")
black = game.headers.get("Black", "") black = game.headers.get("Black", "")
white_rating = game.headers.get("WhiteElo", "")
black_rating = game.headers.get("BlackElo", "")
link = game.headers.get("Link", "")
user_color = None user_color = None
if username: if username:
if username.lower() == white.lower(): if username.lower() == white.lower():
@@ -78,11 +100,6 @@ async def analyze_pgn(pgn_text: str, username: str | None = None, depth: int = D
san_best = board.san(best_move) if best_move and best_move in board.legal_moves else None san_best = board.san(best_move) if best_move and best_move in board.legal_moves else None
uci_best = best_move.uci() if best_move else None uci_best = best_move.uci() if best_move else None
loss_cp = None
if eval_before is not None and eval_after is not None:
loss_cp = (eval_before - eval_after) if mover_is_white else (eval_after - eval_before)
loss_cp = max(0, loss_cp)
board.push(move) board.push(move)
is_user_move = None is_user_move = None
@@ -97,8 +114,8 @@ async def analyze_pgn(pgn_text: str, username: str | None = None, depth: int = D
"best_move_san": san_best, "best_move_san": san_best,
"best_move_uci": uci_best, "best_move_uci": uci_best,
"eval_cp": eval_after, "eval_cp": eval_after,
"loss_cp": loss_cp, "classification": classify(eval_before, eval_after, mover_is_white)
"classification": classify(loss_cp) if loss_cp is not None else "unknown", if eval_before is not None and eval_after is not None else "unknown",
"is_user_move": is_user_move, "is_user_move": is_user_move,
"fen_after": board.fen(), "fen_after": board.fen(),
}) })
@@ -106,6 +123,10 @@ async def analyze_pgn(pgn_text: str, username: str | None = None, depth: int = D
return { return {
"white": white, "white": white,
"black": black, "black": black,
"white_rating": white_rating if white_rating.isdigit() else None,
"black_rating": black_rating if black_rating.isdigit() else None,
"game_url": link if link.startswith("https://www.chess.com/") else None,
"opening": _opening_name(game.headers),
"result": game.headers.get("Result", ""), "result": game.headers.get("Result", ""),
"initial_eval_cp": white_pov_evals[0], "initial_eval_cp": white_pov_evals[0],
"initial_fen": game.headers.get("FEN", chess.STARTING_FEN), "initial_fen": game.headers.get("FEN", chess.STARTING_FEN),
+4 -18
View File
@@ -31,10 +31,6 @@ def init_db() -> None:
CREATE TABLE IF NOT EXISTS games ( CREATE TABLE IF NOT EXISTS games (
id TEXT PRIMARY KEY, id TEXT PRIMARY KEY,
username TEXT, username TEXT,
white TEXT,
black TEXT,
result TEXT,
depth INTEGER,
created_at REAL, created_at REAL,
analysis_json TEXT NOT NULL analysis_json TEXT NOT NULL
) )
@@ -60,25 +56,15 @@ def get_game(game_id: str) -> dict | None:
return analysis return analysis
def save_game(game_id: str, username: str | None, depth: int, analysis: dict) -> None: def save_game(game_id: str, username: str | None, analysis: dict) -> None:
conn = _connect() conn = _connect()
try: try:
conn.execute( conn.execute(
""" """
INSERT OR REPLACE INTO games INSERT OR REPLACE INTO games (id, username, created_at, analysis_json)
(id, username, white, black, result, depth, created_at, analysis_json) VALUES (?, ?, ?, ?)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""", """,
( (game_id, username, time.time(), json.dumps(analysis)),
game_id,
username,
analysis.get("white"),
analysis.get("black"),
analysis.get("result"),
depth,
time.time(),
json.dumps(analysis),
),
) )
_purge_old(conn) _purge_old(conn)
conn.commit() conn.commit()
+15 -6
View File
@@ -5,15 +5,24 @@ from fastapi import HTTPException
BASE_URL = "https://api.chess.com/pub" BASE_URL = "https://api.chess.com/pub"
HEADERS = {"User-Agent": os.environ.get("CHESSCOM_USER_AGENT", "chess.sistav.com")} HEADERS = {"User-Agent": os.environ.get("CHESSCOM_USER_AGENT", "chess.sistav.com")}
UPSTREAM_ERROR = "chess.com isn't responding right now. Try again in a minute."
async def _get(url: str, timeout: float) -> httpx.Response:
try:
async with httpx.AsyncClient(headers=HEADERS, timeout=timeout) as client:
return await client.get(url)
except httpx.HTTPError:
raise HTTPException(status_code=502, detail=UPSTREAM_ERROR)
async def get_archives(username: str) -> list[str]: async def get_archives(username: str) -> list[str]:
url = f"{BASE_URL}/player/{quote(username, safe='')}/games/archives" url = f"{BASE_URL}/player/{quote(username, safe='')}/games/archives"
async with httpx.AsyncClient(headers=HEADERS, timeout=15) as client: resp = await _get(url, timeout=15)
resp = await client.get(url)
if resp.status_code == 404: if resp.status_code == 404:
raise HTTPException(status_code=404, detail=f"No chess.com player found for '{username}'") raise HTTPException(status_code=404, detail=f"No chess.com player found for '{username}'")
resp.raise_for_status() if resp.status_code != 200:
raise HTTPException(status_code=502, detail=UPSTREAM_ERROR)
archive_urls = resp.json().get("archives", []) archive_urls = resp.json().get("archives", [])
months = [] months = []
for archive_url in archive_urls: for archive_url in archive_urls:
@@ -26,10 +35,10 @@ async def get_archives(username: str) -> list[str]:
async def get_games(username: str, year: str, month: str) -> list[dict]: async def get_games(username: str, year: str, month: str) -> list[dict]:
url = f"{BASE_URL}/player/{quote(username, safe='')}/games/{quote(year, safe='')}/{quote(month, safe='')}" url = f"{BASE_URL}/player/{quote(username, safe='')}/games/{quote(year, safe='')}/{quote(month, safe='')}"
async with httpx.AsyncClient(headers=HEADERS, timeout=30) as client: resp = await _get(url, timeout=30)
resp = await client.get(url)
if resp.status_code == 404: if resp.status_code == 404:
return [] return []
resp.raise_for_status() if resp.status_code != 200:
raise HTTPException(status_code=502, detail=UPSTREAM_ERROR)
games = resp.json().get("games", []) games = resp.json().get("games", [])
return list(reversed(games)) return list(reversed(games))
+4 -12
View File
@@ -11,7 +11,7 @@ from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from app import db, fetch from app import db, fetch
from app.analysis import analyze_pgn from app.analysis import DEFAULT_DEPTH, analyze_pgn
logger = logging.getLogger("chess_analyzer") logger = logging.getLogger("chess_analyzer")
@@ -28,7 +28,6 @@ STATIC_DIR = Path(__file__).parent / "static"
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static") app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
ANALYSIS_CONCURRENCY = int(os.environ.get("ANALYSIS_CONCURRENCY", "2")) ANALYSIS_CONCURRENCY = int(os.environ.get("ANALYSIS_CONCURRENCY", "2"))
MAX_DEPTH = int(os.environ.get("MAX_DEPTH", "20"))
analysis_semaphore = asyncio.Semaphore(ANALYSIS_CONCURRENCY) analysis_semaphore = asyncio.Semaphore(ANALYSIS_CONCURRENCY)
@@ -45,7 +44,6 @@ def _game_id(pgn: str, username: str | None, depth: int) -> str:
class AnalyzeRequest(BaseModel): class AnalyzeRequest(BaseModel):
pgn: str = Field(max_length=65536) pgn: str = Field(max_length=65536)
username: str | None = Field(default=None, max_length=64) username: str | None = Field(default=None, max_length=64)
depth: int | None = None
@app.get("/") @app.get("/")
@@ -82,11 +80,8 @@ async def games(username: str, year: str, month: str):
white = g.get("white", {}) white = g.get("white", {})
black = g.get("black", {}) black = g.get("black", {})
games_out.append({ games_out.append({
"url": g.get("url"),
"end_time": g.get("end_time"), "end_time": g.get("end_time"),
"time_class": g.get("time_class"),
"time_control": g.get("time_control"), "time_control": g.get("time_control"),
"rated": g.get("rated"),
"white": {"username": white.get("username"), "rating": white.get("rating"), "result": white.get("result")}, "white": {"username": white.get("username"), "rating": white.get("rating"), "result": white.get("result")},
"black": {"username": black.get("username"), "rating": black.get("rating"), "result": black.get("result")}, "black": {"username": black.get("username"), "rating": black.get("rating"), "result": black.get("result")},
"pgn": g.get("pgn"), "pgn": g.get("pgn"),
@@ -104,14 +99,11 @@ async def get_game(game_id: str):
@app.post("/api/analyze") @app.post("/api/analyze")
async def analyze(req: AnalyzeRequest): async def analyze(req: AnalyzeRequest):
depth = req.depth or int(os.environ.get("ANALYSIS_DEPTH", "14"))
depth = max(1, min(depth, MAX_DEPTH))
# chess.com usernames are case-insensitive; normalize so "Foo" and "foo" # chess.com usernames are case-insensitive; normalize so "Foo" and "foo"
# hit the same cache entry. # hit the same cache entry.
username = req.username.strip().lower() if req.username else None username = req.username.strip().lower() if req.username else None
game_id = _game_id(req.pgn, username, depth) game_id = _game_id(req.pgn, username, DEFAULT_DEPTH)
cached = await asyncio.to_thread(db.get_game, game_id) cached = await asyncio.to_thread(db.get_game, game_id)
if cached is not None: if cached is not None:
@@ -123,7 +115,7 @@ async def analyze(req: AnalyzeRequest):
if cached is not None: if cached is not None:
return {"id": game_id, **cached} return {"id": game_id, **cached}
try: try:
result = await analyze_pgn(req.pgn, username=username, depth=depth) result = await analyze_pgn(req.pgn, username=username)
except ValueError as e: except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) raise HTTPException(status_code=400, detail=str(e))
except Exception: except Exception:
@@ -133,5 +125,5 @@ async def analyze(req: AnalyzeRequest):
detail="Analysis failed. Check server logs — this is usually a missing/misconfigured Stockfish binary.", detail="Analysis failed. Check server logs — this is usually a missing/misconfigured Stockfish binary.",
) )
await asyncio.to_thread(db.save_game, game_id, username, depth, result) await asyncio.to_thread(db.save_game, game_id, username, result)
return {"id": game_id, **result} return {"id": game_id, **result}
+5 -3
View File
@@ -4,20 +4,20 @@
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Chess.Sistav.com</title> <title>Chess.Sistav.com</title>
<link rel="icon" href="/static/pieces/wN.svg" type="image/svg+xml" /> <link rel="icon" href="/static/pieces/bQ.svg" type="image/svg+xml" />
<link rel="stylesheet" href="/static/style.css" /> <link rel="stylesheet" href="/static/style.css" />
</head> </head>
<body> <body>
<div class="masthead"> <div class="masthead">
<div class="masthead-inner"> <div class="masthead-inner">
<a href="/">Chess.Sistav.com</a> <a href="/" class="brand" aria-label="Chess.Sistav.com"><img src="/static/pieces/bQ.svg" alt="Chess.Sistav.com" width="26" height="26" /></a>
<a href="https://sistav.com">&larr; sistav.com</a> <a href="https://sistav.com">&larr; sistav.com</a>
</div> </div>
</div> </div>
<header> <header>
<a href="/" class="back-link">&larr; Back to games</a>
<h1 id="game-title"></h1> <h1 id="game-title"></h1>
<p id="game-opening" class="subtitle"></p>
</header> </header>
<main> <main>
@@ -26,10 +26,12 @@
<section class="panel" id="analysis-panel" hidden> <section class="panel" id="analysis-panel" hidden>
<div class="analysis-layout"> <div class="analysis-layout">
<div class="board-column"> <div class="board-column">
<div id="top-player" class="player-plate"></div>
<div id="board-wrap"> <div id="board-wrap">
<div id="board"></div> <div id="board"></div>
<svg id="arrows" viewBox="0 0 100 100" preserveAspectRatio="none"></svg> <svg id="arrows" viewBox="0 0 100 100" preserveAspectRatio="none"></svg>
</div> </div>
<div id="bottom-player" class="player-plate"></div>
<div class="nav-row"> <div class="nav-row">
<button id="prev-btn">&larr; Prev</button> <button id="prev-btn">&larr; Prev</button>
<span id="ply-label"></span> <span id="ply-label"></span>
+2 -2
View File
@@ -4,13 +4,13 @@
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Chess.Sistav.com</title> <title>Chess.Sistav.com</title>
<link rel="icon" href="/static/pieces/wN.svg" type="image/svg+xml" /> <link rel="icon" href="/static/pieces/bQ.svg" type="image/svg+xml" />
<link rel="stylesheet" href="/static/style.css" /> <link rel="stylesheet" href="/static/style.css" />
</head> </head>
<body> <body>
<div class="masthead"> <div class="masthead">
<div class="masthead-inner"> <div class="masthead-inner">
<a href="/">Chess.Sistav.com</a> <a href="/" class="brand" aria-label="Chess.Sistav.com"><img src="/static/pieces/bQ.svg" alt="Chess.Sistav.com" width="26" height="26" /></a>
<a href="https://sistav.com">&larr; sistav.com</a> <a href="https://sistav.com">&larr; sistav.com</a>
</div> </div>
</div> </div>
+6 -6
View File
@@ -1,4 +1,5 @@
const STARTING_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR"; // Mirrors MATE_SCORE_CP in app/analysis.py: mate in N plies arrives as ±(100000 − N).
const MATE_SCORE_CP = 100000;
// CBurnett piece set by Colin M.L. Burnett (GPLv2+/BSD/CC BY-SA), // CBurnett piece set by Colin M.L. Burnett (GPLv2+/BSD/CC BY-SA),
// via https://github.com/lichess-org/lila/tree/master/public/piece/cburnett // via https://github.com/lichess-org/lila/tree/master/public/piece/cburnett
@@ -13,7 +14,7 @@ const CLASS_COLORS = {
blunder: "#d64545", blunder: "#d64545",
unknown: "#888888", unknown: "#888888",
}; };
const BEST_MOVE_ARROW_COLOR = "#23242a"; // the editor's ink line const BEST_MOVE_ARROW_COLOR = CLASS_COLORS.best;
const el = (id) => document.getElementById(id); const el = (id) => document.getElementById(id);
@@ -41,9 +42,8 @@ async function apiPost(url, payload) {
function formatEval(cp) { function formatEval(cp) {
if (cp === null || cp === undefined) return "n/a"; if (cp === null || cp === undefined) return "n/a";
// Server encodes "mate in N plies" as ±(100000 - N); render as chess notation. if (Math.abs(cp) > MATE_SCORE_CP - 10000) {
if (Math.abs(cp) > 90000) { const plies = MATE_SCORE_CP - Math.abs(cp);
const plies = 100000 - Math.abs(cp);
const label = plies <= 0 ? "#" : `M${Math.ceil(plies / 2)}`; const label = plies <= 0 ? "#" : `M${Math.ceil(plies / 2)}`;
return (cp > 0 ? "+" : "-") + label; return (cp > 0 ? "+" : "-") + label;
} }
@@ -52,7 +52,7 @@ function formatEval(cp) {
} }
function renderBoard(fen, flip) { function renderBoard(fen, flip) {
const placement = fen.split(" ")[0] || STARTING_FEN; const placement = fen.split(" ")[0];
const rows = placement.split("/"); // rows[0] = rank 8 ... rows[7] = rank 1 const rows = placement.split("/"); // rows[0] = rank 8 ... rows[7] = rank 1
const board = el("board"); const board = el("board");
+39 -13
View File
@@ -17,13 +17,11 @@ async function init() {
setStatus("Loading analysis..."); setStatus("Loading analysis...");
try { try {
analysis = await apiGet(`/api/game/${id}`); analysis = await apiGet(`/api/game/${id}`);
el("game-title").textContent = `${analysis.white} vs ${analysis.black}`; const title = `${analysis.white} vs ${analysis.black}`;
document.title = `${analysis.white} vs ${analysis.black}`; document.title = title;
const back = document.querySelector(".back-link"); el("game-title").replaceChildren(gameLink(title));
if (back && analysis.username) { el("game-opening").textContent = analysis.opening || "";
back.href = `/u/${encodeURIComponent(analysis.username)}`; renderPlayerPlates();
back.textContent = `← Back to ${analysis.username}'s games`;
}
el("analysis-panel").hidden = false; el("analysis-panel").hidden = false;
renderMoveList(); renderMoveList();
renderSummary(); renderSummary();
@@ -36,6 +34,31 @@ async function init() {
} }
} }
// Wraps text in an unstyled link to the game on chess.com when we have one.
// Built with createElement/textContent — player names come from the API.
function gameLink(text) {
if (!analysis.game_url) return document.createTextNode(text);
const a = document.createElement("a");
a.className = "quiet-link";
a.href = analysis.game_url;
a.target = "_blank";
a.rel = "noopener";
a.textContent = text;
return a;
}
// Name plates hug the board: whoever owns the pieces at the top of the board
// gets the top plate, so they follow the flip when the user played black.
function renderPlayerPlates() {
const name = (n, rating) => (rating ? `${n} (${rating})` : n);
const plate = (id, text) => el(id).replaceChildren(gameLink(text));
const flip = analysis.user_color === "black";
plate(flip ? "bottom-player" : "top-player",
name(analysis.black, analysis.black_rating));
plate(flip ? "top-player" : "bottom-player",
name(analysis.white, analysis.white_rating));
}
function renderSummary() { function renderSummary() {
const counts = { best: 0, good: 0, inaccuracy: 0, mistake: 0, blunder: 0 }; const counts = { best: 0, good: 0, inaccuracy: 0, mistake: 0, blunder: 0 };
for (const m of analysis.moves) { for (const m of analysis.moves) {
@@ -150,12 +173,15 @@ function renderEvalGraph() {
// Ink on paper, like a stock listing: the faint shaded area is White's // Ink on paper, like a stock listing: the faint shaded area is White's
// share of the game, the ink line is the story, red dots mark the sins. // share of the game, the ink line is the story, red dots mark the sins.
const PAPER = "#f7f3e8"; // Colors come from the stylesheet's :root variables so the palette has one home.
const INK = "#23242a"; const theme = getComputedStyle(document.documentElement);
const PAPER = theme.getPropertyValue("--paper").trim();
const INK = theme.getPropertyValue("--ink").trim();
const GOLD = theme.getPropertyValue("--gold").trim();
const RED = theme.getPropertyValue("--red").trim();
const HAIRLINE = theme.getPropertyValue("--rule").trim();
const MUTED = theme.getPropertyValue("--muted").trim();
const AREA = "#e7dfc9"; const AREA = "#e7dfc9";
const GOLD = "#a8892e";
const RED = "#9c2b23";
const HAIRLINE = "#c9c2ac";
let curve = ""; let curve = "";
for (const p of graphPts) { for (const p of graphPts) {
@@ -189,7 +215,7 @@ function renderEvalGraph() {
// Hover crosshair + current-position marker. // Hover crosshair + current-position marker.
svg.appendChild(svgEl("line", { svg.appendChild(svgEl("line", {
id: "eval-hover-line", x1: 0, y1: 0, x2: 0, y2: GRAPH.H, id: "eval-hover-line", x1: 0, y1: 0, x2: 0, y2: GRAPH.H,
stroke: "#6b6656", "stroke-width": 1.5, visibility: "hidden", stroke: MUTED, "stroke-width": 1.5, visibility: "hidden",
})); }));
svg.appendChild(svgEl("line", { svg.appendChild(svgEl("line", {
id: "eval-marker-line", x1: 0, y1: 0, x2: 0, y2: GRAPH.H, id: "eval-marker-line", x1: 0, y1: 0, x2: 0, y2: GRAPH.H,
+34 -9
View File
@@ -19,6 +19,13 @@ el("month-select").addEventListener("change", () => {
}); });
el("older-month-btn").addEventListener("click", () => stepMonth(1)); el("older-month-btn").addEventListener("click", () => stepMonth(1));
el("newer-month-btn").addEventListener("click", () => stepMonth(-1)); el("newer-month-btn").addEventListener("click", () => stepMonth(-1));
document.addEventListener("keydown", (e) => {
// Leave the arrow keys alone while the user is moving the caret in the search box.
if (document.activeElement === el("player-search")) return;
if (el("games-panel").hidden) return;
if (e.key === "ArrowLeft") stepMonth(1);
if (e.key === "ArrowRight") stepMonth(-1);
});
function monthLabel(value) { function monthLabel(value) {
const [year, month] = value.split("-"); const [year, month] = value.split("-");
@@ -143,9 +150,13 @@ function renderGamesTable() {
tbody.innerHTML = ""; tbody.innerHTML = "";
currentGames.forEach((game) => { currentGames.forEach((game) => {
const tr = document.createElement("tr"); const tr = document.createElement("tr");
const date = game.end_time ? new Date(game.end_time * 1000).toLocaleDateString() : ""; const cell = (text) => {
const td = document.createElement("td");
td.textContent = text;
tr.appendChild(td);
return td;
};
// Everything from the searched player's point of view.
const whiteIsUser = (game.white.username || "").toLowerCase() === currentUsername; const whiteIsUser = (game.white.username || "").toLowerCase() === currentUsername;
const me = whiteIsUser ? game.white : game.black; const me = whiteIsUser ? game.white : game.black;
const opponent = whiteIsUser ? game.black : game.white; const opponent = whiteIsUser ? game.black : game.white;
@@ -162,13 +173,19 @@ function renderGamesTable() {
} }
const why = me.result === "win" ? "" : (RESULT_REASONS[me.result] || me.result); const why = me.result === "win" ? "" : (RESULT_REASONS[me.result] || me.result);
tr.innerHTML = ` cell(game.end_time ? new Date(game.end_time * 1000).toLocaleDateString() : "");
<td>${date}</td> cell(`${opponent.username} (${opponent.rating ?? "?"})`);
<td>${opponent.username} (${opponent.rating ?? "?"})</td> cell(whiteIsUser ? "White" : "Black");
<td>${whiteIsUser ? "White" : "Black"}</td> const resultTd = cell(verdict);
<td class="${resultClass}">${verdict}${why ? ` <span class="res-why">${why}</span>` : ""}</td> resultTd.className = resultClass;
<td>${formatTimeControl(game.time_control)}</td> if (why) {
`; const span = document.createElement("span");
span.className = "res-why";
span.textContent = why;
resultTd.append(" ", span);
}
cell(formatTimeControl(game.time_control));
tr.addEventListener("click", () => analyzeGame(game, tr)); tr.addEventListener("click", () => analyzeGame(game, tr));
tbody.appendChild(tr); tbody.appendChild(tr);
}); });
@@ -182,6 +199,14 @@ if (bookmarkedUsername) {
let analyzing = false; let analyzing = false;
// Safari restores this page from the back/forward cache exactly as it was when
// we navigated away — busy overlay up and clicks locked out. Reset on return.
window.addEventListener("pageshow", () => {
analyzing = false;
el("busy-overlay").hidden = true;
document.querySelectorAll("tr.analyzing").forEach((tr) => tr.classList.remove("analyzing"));
});
async function analyzeGame(game, row) { async function analyzeGame(game, row) {
if (analyzing) return; if (analyzing) return;
analyzing = true; analyzing = true;
+15 -15
View File
@@ -19,7 +19,7 @@
* { box-sizing: border-box; } * { box-sizing: border-box; }
html { overflow-y: scroll; scrollbar-gutter: stable; } html { scrollbar-gutter: stable; }
body { body {
margin: 0; margin: 0;
@@ -34,10 +34,10 @@ body {
.masthead-inner { .masthead-inner {
max-width: 68rem; max-width: 68rem;
margin: 0 auto; margin: 0 auto;
padding: 0.9rem 1.5rem; padding: 0.6rem 1.5rem;
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: baseline; align-items: center;
gap: 1rem; gap: 1rem;
flex-wrap: wrap; flex-wrap: wrap;
font-variant: small-caps; font-variant: small-caps;
@@ -46,6 +46,7 @@ body {
color: var(--muted); color: var(--muted);
} }
.masthead a { color: var(--ink); text-decoration: none; } .masthead a { color: var(--ink); text-decoration: none; }
.masthead .brand img { height: 26px; display: block; }
.masthead a:hover { color: var(--gold); } .masthead a:hover { color: var(--gold); }
header { padding: 1.5rem 1.5rem 0; text-align: center; } header { padding: 1.5rem 1.5rem 0; text-align: center; }
@@ -53,24 +54,15 @@ header { padding: 1.5rem 1.5rem 0; text-align: center; }
h1 { h1 {
font-weight: 700; font-weight: 700;
font-style: italic; font-style: italic;
font-size: clamp(1.7rem, 4vw, 2.5rem); font-size: clamp(1.45rem, 3.2vw, 2.1rem);
line-height: 1.15; line-height: 1.15;
margin: 0 0 0.35rem; margin: 0 0 0.35rem;
text-wrap: balance; text-wrap: balance;
} }
.subtitle { margin: 0; color: var(--muted); font-style: italic; font-size: 1rem; } .subtitle { margin: 0; color: var(--muted); font-style: italic; font-size: 1rem; }
.subtitle b, .subtitle strong { color: var(--gold); font-style: normal; }
.back-link { .quiet-link { color: inherit; text-decoration: none; }
display: inline-block; .quiet-link:hover { color: var(--gold); }
color: var(--muted);
text-decoration: none;
font-variant: small-caps;
letter-spacing: 0.14em;
font-size: 0.85rem;
margin-bottom: 0.5rem;
}
.back-link:hover { color: var(--gold); }
main { main {
padding: 0.75rem 1.5rem 3rem; padding: 0.75rem 1.5rem 3rem;
@@ -196,6 +188,14 @@ tbody tr.analyzing { background: var(--paper-shade); font-style: italic; cursor:
aspect-ratio: 1; aspect-ratio: 1;
} }
.player-plate {
width: 560px;
max-width: 90vw;
font-size: 1rem;
}
#top-player { margin-bottom: 0.4rem; }
#bottom-player { margin-top: 0.4rem; }
#board { #board {
position: absolute; position: absolute;
inset: 0; inset: 0;
+1 -1
View File
@@ -1,4 +1,4 @@
fastapi==0.115.6 fastapi==0.115.6
uvicorn[standard]==0.32.1 uvicorn[standard]==0.32.1
httpx==0.28.1 httpx==0.28.1
python-chess==1.999 chess==1.11.2