BlueGit

projects-timfalken-com microchess

Add permanent compact game history and replay controls

timfa Tim Falken · pushed by timfa

Authored 2026-09-10 · 2 months ago

Hash
a7932f260644a57b4c3f3009814f8c244cc75948
Parent
35438118
7 files changed +243 −14
web/README.md +6 −0
@@ -147,3 +147,9 @@ node web/tests/browser.mjs
147 147 ```
148 148
149 149 The feedback tests cover free and poisoned captures, exchanges, mate, allowing mate, promotion, both colors, draws, budget exhaustion and a small reproducible timing sample. Browser tests exercise real feedback through the API, one-time animation and reduced motion in an isolated application copy.
150
151 ## Saved games
152
153 Games newly entering Your turn go to the end of the queue; the ordering survives reloads. The account summary’s hourglass opens finished games, newest first, showing opponent, outcome and end date. Both players retain access after exiting a tile or starting a rematch. Replay uses the same board orientation and tile styling, with Back/Next stepping one ply (double-click for beginning/end), and Play/Pause advancing every 500 ms. Closing the dialog stops playback. A saved result animates once per player/browser toward the hourglass; reduced-motion preferences suppress motion.
154
155 Replays store the initial position plus two binary bytes per ply, including promotions, separately from permanent result/rating statistics. Saved games have no retention limit and are not automatically deleted based on age. Existing finished tiles can be imported when their original color and complete history are still available. Older rematches whose color was overwritten cannot be reconstructed reliably and are not imported. Data exports include available replay positions. No scheduled worker is required.
@@ -147,3 +147,9 @@ node web/tests/browser.mjs
147```
147```
148
148
149The feedback tests cover free and poisoned captures, exchanges, mate, allowing mate, promotion, both colors, draws, budget exhaustion and a small reproducible timing sample. Browser tests exercise real feedback through the API, one-time animation and reduced motion in an isolated application copy.
149The feedback tests cover free and poisoned captures, exchanges, mate, allowing mate, promotion, both colors, draws, budget exhaustion and a small reproducible timing sample. Browser tests exercise real feedback through the API, one-time animation and reduced motion in an isolated application copy.
150
151## Saved games
152
153Games newly entering Your turn go to the end of the queue; the ordering survives reloads. The account summary’s hourglass opens finished games, newest first, showing opponent, outcome and end date. Both players retain access after exiting a tile or starting a rematch. Replay uses the same board orientation and tile styling, with Back/Next stepping one ply (double-click for beginning/end), and Play/Pause advancing every 500 ms. Closing the dialog stops playback. A saved result animates once per player/browser toward the hourglass; reduced-motion preferences suppress motion.
154
155Replays store the initial position plus two binary bytes per ply, including promotions, separately from permanent result/rating statistics. Saved games have no retention limit and are not automatically deleted based on age. Existing finished tiles can be imported when their original color and complete history are still available. Older rematches whose color was overwritten cannot be reconstructed reliably and are not imported. Data exports include available replay positions. No scheduled worker is required.
web/api.php +17 −0
@@ -12,6 +12,22 @@ try {
12 12 $method=$_SERVER['REQUEST_METHOD'];
13 13 if ($method==='GET') {
14 14 $action=$_GET['action']??'state';
15 if ($action==='history' || $action==='replay') {
16 $rows=query('SELECT r.id,r.game_id,r.a,r.b,r.winner,r.reason,r.ended,p.white FROM results r JOIN replays p ON p.result_id=r.id WHERE (r.a=? OR r.b=?) ORDER BY r.ended DESC,r.id DESC',[$u,$u])->fetchAll();
17 $items=[];
18 foreach ($rows as $r) {
19 if ($action==='replay' && $r['id']!==(int)($_GET['id']??0)) continue;
20 $op=profile($r['a']===$u?$r['b']:$r['a']);
21 $item=['id'=>(int)$r['id'],'opponent'=>$op['name'],'opponentId'=>$op['id'],'opponentAvatar'=>$op['avatar'],'opponentRating'=>$op['rating'],'color'=>$r['white']===$u?'w':'b','outcome'=>$r['winner']===null?'draw':($r['winner']===$u?'win':'loss'),'ended'=>(int)$r['ended'],'reason'=>$r['reason']];
22 if ($action==='replay') {
23 $item['positions']=replayPositions(query('SELECT moves FROM replays WHERE result_id=?',[$r['id']])->fetchColumn());
24 jsonOut($item);
25 }
26 $items[]=$item;
27 }
28 if ($action==='replay') fail('Saved game not found.',404);
29 jsonOut($items);
30 }
15 31 if ($action==='export') {
16 32 header('Content-Disposition: attachment; filename="microchess-data.json"');
17 33 jsonOut(['exported_at'=>gmdate('c'),'profile'=>profile($u),
@@ -21,6 +37,7 @@ try {
21 37 'matchmaking'=>query('SELECT * FROM matchmaking WHERE user_id=?',[$u])->fetchAll(),
22 38 'rating_changes'=>query('SELECT c.* FROM rating_changes c JOIN results r ON r.id=c.result_id WHERE r.a=? OR r.b=?',[$u,$u])->fetchAll(),
23 39 'games'=>query('SELECT * FROM games WHERE a=? OR b=?',[$u,$u])->fetchAll(),
40 'replays'=>array_map(fn($r)=>['id'=>$r['result_id'],'white'=>$r['white'],'positions'=>replayPositions($r['moves'])],query('SELECT p.* FROM replays p JOIN results r ON r.id=p.result_id WHERE r.a=? OR r.b=?',[$u,$u])->fetchAll()),
24 41 'results'=>query('SELECT * FROM results WHERE a=? OR b=?',[$u,$u])->fetchAll()]);
25 42 }
26 43 if ($action!=='state') fail('Unknown action.',404);
@@ -12,6 +12,22 @@ try {
12 $method=$_SERVER['REQUEST_METHOD'];
12 $method=$_SERVER['REQUEST_METHOD'];
13 if ($method==='GET') {
13 if ($method==='GET') {
14 $action=$_GET['action']??'state';
14 $action=$_GET['action']??'state';
15 if ($action==='history' || $action==='replay') {
16 $rows=query('SELECT r.id,r.game_id,r.a,r.b,r.winner,r.reason,r.ended,p.white FROM results r JOIN replays p ON p.result_id=r.id WHERE (r.a=? OR r.b=?) ORDER BY r.ended DESC,r.id DESC',[$u,$u])->fetchAll();
17 $items=[];
18 foreach ($rows as $r) {
19 if ($action==='replay' && $r['id']!==(int)($_GET['id']??0)) continue;
20 $op=profile($r['a']===$u?$r['b']:$r['a']);
21 $item=['id'=>(int)$r['id'],'opponent'=>$op['name'],'opponentId'=>$op['id'],'opponentAvatar'=>$op['avatar'],'opponentRating'=>$op['rating'],'color'=>$r['white']===$u?'w':'b','outcome'=>$r['winner']===null?'draw':($r['winner']===$u?'win':'loss'),'ended'=>(int)$r['ended'],'reason'=>$r['reason']];
22 if ($action==='replay') {
23 $item['positions']=replayPositions(query('SELECT moves FROM replays WHERE result_id=?',[$r['id']])->fetchColumn());
24 jsonOut($item);
25 }
26 $items[]=$item;
27 }
28 if ($action==='replay') fail('Saved game not found.',404);
29 jsonOut($items);
30 }
15 if ($action==='export') {
31 if ($action==='export') {
16 header('Content-Disposition: attachment; filename="microchess-data.json"');
32 header('Content-Disposition: attachment; filename="microchess-data.json"');
17 jsonOut(['exported_at'=>gmdate('c'),'profile'=>profile($u),
33 jsonOut(['exported_at'=>gmdate('c'),'profile'=>profile($u),
@@ -21,6 +37,7 @@ try {
21 'matchmaking'=>query('SELECT * FROM matchmaking WHERE user_id=?',[$u])->fetchAll(),
37 'matchmaking'=>query('SELECT * FROM matchmaking WHERE user_id=?',[$u])->fetchAll(),
22 'rating_changes'=>query('SELECT c.* FROM rating_changes c JOIN results r ON r.id=c.result_id WHERE r.a=? OR r.b=?',[$u,$u])->fetchAll(),
38 'rating_changes'=>query('SELECT c.* FROM rating_changes c JOIN results r ON r.id=c.result_id WHERE r.a=? OR r.b=?',[$u,$u])->fetchAll(),
23 'games'=>query('SELECT * FROM games WHERE a=? OR b=?',[$u,$u])->fetchAll(),
39 'games'=>query('SELECT * FROM games WHERE a=? OR b=?',[$u,$u])->fetchAll(),
40 'replays'=>array_map(fn($r)=>['id'=>$r['result_id'],'white'=>$r['white'],'positions'=>replayPositions($r['moves'])],query('SELECT p.* FROM replays p JOIN results r ON r.id=p.result_id WHERE r.a=? OR r.b=?',[$u,$u])->fetchAll()),
24 'results'=>query('SELECT * FROM results WHERE a=? OR b=?',[$u,$u])->fetchAll()]);
41 'results'=>query('SELECT * FROM results WHERE a=? OR b=?',[$u,$u])->fetchAll()]);
25 }
42 }
26 if ($action!=='state') fail('Unknown action.',404);
43 if ($action!=='state') fail('Unknown action.',404);
web/assets/app.css +9 −0
@@ -1415,3 +1415,12 @@ dialog .avatar-credits {
1415 1415 .friend-request strong { overflow-wrap: anywhere; font-size: 13px; }
1416 1416 .friend-request .actions { margin-top: 8px; flex-wrap: wrap; }
1417 1417 .friend-request button { padding: 7px 10px; font-size: 12px; }
1418
1419 #history-button { margin-left: auto; flex-shrink: 0; font-size: 22px; }
1420 .history-list { display: grid; gap: 8px; max-height: 65vh; overflow-y: auto; }
1421 .history-entry { display: grid; grid-template-columns: 1fr auto auto; gap: 14px; align-items: center; text-align: left; }
1422 .history-entry strong { overflow-wrap: anywhere; }
1423 dialog.replay-modal { width: min(400px, calc(100vw - 24px)); }
1424 .replay-controls { display: flex; justify-content: space-between; gap: 12px; margin-top: 18px; }
1425 #replay-progress { font-size: 12px; text-align: center; }
1426 .saved-hourglass { position: fixed; z-index: 100; pointer-events: none; font-size: 24px; }
@@ -1415,3 +1415,12 @@ dialog .avatar-credits {
1415.friend-request strong { overflow-wrap: anywhere; font-size: 13px; }
1415.friend-request strong { overflow-wrap: anywhere; font-size: 13px; }
1416.friend-request .actions { margin-top: 8px; flex-wrap: wrap; }
1416.friend-request .actions { margin-top: 8px; flex-wrap: wrap; }
1417.friend-request button { padding: 7px 10px; font-size: 12px; }
1417.friend-request button { padding: 7px 10px; font-size: 12px; }
1418
1419#history-button { margin-left: auto; flex-shrink: 0; font-size: 22px; }
1420.history-list { display: grid; gap: 8px; max-height: 65vh; overflow-y: auto; }
1421.history-entry { display: grid; grid-template-columns: 1fr auto auto; gap: 14px; align-items: center; text-align: left; }
1422.history-entry strong { overflow-wrap: anywhere; }
1423dialog.replay-modal { width: min(400px, calc(100vw - 24px)); }
1424.replay-controls { display: flex; justify-content: space-between; gap: 12px; margin-top: 18px; }
1425#replay-progress { font-size: 12px; text-align: center; }
1426.saved-hourglass { position: fixed; z-index: 100; pointer-events: none; font-size: 24px; }
web/assets/app.js +106 −12
@@ -40,12 +40,13 @@ let moveHoldTimer;
40 40 let inviteToken = new URLSearchParams(location.search).get('invite');
41 41 const modal = $('#modal');
42 42 function toast (message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 5000); }
43 function showModal (html) { delete $('#modal-content').dataset.rivalry; modal.classList.remove('avatar-picker'); $('#modal-content').innerHTML = html; if (!modal.open) modal.showModal(); }
44 function closeModal () { modal.close(); }
43 function showModal (html) { delete $('#modal-content').dataset.rivalry; stopReplay(); modal.classList.remove('avatar-picker', 'replay-modal'); $('#modal-content').innerHTML = html; if (!modal.open) modal.showModal(); }
44 function clearReplay () { stopReplay(); if (modal.classList.contains('replay-modal')) { $('#modal-content').innerHTML = ''; modal.classList.remove('replay-modal'); } }
45 function closeModal () { clearReplay(); modal.close(); }
45 46 $('#modal-close').onclick = closeModal;
46 47 modal.addEventListener('click', e => { if (e.target === modal) { const r = modal.getBoundingClientRect(); if (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom) closeModal(); } });
47 48 function dismissInvite () { inviteToken = null; history.replaceState(null, '', location.pathname); }
48 modal.addEventListener('close', () => { if (inviteShown) dismissInvite(); });
49 modal.addEventListener('close', () => { if (!modal.open) clearReplay(); if (inviteShown) dismissInvite(); });
49 50 const mobileLayout = matchMedia('(max-width: 760px)');
50 51 function showSidebar (open)
51 52 {
@@ -56,7 +57,7 @@ function showSidebar (open)
56 57 $('#friends-toggle').setAttribute('aria-expanded', String(open));
57 58 $('#main').inert = mobileLayout.matches && open;
58 59 document.body.classList.toggle('sidebar-open', mobileLayout.matches && open);
59 if (open) $('#friends-close').focus();
60 if (open) { $('#friends-close').focus(); animateSavedGames(); }
60 61 else if (mobileLayout.matches) $('#friends-toggle').focus();
61 62 }
62 63 mobileLayout.addEventListener('change', () => showSidebar(false));
@@ -78,7 +79,7 @@ async function action (data, success)
78 79 const result = await api(data);
79 80 if (data.action === 'move')
80 81 {
81 moveHolds.set(data.game, { user: state.user.id, version: data.version, until: null });
82 moveHolds.set(data.game, { user: state.user.id, version: data.version, turnOrder: state.games.find(g => g.id === data.game)?.turnOrder, until: null });
82 83 if (['good', 'poor'].includes(result.feedback?.quality)) moveFeedback.set(data.game, { user: state.user.id, ply: result.feedback.ply, quality: result.feedback.quality, start: null });
83 84 }
84 85 selected = null; promotion = null; if (success) await success(result); await refresh(true);
@@ -98,7 +99,7 @@ async function refresh (force = false)
98 99 state = data;
99 100 if (selected) { const g = state.games.find(g => g.id === selected.game); if (!g?.yourTurn || g.version !== selected.version) { selected = null; promotion = null; } }
100 101 const signature = JSON.stringify(data);
101 if (signature !== lastRender) { lastRender = signature; renderGames(); renderFriends(); renderMatchmaking(); refreshRivalry(); }
102 if (signature !== lastRender) { lastRender = signature; renderGames(); renderFriends(); renderMatchmaking(); refreshRivalry(); animateSavedGames(); }
102 103 if (data.invite && !inviteShown)
103 104 {
104 105 inviteShown = true; const i = data.invite;
@@ -127,16 +128,16 @@ function renderGames ()
127 128 }
128 129 const deadlines = [...moveHolds.values()].filter(h => h.until !== null).map(h => h.until);
129 130 if (deadlines.length) moveHoldTimer = setTimeout(renderGames, Math.max(drag ? 100 : 1, Math.min(...deadlines) - now));
130 const selector = '.game-card, .waiting-heading, #main > footer';
131 const selector = '#main .game-card, .waiting-heading, #main > footer';
131 132 const key = el => el.dataset.game || el.tagName;
132 133 const animate = !matchMedia('(prefers-reduced-motion: reduce)').matches &&
133 134 (relocating || [...document.querySelectorAll(selector)].some(el => el.getAnimations().length));
134 135 const before = new Map(animate ? [...document.querySelectorAll(selector)].map(el => [key(el), el.getBoundingClientRect()]) : []);
135 const yours = state.games.filter(g => g.yourTurn || g.status === 'ended' || g.status === 'pending' && g.incoming || moveHolds.has(g.id));
136 const yours = state.games.filter(g => g.yourTurn || g.status === 'ended' || g.status === 'pending' && g.incoming || moveHolds.has(g.id)).sort((a, b) => (moveHolds.get(a.id)?.turnOrder ?? a.turnOrder) - (moveHolds.get(b.id)?.turnOrder ?? b.turnOrder) || a.id - b.id);
136 137 const waiting = state.games.filter(g => !yours.includes(g));
137 138 $('#your-count').textContent = yours.length; $('#waiting-count').textContent = waiting.length + (state.matchmaking ? 1 : 0);
138 139 // Continue from the visible fill even when polling/selection recreates the cards mid-animation.
139 const materialBefore = new Map([...document.querySelectorAll('.material-bar')].map(el =>
140 const materialBefore = new Map([...document.querySelectorAll('#main .material-bar')].map(el =>
140 141 {
141 142 const fill = $('.material-white', el), animation = fill.getAnimations()[0];
142 143 return [el.closest('[data-game]').dataset.game, { share: new DOMMatrixReadOnly(getComputedStyle(fill).transform).a, target: el.dataset.share, remaining: animation ? Math.max(0, 650 - Number(animation.currentTime)) : 650 }];
@@ -144,7 +145,7 @@ function renderGames ()
144 145 $('#your-games').innerHTML = yours.map(card).join('') || empty(true);
145 146 $('#waiting-games').innerHTML = (state.matchmaking ? matchmakingCard() : '') + waiting.map(card).join('') || empty(false);
146 147 const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
147 for (const el of document.querySelectorAll('.material-bar'))
148 for (const el of document.querySelectorAll('#main .material-bar'))
148 149 {
149 150 const fill = $('.material-white', el), share = Number(el.dataset.share), old = materialBefore.get(el.closest('[data-game]').dataset.game);
150 151 fill.style.transform = `scaleX(${share})`;
@@ -170,7 +171,8 @@ function renderGames ()
170 171 function card (g)
171 172 {
172 173 let content = '';
173 if (g.status === 'pending') content = `<div class="pending-content"><span class="big-icon">♘</span><h3>${g.incoming ? 'A little challenge?' : 'Challenge sent.'}</h3><p>${g.incoming ? `${esc(g.opponent)} invited you to play.<br>Your board is waiting.` : `Waiting for ${esc(g.opponent)}<br>to accept your challenge.`}</p>${g.incoming ? `<div class="actions"><button class="primary" data-game-action="accept">Accept</button><button class="secondary" data-game-action="reject">Reject</button></div>` : '<span class="inline-note"></span>'}</div>`;
174 if (g.replay) content = board(g);
175 else if (g.status === 'pending') content = `<div class="pending-content"><span class="big-icon">♘</span><h3>${g.incoming ? 'A little challenge?' : 'Challenge sent.'}</h3><p>${g.incoming ? `${esc(g.opponent)} invited you to play.<br>Your board is waiting.` : `Waiting for ${esc(g.opponent)}<br>to accept your challenge.`}</p>${g.incoming ? `<div class="actions"><button class="primary" data-game-action="accept">Accept</button><button class="secondary" data-game-action="reject">Reject</button></div>` : '<span class="inline-note"></span>'}</div>`;
174 176 else if (g.status === 'ended') content = `<div class="ended-board">${board(g)}<div class="end-content"><div class="end-status"><h3>${g.outcome === 'win' ? 'You won!' : g.outcome === 'loss' ? 'You lost' : 'A game well matched.'}</h3><small>${esc(g.reason)}</small>${g.opponentRematch && g.canRematch ? `<small>${esc(g.opponent)} wants a rematch.</small>` : ''}</div><div class="actions">${g.canRematch ? `<button class="primary" data-game-action="rematch" ${g.rematch ? 'disabled' : ''}>${g.rematch ? 'Requested' : 'Rematch'}</button>` : ''}<button class="secondary" data-game-action="exit">Exit</button></div></div></div>`;
175 177 else content = board(g) + `<div class="card-footer"><span class="${g.yourTurn ? 'turn-label' : ''}">${g.check ? 'Check · ' : ''}${g.yourTurn ? 'Your move' : 'Waiting for a move'}</span>${g.yourTurn ? `<button class="text-button" data-game-action="options" aria-label="Game options">${g.drawOffer === 'opponent' ? 'Draw offered · ' : ''}•••</button>` : `<span>Move ${Math.floor(g.state.ply / 2) + 1}</span>`}</div>`;
176 178 return `<article class="game-card ${!g.yourTurn && g.status === 'active' ? 'waiting' : ''}" data-game="${g.id}" aria-label="Game with ${esc(g.opponent)}"><div class="card-header">${avatarMarkup(g.opponent, g.opponentAvatar)}<div class="opponent-info"><strong><button class="opponent-name" data-opponent="${esc(g.opponentId)}">${esc(g.opponent)}</button> <small class="rating" aria-label="${g.opponentRating} Elo">${g.opponentRating}</small></strong>${g.status !== 'pending' ? materialBar(g) : ''}</div>${g.status !== 'pending' ? `<span class="color-tag"><span class="color-disc ${g.color === 'b' ? 'black' : ''}"></span>${g.color === 'w' ? 'White' : 'Black'}</span>` : ''}${g.inactiveDays >= 7 ? '<button class="stop-inactive" data-game-action="stop-confirm" aria-label="Stop inactive game" title="Stop inactive game">×</button>' : ''}</div>${content}</article>`;
@@ -238,7 +240,7 @@ function renderFriends ()
238 240 const incoming = state.friendRequests.filter(r => r.incoming);
239 241 $('#friend-requests').innerHTML = incoming.length ? '<div class="friends-label">PENDING REQUESTS</div>' + incoming.map(r => `<div class="friend-request">${avatarMarkup(r.name, r.avatar)}<div><strong>${esc(r.name)}</strong><div class="actions"><button class="primary" data-request-action="accept_friend_request" data-request-user="${esc(r.id)}">Accept</button><button class="secondary" data-request-action="reject_friend_request" data-request-user="${esc(r.id)}">Reject</button></div></div></div>`).join('') : '';
240 242 $('#friend-count').textContent = state.friends.length + incoming.length;
241 $('#account-summary').innerHTML = `${avatarMarkup(state.user.name, state.user.avatar, true)}<span>${esc(state.user.name)}<small>${state.user.rating} Elo</small></span>`;
243 $('#account-summary').innerHTML = `${avatarMarkup(state.user.name, state.user.avatar, true)}<span>${esc(state.user.name)}<small>${state.user.rating} Elo</small></span><button id="history-button" class="text-button" aria-label="Game history" title="Game history">⌛</button>`;
242 244 }
243 245 function showRivalry (id)
244 246 {
@@ -305,6 +307,7 @@ document.addEventListener('click', e =>
305 307 const gameEl = el.closest('[data-game]'); const g = gameEl && state?.games.find(g => g.id === Number(gameEl.dataset.game));
306 308 if (el.dataset.requestAction) action({ action: el.dataset.requestAction, friend: el.dataset.requestUser }, () => { if (modal.open) closeModal(); toast(el.dataset.requestAction === 'send_friend_request' ? 'Friend request sent.' : el.dataset.requestAction === 'accept_friend_request' ? 'Friend request accepted.' : 'Friend request rejected.'); });
307 309 if (el.dataset.matchmaking) action({ action: el.dataset.matchmaking }, () => { if (modal.open) closeModal(); });
310 if (el.id === 'history-button') showHistory();
308 311 if (el.id === 'avatar-button') chooseAvatar();
309 312 if (el.dataset.createLink) createLink(el.dataset.createLink);
310 313 if (el.hasAttribute('data-square') && g) { if (suppressClick) { suppressClick = false; return; } chooseSquare(g, Number(el.dataset.square)); }
@@ -360,3 +363,94 @@ document.addEventListener('pointerup', e =>
360 363 });
361 364 document.addEventListener('pointercancel', () => { drag = null; $('.drag-ghost')?.remove(); });
362 365 refresh(); setInterval(() => { if (!document.hidden) refresh(); }, 2500); document.addEventListener('visibilitychange', () => { if (!document.hidden) refresh(); });
366
367 let replay = null, replayTimer = null, historyRequest = 0;
368 function stopReplay () { clearInterval(replayTimer); replayTimer = null; }
369 async function historyFetch (query)
370 {
371 const response = await fetch('api.php?action=' + query);
372 const data = await response.json();
373 if (!response.ok) throw new Error(data.error || 'Unable to load saved games.');
374 return data;
375 }
376 async function showHistory ()
377 {
378 const request = ++historyRequest;
379 showModal('<h2 id="modal-title">Game history</h2><p>Loading saved games…</p>');
380 try {
381 const games = await historyFetch('history');
382 if (request !== historyRequest || !modal.open || $('#modal-title')?.textContent !== 'Game history') return;
383 $('#modal-content').innerHTML = `<h2 id="modal-title">Game history</h2><div class="history-list">${games.map(g => `<button class="secondary history-entry" data-replay-id="${g.id}"><strong>${esc(g.opponent)}</strong><span>${g.outcome === 'win' ? 'Won' : g.outcome === 'loss' ? 'Lost' : 'Draw'}</span><time datetime="${new Date(g.ended * 1000).toISOString()}">${esc(new Date(g.ended * 1000).toLocaleDateString())}</time></button>`).join('') || '<p>No saved games yet.</p>'}</div>`;
384 } catch (e) { toast(e.message); }
385 }
386 async function openReplay (id)
387 {
388 const source = $('#modal-content').firstElementChild;
389 const request = ++historyRequest;
390 try {
391 const game = await historyFetch('replay&id=' + id);
392 if (request !== historyRequest || !modal.open || source !== $('#modal-content').firstElementChild) return;
393 showModal('<div id="replay-card"></div><div class="replay-controls"><button class="secondary" data-replay-control="back" title="Double-click to jump to the beginning">Back</button><button class="primary" data-replay-control="play">Play</button><button class="secondary" data-replay-control="next" title="Double-click to jump to the end">Next</button></div><p id="replay-progress" aria-live="polite"></p><button class="text-button" id="history-return">← Game history</button>');
394 modal.classList.add('replay-modal');
395 replay = { ...game, index: 0 };
396 renderReplay();
397 } catch (e) { toast(e.message); }
398 }
399 function renderReplay ()
400 {
401 if (!replay || !$('#replay-card')) return;
402 const g = { ...replay, id: 'replay', replay: true, status: 'replay', yourTurn: false, legal: [], check: false, state: replay.positions[replay.index] };
403 $('#replay-card').innerHTML = card(g);
404 const material = $('#replay-card .material-bar');
405 $('.material-white', material).style.transform = `scaleX(${material.dataset.share})`;
406 $('#replay-progress').textContent = `${replay.index} / ${replay.positions.length - 1} · ${replay.outcome === 'win' ? 'Won' : replay.outcome === 'loss' ? 'Lost' : 'Draw'} · ${replay.reason}`;
407 $('[data-replay-control="play"]').textContent = replayTimer ? 'Pause' : 'Play';
408 $('[data-replay-control="play"]').disabled = replay.positions.length < 2;
409 }
410 $('#modal-content').addEventListener('click', e => {
411 const b = e.target.closest('button'); if (!b) return;
412 if (b.dataset.replayId) openReplay(b.dataset.replayId);
413 if (b.id === 'history-return') showHistory();
414 const control = b.dataset.replayControl;
415 if (!control || !replay) return;
416 if (control === 'play') {
417 if (replayTimer) stopReplay();
418 else {
419 if (replay.index === replay.positions.length - 1) replay.index = 0;
420 replayTimer = setInterval(() => {
421 replay.index++;
422 if (replay.index >= replay.positions.length - 1) stopReplay();
423 renderReplay();
424 }, 500);
425 }
426 } else {
427 stopReplay();
428 replay.index = Math.max(0, Math.min(replay.positions.length - 1, replay.index + (control === 'back' ? -1 : 1)));
429 }
430 renderReplay();
431 });
432 $('#modal-content').addEventListener('dblclick', e => {
433 const control = e.target.closest('button')?.dataset.replayControl;
434 if (!replay || !['back', 'next'].includes(control)) return;
435 stopReplay(); replay.index = control === 'back' ? 0 : replay.positions.length - 1; renderReplay();
436 });
437 const savedAnimations = new Set();
438 function animateSavedGames ()
439 {
440 for (const g of state.games) {
441 if (!g.replayId) continue;
442 const key = `microchess-saved:${state.user.id}:${g.replayId}`;
443 let seen = savedAnimations.has(key);
444 try { seen ||= localStorage.getItem(key) === '1'; } catch {}
445 const tile = $(`#your-games [data-game="${g.id}"]`), target = $('#history-button');
446 if (seen || !tile || !target || !target.getBoundingClientRect().width) continue;
447 savedAnimations.add(key);
448 try { localStorage.setItem(key, '1'); } catch {}
449 if (matchMedia('(prefers-reduced-motion: reduce)').matches) continue;
450 const start = tile.getBoundingClientRect(), end = target.getBoundingClientRect();
451 const icon = document.createElement('span'); icon.className = 'saved-hourglass'; icon.textContent = '⌛'; icon.setAttribute('aria-hidden', 'true');
452 icon.style.left = `${start.left + start.width / 2 - 12}px`; icon.style.top = `${start.top + 45}px`; document.body.append(icon);
453 const flight = icon.animate([{ opacity: 0, transform: 'translate(0,0) scale(.5)' }, { opacity: 1, transform: 'translate(0,0) scale(1)', offset: .2 }, { opacity: 0, transform: `translate(${end.left + end.width / 2 - start.left - start.width / 2}px,${end.top + end.height / 2 - start.top - 57}px) scale(.5)` }], { duration: 1100, easing: 'cubic-bezier(.4,0,.2,1)' });
454 flight.onfinish = () => { icon.remove(); $('#history-button')?.animate([{ transform: 'translateY(0)' }, { transform: 'translateY(-9px)' }, { transform: 'translateY(0)' }], { duration: 360, easing: 'ease-out' }); };
455 }
456 }
@@ -40,12 +40,13 @@ let moveHoldTimer;
40let inviteToken = new URLSearchParams(location.search).get('invite');
40let inviteToken = new URLSearchParams(location.search).get('invite');
41const modal = $('#modal');
41const modal = $('#modal');
42function toast (message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 5000); }
42function toast (message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 5000); }
43function showModal (html) { delete $('#modal-content').dataset.rivalry; modal.classList.remove('avatar-picker'); $('#modal-content').innerHTML = html; if (!modal.open) modal.showModal(); }
43function showModal (html) { delete $('#modal-content').dataset.rivalry; stopReplay(); modal.classList.remove('avatar-picker', 'replay-modal'); $('#modal-content').innerHTML = html; if (!modal.open) modal.showModal(); }
44function closeModal () { modal.close(); }
44function clearReplay () { stopReplay(); if (modal.classList.contains('replay-modal')) { $('#modal-content').innerHTML = ''; modal.classList.remove('replay-modal'); } }
45function closeModal () { clearReplay(); modal.close(); }
45$('#modal-close').onclick = closeModal;
46$('#modal-close').onclick = closeModal;
46modal.addEventListener('click', e => { if (e.target === modal) { const r = modal.getBoundingClientRect(); if (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom) closeModal(); } });
47modal.addEventListener('click', e => { if (e.target === modal) { const r = modal.getBoundingClientRect(); if (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom) closeModal(); } });
47function dismissInvite () { inviteToken = null; history.replaceState(null, '', location.pathname); }
48function dismissInvite () { inviteToken = null; history.replaceState(null, '', location.pathname); }
48modal.addEventListener('close', () => { if (inviteShown) dismissInvite(); });
49modal.addEventListener('close', () => { if (!modal.open) clearReplay(); if (inviteShown) dismissInvite(); });
49const mobileLayout = matchMedia('(max-width: 760px)');
50const mobileLayout = matchMedia('(max-width: 760px)');
50function showSidebar (open)
51function showSidebar (open)
51{
52{
@@ -56,7 +57,7 @@ function showSidebar (open)
56 $('#friends-toggle').setAttribute('aria-expanded', String(open));
57 $('#friends-toggle').setAttribute('aria-expanded', String(open));
57 $('#main').inert = mobileLayout.matches && open;
58 $('#main').inert = mobileLayout.matches && open;
58 document.body.classList.toggle('sidebar-open', mobileLayout.matches && open);
59 document.body.classList.toggle('sidebar-open', mobileLayout.matches && open);
59 if (open) $('#friends-close').focus();
60 if (open) { $('#friends-close').focus(); animateSavedGames(); }
60 else if (mobileLayout.matches) $('#friends-toggle').focus();
61 else if (mobileLayout.matches) $('#friends-toggle').focus();
61}
62}
62mobileLayout.addEventListener('change', () => showSidebar(false));
63mobileLayout.addEventListener('change', () => showSidebar(false));
@@ -78,7 +79,7 @@ async function action (data, success)
78 const result = await api(data);
79 const result = await api(data);
79 if (data.action === 'move')
80 if (data.action === 'move')
80 {
81 {
81 moveHolds.set(data.game, { user: state.user.id, version: data.version, until: null });
82 moveHolds.set(data.game, { user: state.user.id, version: data.version, turnOrder: state.games.find(g => g.id === data.game)?.turnOrder, until: null });
82 if (['good', 'poor'].includes(result.feedback?.quality)) moveFeedback.set(data.game, { user: state.user.id, ply: result.feedback.ply, quality: result.feedback.quality, start: null });
83 if (['good', 'poor'].includes(result.feedback?.quality)) moveFeedback.set(data.game, { user: state.user.id, ply: result.feedback.ply, quality: result.feedback.quality, start: null });
83 }
84 }
84 selected = null; promotion = null; if (success) await success(result); await refresh(true);
85 selected = null; promotion = null; if (success) await success(result); await refresh(true);
@@ -98,7 +99,7 @@ async function refresh (force = false)
98 state = data;
99 state = data;
99 if (selected) { const g = state.games.find(g => g.id === selected.game); if (!g?.yourTurn || g.version !== selected.version) { selected = null; promotion = null; } }
100 if (selected) { const g = state.games.find(g => g.id === selected.game); if (!g?.yourTurn || g.version !== selected.version) { selected = null; promotion = null; } }
100 const signature = JSON.stringify(data);
101 const signature = JSON.stringify(data);
101 if (signature !== lastRender) { lastRender = signature; renderGames(); renderFriends(); renderMatchmaking(); refreshRivalry(); }
102 if (signature !== lastRender) { lastRender = signature; renderGames(); renderFriends(); renderMatchmaking(); refreshRivalry(); animateSavedGames(); }
102 if (data.invite && !inviteShown)
103 if (data.invite && !inviteShown)
103 {
104 {
104 inviteShown = true; const i = data.invite;
105 inviteShown = true; const i = data.invite;
@@ -127,16 +128,16 @@ function renderGames ()
127 }
128 }
128 const deadlines = [...moveHolds.values()].filter(h => h.until !== null).map(h => h.until);
129 const deadlines = [...moveHolds.values()].filter(h => h.until !== null).map(h => h.until);
129 if (deadlines.length) moveHoldTimer = setTimeout(renderGames, Math.max(drag ? 100 : 1, Math.min(...deadlines) - now));
130 if (deadlines.length) moveHoldTimer = setTimeout(renderGames, Math.max(drag ? 100 : 1, Math.min(...deadlines) - now));
130 const selector = '.game-card, .waiting-heading, #main > footer';
131 const selector = '#main .game-card, .waiting-heading, #main > footer';
131 const key = el => el.dataset.game || el.tagName;
132 const key = el => el.dataset.game || el.tagName;
132 const animate = !matchMedia('(prefers-reduced-motion: reduce)').matches &&
133 const animate = !matchMedia('(prefers-reduced-motion: reduce)').matches &&
133 (relocating || [...document.querySelectorAll(selector)].some(el => el.getAnimations().length));
134 (relocating || [...document.querySelectorAll(selector)].some(el => el.getAnimations().length));
134 const before = new Map(animate ? [...document.querySelectorAll(selector)].map(el => [key(el), el.getBoundingClientRect()]) : []);
135 const before = new Map(animate ? [...document.querySelectorAll(selector)].map(el => [key(el), el.getBoundingClientRect()]) : []);
135 const yours = state.games.filter(g => g.yourTurn || g.status === 'ended' || g.status === 'pending' && g.incoming || moveHolds.has(g.id));
136 const yours = state.games.filter(g => g.yourTurn || g.status === 'ended' || g.status === 'pending' && g.incoming || moveHolds.has(g.id)).sort((a, b) => (moveHolds.get(a.id)?.turnOrder ?? a.turnOrder) - (moveHolds.get(b.id)?.turnOrder ?? b.turnOrder) || a.id - b.id);
136 const waiting = state.games.filter(g => !yours.includes(g));
137 const waiting = state.games.filter(g => !yours.includes(g));
137 $('#your-count').textContent = yours.length; $('#waiting-count').textContent = waiting.length + (state.matchmaking ? 1 : 0);
138 $('#your-count').textContent = yours.length; $('#waiting-count').textContent = waiting.length + (state.matchmaking ? 1 : 0);
138 // Continue from the visible fill even when polling/selection recreates the cards mid-animation.
139 // Continue from the visible fill even when polling/selection recreates the cards mid-animation.
139 const materialBefore = new Map([...document.querySelectorAll('.material-bar')].map(el =>
140 const materialBefore = new Map([...document.querySelectorAll('#main .material-bar')].map(el =>
140 {
141 {
141 const fill = $('.material-white', el), animation = fill.getAnimations()[0];
142 const fill = $('.material-white', el), animation = fill.getAnimations()[0];
142 return [el.closest('[data-game]').dataset.game, { share: new DOMMatrixReadOnly(getComputedStyle(fill).transform).a, target: el.dataset.share, remaining: animation ? Math.max(0, 650 - Number(animation.currentTime)) : 650 }];
143 return [el.closest('[data-game]').dataset.game, { share: new DOMMatrixReadOnly(getComputedStyle(fill).transform).a, target: el.dataset.share, remaining: animation ? Math.max(0, 650 - Number(animation.currentTime)) : 650 }];
@@ -144,7 +145,7 @@ function renderGames ()
144 $('#your-games').innerHTML = yours.map(card).join('') || empty(true);
145 $('#your-games').innerHTML = yours.map(card).join('') || empty(true);
145 $('#waiting-games').innerHTML = (state.matchmaking ? matchmakingCard() : '') + waiting.map(card).join('') || empty(false);
146 $('#waiting-games').innerHTML = (state.matchmaking ? matchmakingCard() : '') + waiting.map(card).join('') || empty(false);
146 const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
147 const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
147 for (const el of document.querySelectorAll('.material-bar'))
148 for (const el of document.querySelectorAll('#main .material-bar'))
148 {
149 {
149 const fill = $('.material-white', el), share = Number(el.dataset.share), old = materialBefore.get(el.closest('[data-game]').dataset.game);
150 const fill = $('.material-white', el), share = Number(el.dataset.share), old = materialBefore.get(el.closest('[data-game]').dataset.game);
150 fill.style.transform = `scaleX(${share})`;
151 fill.style.transform = `scaleX(${share})`;
@@ -170,7 +171,8 @@ function renderGames ()
170function card (g)
171function card (g)
171{
172{
172 let content = '';
173 let content = '';
173 if (g.status === 'pending') content = `<div class="pending-content"><span class="big-icon">♘</span><h3>${g.incoming ? 'A little challenge?' : 'Challenge sent.'}</h3><p>${g.incoming ? `${esc(g.opponent)} invited you to play.<br>Your board is waiting.` : `Waiting for ${esc(g.opponent)}<br>to accept your challenge.`}</p>${g.incoming ? `<div class="actions"><button class="primary" data-game-action="accept">Accept</button><button class="secondary" data-game-action="reject">Reject</button></div>` : '<span class="inline-note"></span>'}</div>`;
174 if (g.replay) content = board(g);
175 else if (g.status === 'pending') content = `<div class="pending-content"><span class="big-icon">♘</span><h3>${g.incoming ? 'A little challenge?' : 'Challenge sent.'}</h3><p>${g.incoming ? `${esc(g.opponent)} invited you to play.<br>Your board is waiting.` : `Waiting for ${esc(g.opponent)}<br>to accept your challenge.`}</p>${g.incoming ? `<div class="actions"><button class="primary" data-game-action="accept">Accept</button><button class="secondary" data-game-action="reject">Reject</button></div>` : '<span class="inline-note"></span>'}</div>`;
174 else if (g.status === 'ended') content = `<div class="ended-board">${board(g)}<div class="end-content"><div class="end-status"><h3>${g.outcome === 'win' ? 'You won!' : g.outcome === 'loss' ? 'You lost' : 'A game well matched.'}</h3><small>${esc(g.reason)}</small>${g.opponentRematch && g.canRematch ? `<small>${esc(g.opponent)} wants a rematch.</small>` : ''}</div><div class="actions">${g.canRematch ? `<button class="primary" data-game-action="rematch" ${g.rematch ? 'disabled' : ''}>${g.rematch ? 'Requested' : 'Rematch'}</button>` : ''}<button class="secondary" data-game-action="exit">Exit</button></div></div></div>`;
176 else if (g.status === 'ended') content = `<div class="ended-board">${board(g)}<div class="end-content"><div class="end-status"><h3>${g.outcome === 'win' ? 'You won!' : g.outcome === 'loss' ? 'You lost' : 'A game well matched.'}</h3><small>${esc(g.reason)}</small>${g.opponentRematch && g.canRematch ? `<small>${esc(g.opponent)} wants a rematch.</small>` : ''}</div><div class="actions">${g.canRematch ? `<button class="primary" data-game-action="rematch" ${g.rematch ? 'disabled' : ''}>${g.rematch ? 'Requested' : 'Rematch'}</button>` : ''}<button class="secondary" data-game-action="exit">Exit</button></div></div></div>`;
175 else content = board(g) + `<div class="card-footer"><span class="${g.yourTurn ? 'turn-label' : ''}">${g.check ? 'Check · ' : ''}${g.yourTurn ? 'Your move' : 'Waiting for a move'}</span>${g.yourTurn ? `<button class="text-button" data-game-action="options" aria-label="Game options">${g.drawOffer === 'opponent' ? 'Draw offered · ' : ''}•••</button>` : `<span>Move ${Math.floor(g.state.ply / 2) + 1}</span>`}</div>`;
177 else content = board(g) + `<div class="card-footer"><span class="${g.yourTurn ? 'turn-label' : ''}">${g.check ? 'Check · ' : ''}${g.yourTurn ? 'Your move' : 'Waiting for a move'}</span>${g.yourTurn ? `<button class="text-button" data-game-action="options" aria-label="Game options">${g.drawOffer === 'opponent' ? 'Draw offered · ' : ''}•••</button>` : `<span>Move ${Math.floor(g.state.ply / 2) + 1}</span>`}</div>`;
176 return `<article class="game-card ${!g.yourTurn && g.status === 'active' ? 'waiting' : ''}" data-game="${g.id}" aria-label="Game with ${esc(g.opponent)}"><div class="card-header">${avatarMarkup(g.opponent, g.opponentAvatar)}<div class="opponent-info"><strong><button class="opponent-name" data-opponent="${esc(g.opponentId)}">${esc(g.opponent)}</button> <small class="rating" aria-label="${g.opponentRating} Elo">${g.opponentRating}</small></strong>${g.status !== 'pending' ? materialBar(g) : ''}</div>${g.status !== 'pending' ? `<span class="color-tag"><span class="color-disc ${g.color === 'b' ? 'black' : ''}"></span>${g.color === 'w' ? 'White' : 'Black'}</span>` : ''}${g.inactiveDays >= 7 ? '<button class="stop-inactive" data-game-action="stop-confirm" aria-label="Stop inactive game" title="Stop inactive game">×</button>' : ''}</div>${content}</article>`;
178 return `<article class="game-card ${!g.yourTurn && g.status === 'active' ? 'waiting' : ''}" data-game="${g.id}" aria-label="Game with ${esc(g.opponent)}"><div class="card-header">${avatarMarkup(g.opponent, g.opponentAvatar)}<div class="opponent-info"><strong><button class="opponent-name" data-opponent="${esc(g.opponentId)}">${esc(g.opponent)}</button> <small class="rating" aria-label="${g.opponentRating} Elo">${g.opponentRating}</small></strong>${g.status !== 'pending' ? materialBar(g) : ''}</div>${g.status !== 'pending' ? `<span class="color-tag"><span class="color-disc ${g.color === 'b' ? 'black' : ''}"></span>${g.color === 'w' ? 'White' : 'Black'}</span>` : ''}${g.inactiveDays >= 7 ? '<button class="stop-inactive" data-game-action="stop-confirm" aria-label="Stop inactive game" title="Stop inactive game">×</button>' : ''}</div>${content}</article>`;
@@ -238,7 +240,7 @@ function renderFriends ()
238 const incoming = state.friendRequests.filter(r => r.incoming);
240 const incoming = state.friendRequests.filter(r => r.incoming);
239 $('#friend-requests').innerHTML = incoming.length ? '<div class="friends-label">PENDING REQUESTS</div>' + incoming.map(r => `<div class="friend-request">${avatarMarkup(r.name, r.avatar)}<div><strong>${esc(r.name)}</strong><div class="actions"><button class="primary" data-request-action="accept_friend_request" data-request-user="${esc(r.id)}">Accept</button><button class="secondary" data-request-action="reject_friend_request" data-request-user="${esc(r.id)}">Reject</button></div></div></div>`).join('') : '';
241 $('#friend-requests').innerHTML = incoming.length ? '<div class="friends-label">PENDING REQUESTS</div>' + incoming.map(r => `<div class="friend-request">${avatarMarkup(r.name, r.avatar)}<div><strong>${esc(r.name)}</strong><div class="actions"><button class="primary" data-request-action="accept_friend_request" data-request-user="${esc(r.id)}">Accept</button><button class="secondary" data-request-action="reject_friend_request" data-request-user="${esc(r.id)}">Reject</button></div></div></div>`).join('') : '';
240 $('#friend-count').textContent = state.friends.length + incoming.length;
242 $('#friend-count').textContent = state.friends.length + incoming.length;
241 $('#account-summary').innerHTML = `${avatarMarkup(state.user.name, state.user.avatar, true)}<span>${esc(state.user.name)}<small>${state.user.rating} Elo</small></span>`;
243 $('#account-summary').innerHTML = `${avatarMarkup(state.user.name, state.user.avatar, true)}<span>${esc(state.user.name)}<small>${state.user.rating} Elo</small></span><button id="history-button" class="text-button" aria-label="Game history" title="Game history">⌛</button>`;
242}
244}
243function showRivalry (id)
245function showRivalry (id)
244{
246{
@@ -305,6 +307,7 @@ document.addEventListener('click', e =>
305 const gameEl = el.closest('[data-game]'); const g = gameEl && state?.games.find(g => g.id === Number(gameEl.dataset.game));
307 const gameEl = el.closest('[data-game]'); const g = gameEl && state?.games.find(g => g.id === Number(gameEl.dataset.game));
306 if (el.dataset.requestAction) action({ action: el.dataset.requestAction, friend: el.dataset.requestUser }, () => { if (modal.open) closeModal(); toast(el.dataset.requestAction === 'send_friend_request' ? 'Friend request sent.' : el.dataset.requestAction === 'accept_friend_request' ? 'Friend request accepted.' : 'Friend request rejected.'); });
308 if (el.dataset.requestAction) action({ action: el.dataset.requestAction, friend: el.dataset.requestUser }, () => { if (modal.open) closeModal(); toast(el.dataset.requestAction === 'send_friend_request' ? 'Friend request sent.' : el.dataset.requestAction === 'accept_friend_request' ? 'Friend request accepted.' : 'Friend request rejected.'); });
307 if (el.dataset.matchmaking) action({ action: el.dataset.matchmaking }, () => { if (modal.open) closeModal(); });
309 if (el.dataset.matchmaking) action({ action: el.dataset.matchmaking }, () => { if (modal.open) closeModal(); });
310 if (el.id === 'history-button') showHistory();
308 if (el.id === 'avatar-button') chooseAvatar();
311 if (el.id === 'avatar-button') chooseAvatar();
309 if (el.dataset.createLink) createLink(el.dataset.createLink);
312 if (el.dataset.createLink) createLink(el.dataset.createLink);
310 if (el.hasAttribute('data-square') && g) { if (suppressClick) { suppressClick = false; return; } chooseSquare(g, Number(el.dataset.square)); }
313 if (el.hasAttribute('data-square') && g) { if (suppressClick) { suppressClick = false; return; } chooseSquare(g, Number(el.dataset.square)); }
@@ -360,3 +363,94 @@ document.addEventListener('pointerup', e =>
360});
363});
361document.addEventListener('pointercancel', () => { drag = null; $('.drag-ghost')?.remove(); });
364document.addEventListener('pointercancel', () => { drag = null; $('.drag-ghost')?.remove(); });
362refresh(); setInterval(() => { if (!document.hidden) refresh(); }, 2500); document.addEventListener('visibilitychange', () => { if (!document.hidden) refresh(); });
365refresh(); setInterval(() => { if (!document.hidden) refresh(); }, 2500); document.addEventListener('visibilitychange', () => { if (!document.hidden) refresh(); });
366
367let replay = null, replayTimer = null, historyRequest = 0;
368function stopReplay () { clearInterval(replayTimer); replayTimer = null; }
369async function historyFetch (query)
370{
371 const response = await fetch('api.php?action=' + query);
372 const data = await response.json();
373 if (!response.ok) throw new Error(data.error || 'Unable to load saved games.');
374 return data;
375}
376async function showHistory ()
377{
378 const request = ++historyRequest;
379 showModal('<h2 id="modal-title">Game history</h2><p>Loading saved games…</p>');
380 try {
381 const games = await historyFetch('history');
382 if (request !== historyRequest || !modal.open || $('#modal-title')?.textContent !== 'Game history') return;
383 $('#modal-content').innerHTML = `<h2 id="modal-title">Game history</h2><div class="history-list">${games.map(g => `<button class="secondary history-entry" data-replay-id="${g.id}"><strong>${esc(g.opponent)}</strong><span>${g.outcome === 'win' ? 'Won' : g.outcome === 'loss' ? 'Lost' : 'Draw'}</span><time datetime="${new Date(g.ended * 1000).toISOString()}">${esc(new Date(g.ended * 1000).toLocaleDateString())}</time></button>`).join('') || '<p>No saved games yet.</p>'}</div>`;
384 } catch (e) { toast(e.message); }
385}
386async function openReplay (id)
387{
388 const source = $('#modal-content').firstElementChild;
389 const request = ++historyRequest;
390 try {
391 const game = await historyFetch('replay&id=' + id);
392 if (request !== historyRequest || !modal.open || source !== $('#modal-content').firstElementChild) return;
393 showModal('<div id="replay-card"></div><div class="replay-controls"><button class="secondary" data-replay-control="back" title="Double-click to jump to the beginning">Back</button><button class="primary" data-replay-control="play">Play</button><button class="secondary" data-replay-control="next" title="Double-click to jump to the end">Next</button></div><p id="replay-progress" aria-live="polite"></p><button class="text-button" id="history-return">← Game history</button>');
394 modal.classList.add('replay-modal');
395 replay = { ...game, index: 0 };
396 renderReplay();
397 } catch (e) { toast(e.message); }
398}
399function renderReplay ()
400{
401 if (!replay || !$('#replay-card')) return;
402 const g = { ...replay, id: 'replay', replay: true, status: 'replay', yourTurn: false, legal: [], check: false, state: replay.positions[replay.index] };
403 $('#replay-card').innerHTML = card(g);
404 const material = $('#replay-card .material-bar');
405 $('.material-white', material).style.transform = `scaleX(${material.dataset.share})`;
406 $('#replay-progress').textContent = `${replay.index} / ${replay.positions.length - 1} · ${replay.outcome === 'win' ? 'Won' : replay.outcome === 'loss' ? 'Lost' : 'Draw'} · ${replay.reason}`;
407 $('[data-replay-control="play"]').textContent = replayTimer ? 'Pause' : 'Play';
408 $('[data-replay-control="play"]').disabled = replay.positions.length < 2;
409}
410$('#modal-content').addEventListener('click', e => {
411 const b = e.target.closest('button'); if (!b) return;
412 if (b.dataset.replayId) openReplay(b.dataset.replayId);
413 if (b.id === 'history-return') showHistory();
414 const control = b.dataset.replayControl;
415 if (!control || !replay) return;
416 if (control === 'play') {
417 if (replayTimer) stopReplay();
418 else {
419 if (replay.index === replay.positions.length - 1) replay.index = 0;
420 replayTimer = setInterval(() => {
421 replay.index++;
422 if (replay.index >= replay.positions.length - 1) stopReplay();
423 renderReplay();
424 }, 500);
425 }
426 } else {
427 stopReplay();
428 replay.index = Math.max(0, Math.min(replay.positions.length - 1, replay.index + (control === 'back' ? -1 : 1)));
429 }
430 renderReplay();
431});
432$('#modal-content').addEventListener('dblclick', e => {
433 const control = e.target.closest('button')?.dataset.replayControl;
434 if (!replay || !['back', 'next'].includes(control)) return;
435 stopReplay(); replay.index = control === 'back' ? 0 : replay.positions.length - 1; renderReplay();
436});
437const savedAnimations = new Set();
438function animateSavedGames ()
439{
440 for (const g of state.games) {
441 if (!g.replayId) continue;
442 const key = `microchess-saved:${state.user.id}:${g.replayId}`;
443 let seen = savedAnimations.has(key);
444 try { seen ||= localStorage.getItem(key) === '1'; } catch {}
445 const tile = $(`#your-games [data-game="${g.id}"]`), target = $('#history-button');
446 if (seen || !tile || !target || !target.getBoundingClientRect().width) continue;
447 savedAnimations.add(key);
448 try { localStorage.setItem(key, '1'); } catch {}
449 if (matchMedia('(prefers-reduced-motion: reduce)').matches) continue;
450 const start = tile.getBoundingClientRect(), end = target.getBoundingClientRect();
451 const icon = document.createElement('span'); icon.className = 'saved-hourglass'; icon.textContent = '⌛'; icon.setAttribute('aria-hidden', 'true');
452 icon.style.left = `${start.left + start.width / 2 - 12}px`; icon.style.top = `${start.top + 45}px`; document.body.append(icon);
453 const flight = icon.animate([{ opacity: 0, transform: 'translate(0,0) scale(.5)' }, { opacity: 1, transform: 'translate(0,0) scale(1)', offset: .2 }, { opacity: 0, transform: `translate(${end.left + end.width / 2 - start.left - start.width / 2}px,${end.top + end.height / 2 - start.top - 57}px) scale(.5)` }], { duration: 1100, easing: 'cubic-bezier(.4,0,.2,1)' });
454 flight.onfinish = () => { icon.remove(); $('#history-button')?.animate([{ transform: 'translateY(0)' }, { transform: 'translateY(-9px)' }, { transform: 'translateY(0)' }], { duration: 360, easing: 'ease-out' }); };
455 }
456}
web/lib/bootstrap.php +53 −2
@@ -58,6 +58,27 @@ function db(): PDO {
58 58 CREATE TABLE IF NOT EXISTS matchmaking (user_id TEXT PRIMARY KEY REFERENCES users(id), joined INTEGER NOT NULL);
59 59 CREATE TABLE IF NOT EXISTS matchmaking_clock (id INTEGER PRIMARY KEY CHECK(id=1), checked INTEGER NOT NULL);
60 60 INSERT OR IGNORE INTO matchmaking_clock VALUES(1,0);');
61 $db->exec('CREATE TABLE IF NOT EXISTS replays (result_id INTEGER PRIMARY KEY REFERENCES results(id), white TEXT NOT NULL, moves BLOB NOT NULL);
62 CREATE INDEX IF NOT EXISTS results_ended ON results(ended);');
63 if (!in_array('turn_order',$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1),true)) {
64 $db->exec('BEGIN IMMEDIATE');
65 try {
66 if (!in_array('turn_order',$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1),true)) {
67 $db->exec('ALTER TABLE games ADD COLUMN turn_order INTEGER NOT NULL DEFAULT 0');
68 $db->exec('UPDATE games SET turn_order=id');
69 }
70 $db->exec('COMMIT');
71 } catch (Throwable $e) {$db->exec('ROLLBACK');throw $e;}
72 }
73 $db->exec("CREATE TRIGGER IF NOT EXISTS games_turn_insert AFTER INSERT ON games BEGIN UPDATE games SET turn_order=(SELECT COALESCE(MAX(turn_order),0)+1 FROM games) WHERE id=NEW.id; END;
74 CREATE TRIGGER IF NOT EXISTS games_turn_update AFTER UPDATE OF state ON games WHEN NEW.state IS NOT OLD.state BEGIN UPDATE games SET turn_order=(SELECT COALESCE(MAX(turn_order),0)+1 FROM games) WHERE id=NEW.id; END;");
75 $q=$db->query("SELECT r.id,r.state,g.white FROM results r JOIN games g ON g.id=r.game_id WHERE r.state=g.state AND g.status='ended' AND NOT EXISTS (SELECT 1 FROM replays p WHERE p.result_id=r.id)");
76 foreach ($q->fetchAll() as $r) {
77 $position=json_decode($r['state'],true);
78 if (!empty($position['history'])) {
79 try {saveReplay((int)$r['id'],$r['white'],$position);} catch (PDOException $e) {if ($e->getCode()!=='23000') throw $e;}
80 }
81 }
61 82 return $db;
62 83 }
63 84 function activityTriggers(PDO $db): void {
@@ -158,11 +179,41 @@ function befriend(string $a,string $b): void {
158 179 query('INSERT OR IGNORE INTO friends VALUES(?,?)',$p);
159 180 query('DELETE FROM friend_requests WHERE a=? AND b=?',$p);
160 181 }
182 // Two bytes per ply: source square, destination square and resulting piece (promotion included).
183 // Only the initial board is stored in full; no repeated position snapshots.
184 function saveReplay(int $result,string $white,array $s): void {
185 $history=$s['history'];
186 $packed=substr($history[0],0,21);
187 $pieces='.prnbqkPRNBQK';
188 for ($i=1;$i<count($history);$i++) {
189 $before=$history[$i-1];$after=$history[$i];$from=0;$to=0;
190 for ($j=0;$j<20;$j++) if ($before[$j]!==$after[$j]) {
191 if ($after[$j]==='.') $from=$j; else $to=$j;
192 }
193 $packed.=pack('n',($from*20+$to)*13+strpos($pieces,$after[$to]));
194 }
195 $q=db()->prepare('INSERT INTO replays VALUES(?,?,?)');
196 $q->bindValue(1,$result);$q->bindValue(2,$white);$q->bindValue(3,$packed,PDO::PARAM_LOB);$q->execute();
197 query("UPDATE results SET state='{}' WHERE id=?",[$result]);
198 }
199 function replayPositions(string $packed): array {
200 $board=str_split(substr($packed,0,20));$turn=$packed[20];
201 $positions=[['board'=>$board,'turn'=>$turn,'ply'=>0,'last'=>null]];
202 for ($i=21;$i<strlen($packed);$i+=2) {
203 $code=unpack('n',substr($packed,$i,2))[1];$piece='.prnbqkPRNBQK'[$code%13];
204 $squares=intdiv($code,13);$from=intdiv($squares,20);$to=$squares%20;
205 $board[$from]='.';$board[$to]=$piece;$turn=$turn==='w'?'b':'w';
206 $positions[]=['board'=>$board,'turn'=>$turn,'ply'=>count($positions),'last'=>['from'=>$from,'to'=>$to]];
207 }
208 return $positions;
209 }
161 210 function finishGame(array $g,?string $winner,string $reason,array $s): void {
162 $finished=query("UPDATE games SET status='ended',winner=?,reason=?,state=?,draw_offer=NULL,version=version+1 WHERE id=? AND status='active' AND version=?",[$winner,$reason,json_encode($s),$g['id'],$g['version']]);
211 $final=$s;$final['history']=[];
212 $finished=query("UPDATE games SET status='ended',winner=?,reason=?,state=?,draw_offer=NULL,version=version+1 WHERE id=? AND status='active' AND version=?",[$winner,$reason,json_encode($final),$g['id'],$g['version']]);
163 213 if ($finished->rowCount()!==1) throw new DomainException('The game has changed. Please try again.');
164 214 query('INSERT INTO results(game_id,a,b,winner,reason,state,ended) VALUES(?,?,?,?,?,?,?)',[$g['id'],$g['a'],$g['b'],$winner,$reason,json_encode($s),time()]);
165 215 $result=(int)db()->lastInsertId();
216 saveReplay($result,$g['white'],$s);
166 217 $a=(int)profile($g['a'])['rating'];$b=(int)profile($g['b'])['rating'];
167 218 $score=$winner===null?0.5:($winner===$g['a']?1:0);
168 219 $delta=(int)round(32*($score-1/(1+10**(($b-$a)/400))));
@@ -202,7 +253,7 @@ function gameView(array $g,string $u): array {
202 253 $opponent=profile($other);
203 254 $s=$g['state']?json_decode($g['state'],true):null;
204 255 $color=$g['white']===$u?'w':'b';
205 return ['id'=>(int)$g['id'],'opponentId'=>$other,'rivalry'=>rivalry($u,$other),'opponent'=>$opponent['name'],'opponentAvatar'=>$opponent['avatar'],'opponentRating'=>(int)$opponent['rating'], 'status'=>$g['status'],'incoming'=>$g['b']===$u,'color'=>$color,
256 return ['id'=>(int)$g['id'],'turnOrder'=>(int)$g['turn_order'],'replayId'=>$g['status']==='ended'?(int)query('SELECT MAX(result_id) FROM replays JOIN results ON results.id=replays.result_id WHERE game_id=?',[$g['id']])->fetchColumn():null,'opponentId'=>$other,'rivalry'=>rivalry($u,$other),'opponent'=>$opponent['name'],'opponentAvatar'=>$opponent['avatar'],'opponentRating'=>(int)$opponent['rating'], 'status'=>$g['status'],'incoming'=>$g['b']===$u,'color'=>$color,
206 257 'inactiveDays'=>max(0,(int)floor((time()-($g['activity_at']??time()))/86400)),
207 258 'outcome'=>$g['winner']===null?'draw':($g['winner']===$u?'win':'loss'),
208 259 'state'=>$s,'yourTurn'=>$g['status']==='active' && $s['turn']===$color,'legal'=>$g['status']==='active' && $s['turn']===$color?Chess::legal($s):[],
@@ -58,6 +58,27 @@ function db(): PDO {
58 CREATE TABLE IF NOT EXISTS matchmaking (user_id TEXT PRIMARY KEY REFERENCES users(id), joined INTEGER NOT NULL);
58 CREATE TABLE IF NOT EXISTS matchmaking (user_id TEXT PRIMARY KEY REFERENCES users(id), joined INTEGER NOT NULL);
59 CREATE TABLE IF NOT EXISTS matchmaking_clock (id INTEGER PRIMARY KEY CHECK(id=1), checked INTEGER NOT NULL);
59 CREATE TABLE IF NOT EXISTS matchmaking_clock (id INTEGER PRIMARY KEY CHECK(id=1), checked INTEGER NOT NULL);
60 INSERT OR IGNORE INTO matchmaking_clock VALUES(1,0);');
60 INSERT OR IGNORE INTO matchmaking_clock VALUES(1,0);');
61 $db->exec('CREATE TABLE IF NOT EXISTS replays (result_id INTEGER PRIMARY KEY REFERENCES results(id), white TEXT NOT NULL, moves BLOB NOT NULL);
62 CREATE INDEX IF NOT EXISTS results_ended ON results(ended);');
63 if (!in_array('turn_order',$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1),true)) {
64 $db->exec('BEGIN IMMEDIATE');
65 try {
66 if (!in_array('turn_order',$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1),true)) {
67 $db->exec('ALTER TABLE games ADD COLUMN turn_order INTEGER NOT NULL DEFAULT 0');
68 $db->exec('UPDATE games SET turn_order=id');
69 }
70 $db->exec('COMMIT');
71 } catch (Throwable $e) {$db->exec('ROLLBACK');throw $e;}
72 }
73 $db->exec("CREATE TRIGGER IF NOT EXISTS games_turn_insert AFTER INSERT ON games BEGIN UPDATE games SET turn_order=(SELECT COALESCE(MAX(turn_order),0)+1 FROM games) WHERE id=NEW.id; END;
74 CREATE TRIGGER IF NOT EXISTS games_turn_update AFTER UPDATE OF state ON games WHEN NEW.state IS NOT OLD.state BEGIN UPDATE games SET turn_order=(SELECT COALESCE(MAX(turn_order),0)+1 FROM games) WHERE id=NEW.id; END;");
75 $q=$db->query("SELECT r.id,r.state,g.white FROM results r JOIN games g ON g.id=r.game_id WHERE r.state=g.state AND g.status='ended' AND NOT EXISTS (SELECT 1 FROM replays p WHERE p.result_id=r.id)");
76 foreach ($q->fetchAll() as $r) {
77 $position=json_decode($r['state'],true);
78 if (!empty($position['history'])) {
79 try {saveReplay((int)$r['id'],$r['white'],$position);} catch (PDOException $e) {if ($e->getCode()!=='23000') throw $e;}
80 }
81 }
61 return $db;
82 return $db;
62}
83}
63function activityTriggers(PDO $db): void {
84function activityTriggers(PDO $db): void {
@@ -158,11 +179,41 @@ function befriend(string $a,string $b): void {
158 query('INSERT OR IGNORE INTO friends VALUES(?,?)',$p);
179 query('INSERT OR IGNORE INTO friends VALUES(?,?)',$p);
159 query('DELETE FROM friend_requests WHERE a=? AND b=?',$p);
180 query('DELETE FROM friend_requests WHERE a=? AND b=?',$p);
160}
181}
182// Two bytes per ply: source square, destination square and resulting piece (promotion included).
183// Only the initial board is stored in full; no repeated position snapshots.
184function saveReplay(int $result,string $white,array $s): void {
185 $history=$s['history'];
186 $packed=substr($history[0],0,21);
187 $pieces='.prnbqkPRNBQK';
188 for ($i=1;$i<count($history);$i++) {
189 $before=$history[$i-1];$after=$history[$i];$from=0;$to=0;
190 for ($j=0;$j<20;$j++) if ($before[$j]!==$after[$j]) {
191 if ($after[$j]==='.') $from=$j; else $to=$j;
192 }
193 $packed.=pack('n',($from*20+$to)*13+strpos($pieces,$after[$to]));
194 }
195 $q=db()->prepare('INSERT INTO replays VALUES(?,?,?)');
196 $q->bindValue(1,$result);$q->bindValue(2,$white);$q->bindValue(3,$packed,PDO::PARAM_LOB);$q->execute();
197 query("UPDATE results SET state='{}' WHERE id=?",[$result]);
198}
199function replayPositions(string $packed): array {
200 $board=str_split(substr($packed,0,20));$turn=$packed[20];
201 $positions=[['board'=>$board,'turn'=>$turn,'ply'=>0,'last'=>null]];
202 for ($i=21;$i<strlen($packed);$i+=2) {
203 $code=unpack('n',substr($packed,$i,2))[1];$piece='.prnbqkPRNBQK'[$code%13];
204 $squares=intdiv($code,13);$from=intdiv($squares,20);$to=$squares%20;
205 $board[$from]='.';$board[$to]=$piece;$turn=$turn==='w'?'b':'w';
206 $positions[]=['board'=>$board,'turn'=>$turn,'ply'=>count($positions),'last'=>['from'=>$from,'to'=>$to]];
207 }
208 return $positions;
209}
161function finishGame(array $g,?string $winner,string $reason,array $s): void {
210function finishGame(array $g,?string $winner,string $reason,array $s): void {
162 $finished=query("UPDATE games SET status='ended',winner=?,reason=?,state=?,draw_offer=NULL,version=version+1 WHERE id=? AND status='active' AND version=?",[$winner,$reason,json_encode($s),$g['id'],$g['version']]);
211 $final=$s;$final['history']=[];
212 $finished=query("UPDATE games SET status='ended',winner=?,reason=?,state=?,draw_offer=NULL,version=version+1 WHERE id=? AND status='active' AND version=?",[$winner,$reason,json_encode($final),$g['id'],$g['version']]);
163 if ($finished->rowCount()!==1) throw new DomainException('The game has changed. Please try again.');
213 if ($finished->rowCount()!==1) throw new DomainException('The game has changed. Please try again.');
164 query('INSERT INTO results(game_id,a,b,winner,reason,state,ended) VALUES(?,?,?,?,?,?,?)',[$g['id'],$g['a'],$g['b'],$winner,$reason,json_encode($s),time()]);
214 query('INSERT INTO results(game_id,a,b,winner,reason,state,ended) VALUES(?,?,?,?,?,?,?)',[$g['id'],$g['a'],$g['b'],$winner,$reason,json_encode($s),time()]);
165 $result=(int)db()->lastInsertId();
215 $result=(int)db()->lastInsertId();
216 saveReplay($result,$g['white'],$s);
166 $a=(int)profile($g['a'])['rating'];$b=(int)profile($g['b'])['rating'];
217 $a=(int)profile($g['a'])['rating'];$b=(int)profile($g['b'])['rating'];
167 $score=$winner===null?0.5:($winner===$g['a']?1:0);
218 $score=$winner===null?0.5:($winner===$g['a']?1:0);
168 $delta=(int)round(32*($score-1/(1+10**(($b-$a)/400))));
219 $delta=(int)round(32*($score-1/(1+10**(($b-$a)/400))));
@@ -202,7 +253,7 @@ function gameView(array $g,string $u): array {
202 $opponent=profile($other);
253 $opponent=profile($other);
203 $s=$g['state']?json_decode($g['state'],true):null;
254 $s=$g['state']?json_decode($g['state'],true):null;
204 $color=$g['white']===$u?'w':'b';
255 $color=$g['white']===$u?'w':'b';
205 return ['id'=>(int)$g['id'],'opponentId'=>$other,'rivalry'=>rivalry($u,$other),'opponent'=>$opponent['name'],'opponentAvatar'=>$opponent['avatar'],'opponentRating'=>(int)$opponent['rating'], 'status'=>$g['status'],'incoming'=>$g['b']===$u,'color'=>$color,
256 return ['id'=>(int)$g['id'],'turnOrder'=>(int)$g['turn_order'],'replayId'=>$g['status']==='ended'?(int)query('SELECT MAX(result_id) FROM replays JOIN results ON results.id=replays.result_id WHERE game_id=?',[$g['id']])->fetchColumn():null,'opponentId'=>$other,'rivalry'=>rivalry($u,$other),'opponent'=>$opponent['name'],'opponentAvatar'=>$opponent['avatar'],'opponentRating'=>(int)$opponent['rating'], 'status'=>$g['status'],'incoming'=>$g['b']===$u,'color'=>$color,
206 'inactiveDays'=>max(0,(int)floor((time()-($g['activity_at']??time()))/86400)),
257 'inactiveDays'=>max(0,(int)floor((time()-($g['activity_at']??time()))/86400)),
207 'outcome'=>$g['winner']===null?'draw':($g['winner']===$u?'win':'loss'),
258 'outcome'=>$g['winner']===null?'draw':($g['winner']===$u?'win':'loss'),
208 'state'=>$s,'yourTurn'=>$g['status']==='active' && $s['turn']===$color,'legal'=>$g['status']==='active' && $s['turn']===$color?Chess::legal($s):[],
259 'state'=>$s,'yourTurn'=>$g['status']==='active' && $s['turn']===$color,'legal'=>$g['status']==='active' && $s['turn']===$color?Chess::legal($s):[],
web/tests/browser.mjs +25 −0
@@ -119,6 +119,11 @@ try{
119 119 await white.emulateMedia({reducedMotion:'no-preference'});
120 120 const kingsBar=await white.evaluate(()=>materialBar({color:'w',state:{board:['K','k',...Array(18).fill('.')]}}));
121 121 assert(kingsBar.includes('data-share="0.5"'),'Bare kings give a neutral material bar');
122 await white.evaluate(() => {
123 window.savedFlights = 0;
124 const original = Element.prototype.animate;
125 Element.prototype.animate = function (...args) { if (this.classList.contains('saved-hourglass')) window.savedFlights++; return original.apply(this, args); };
126 });
122 127 // Fixture a legal promotion position in the isolated database.
123 128 const fixture={board:['.','.','.','k','.','P','.','.','.','.','.','.','.','.','.','.','K','.','.','.'],turn:'w',halfmove:0,ply:2,history:[],last:null};
124 129 fixture.history=[fixture.board.join('')+'w'];
@@ -139,6 +144,26 @@ try{
139 144 await page.locator('.end-content').hover();await page.waitForTimeout(850);
140 145 assert.equal(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity),'1','Hover reveals result controls');
141 146 }
147 assert.equal(await white.evaluate(()=>window.savedFlights),1,'Finished game animates to history once');
148 await white.locator('#history-button').click();
149 await white.locator('.history-entry').waitFor();
150 await white.locator('.history-entry').first().click();
151 await white.locator('#replay-card .board').waitFor();
152 assert.equal(await white.locator('#replay-card [data-square="5"] img').count(),1,'Replay starts before promotion');
153 await white.locator('[data-replay-control="next"]').dblclick();
154 assert.match(await white.locator('#replay-card [data-square="1"] img').getAttribute('src'),/nlt/,'Replay preserves underpromotion');
155 await white.locator('[data-replay-control="back"]').dblclick();
156 assert.match(await white.locator('#replay-progress').innerText(),/^0 \/ 1/,'Double back returns to beginning');
157 await white.locator('[data-replay-control="play"]').click();
158 assert.equal(await white.locator('[data-replay-control="play"]').innerText(),'Pause','Play becomes pause');
159 await white.waitForTimeout(600);
160 assert.match(await white.locator('#replay-progress').innerText(),/^1 \/ 1/,'Autoplay advances to end');
161 assert.equal(await white.locator('[data-replay-control="play"]').innerText(),'Play','Autoplay stops at end');
162 assert.equal(await white.locator('#replay-card .material-white').evaluate(el=>new DOMMatrixReadOnly(getComputedStyle(el).transform).a),1,'Replay material bar updates after promotion');
163 await white.screenshot({path:path.join(web,'tests/artifacts/game-replay.png')});
164 await white.locator('#modal-close').click();
165 await white.evaluate(()=>refresh(true));
166 assert.equal(await white.locator('.saved-hourglass').count(),0,'Saved animation does not repeat');
142 167 await white.getByRole('button',{name:'Rematch',exact:true}).click();
143 168 await black.getByText(/wants a rematch/).waitFor();
144 169 await black.getByRole('button',{name:'Rematch',exact:true}).click();
@@ -119,6 +119,11 @@ try{
119 await white.emulateMedia({reducedMotion:'no-preference'});
119 await white.emulateMedia({reducedMotion:'no-preference'});
120 const kingsBar=await white.evaluate(()=>materialBar({color:'w',state:{board:['K','k',...Array(18).fill('.')]}}));
120 const kingsBar=await white.evaluate(()=>materialBar({color:'w',state:{board:['K','k',...Array(18).fill('.')]}}));
121 assert(kingsBar.includes('data-share="0.5"'),'Bare kings give a neutral material bar');
121 assert(kingsBar.includes('data-share="0.5"'),'Bare kings give a neutral material bar');
122 await white.evaluate(() => {
123 window.savedFlights = 0;
124 const original = Element.prototype.animate;
125 Element.prototype.animate = function (...args) { if (this.classList.contains('saved-hourglass')) window.savedFlights++; return original.apply(this, args); };
126 });
122 // Fixture a legal promotion position in the isolated database.
127 // Fixture a legal promotion position in the isolated database.
123 const fixture={board:['.','.','.','k','.','P','.','.','.','.','.','.','.','.','.','.','K','.','.','.'],turn:'w',halfmove:0,ply:2,history:[],last:null};
128 const fixture={board:['.','.','.','k','.','P','.','.','.','.','.','.','.','.','.','.','K','.','.','.'],turn:'w',halfmove:0,ply:2,history:[],last:null};
124 fixture.history=[fixture.board.join('')+'w'];
129 fixture.history=[fixture.board.join('')+'w'];
@@ -139,6 +144,26 @@ try{
139 await page.locator('.end-content').hover();await page.waitForTimeout(850);
144 await page.locator('.end-content').hover();await page.waitForTimeout(850);
140 assert.equal(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity),'1','Hover reveals result controls');
145 assert.equal(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity),'1','Hover reveals result controls');
141 }
146 }
147 assert.equal(await white.evaluate(()=>window.savedFlights),1,'Finished game animates to history once');
148 await white.locator('#history-button').click();
149 await white.locator('.history-entry').waitFor();
150 await white.locator('.history-entry').first().click();
151 await white.locator('#replay-card .board').waitFor();
152 assert.equal(await white.locator('#replay-card [data-square="5"] img').count(),1,'Replay starts before promotion');
153 await white.locator('[data-replay-control="next"]').dblclick();
154 assert.match(await white.locator('#replay-card [data-square="1"] img').getAttribute('src'),/nlt/,'Replay preserves underpromotion');
155 await white.locator('[data-replay-control="back"]').dblclick();
156 assert.match(await white.locator('#replay-progress').innerText(),/^0 \/ 1/,'Double back returns to beginning');
157 await white.locator('[data-replay-control="play"]').click();
158 assert.equal(await white.locator('[data-replay-control="play"]').innerText(),'Pause','Play becomes pause');
159 await white.waitForTimeout(600);
160 assert.match(await white.locator('#replay-progress').innerText(),/^1 \/ 1/,'Autoplay advances to end');
161 assert.equal(await white.locator('[data-replay-control="play"]').innerText(),'Play','Autoplay stops at end');
162 assert.equal(await white.locator('#replay-card .material-white').evaluate(el=>new DOMMatrixReadOnly(getComputedStyle(el).transform).a),1,'Replay material bar updates after promotion');
163 await white.screenshot({path:path.join(web,'tests/artifacts/game-replay.png')});
164 await white.locator('#modal-close').click();
165 await white.evaluate(()=>refresh(true));
166 assert.equal(await white.locator('.saved-hourglass').count(),0,'Saved animation does not repeat');
142 await white.getByRole('button',{name:'Rematch',exact:true}).click();
167 await white.getByRole('button',{name:'Rematch',exact:true}).click();
143 await black.getByText(/wants a rematch/).waitFor();
168 await black.getByText(/wants a rematch/).waitFor();
144 await black.getByRole('button',{name:'Rematch',exact:true}).click();
169 await black.getByRole('button',{name:'Rematch',exact:true}).click();
web/tests/integration.py +27 −0
@@ -129,12 +129,20 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
129 129 check(response['feedback']['quality'] in [None, 'good', 'poor'], 'Only supported feedback values')
130 130 white.post('move', game=id, version=current['version'], **move, expected=409)
131 131 check(black.game(id)['yourTurn'], 'Turn passes')
132 check(black.game(id)['turnOrder']>current['turnOrder'],'New turn receives a later persistent queue position')
132 133 black.game_action('resign', id)
133 134 check(a.game(id)['status']=='ended' and b.game(id)['winner']==white.state()['user']['name'], 'Resignation result')
134 135 check(white.state()['user']['rating']==1216 and black.state()['user']['rating']==1184, 'Equal rating win transfers 16 points')
135 136 black.game_action('resign', id, expected=409)
136 137 check(black.state()['user']['ratedGames']==1, 'Duplicate result cannot change rating twice')
137 138 check(sum(a.state()['friends'][0][k] for k in ['wins','losses','ties'])==1, 'Stats recorded once')
139 archive=white.get('/api.php?action=history')
140 check(len(archive)==1 and archive[0]['outcome']=='win','Winner has saved game')
141 saved_id=archive[0]['id']
142 saved=white.get(f'/api.php?action=replay&id={saved_id}')
143 check(len(saved['positions'])==2 and saved['positions'][-1]['board']==white.game(id)['state']['board'],'Replay reconstructs opening and final board')
144 check(black.get('/api.php?action=history')[0]['outcome']=='loss','Both participants can access their result')
145 check(saved['color']=='w','Replay retains player orientation')
138 146 old_color = a.game(id)['color']
139 147 a.game_action('rematch', id)
140 148 check(b.game(id)['opponentRematch'], 'Rematch notification')
@@ -148,9 +156,13 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
148 156 check(a.state()['friends'][0]['ties']==1, 'Draw stats')
149 157 check(white.state()['user']['rating']==1215 and black.state()['user']['rating']==1185, 'Rematch draw transfers one point to lower rated player')
150 158 check(a.state()['user']['ratedGames']==b.state()['user']['ratedGames']==2, 'Rematch rated separately')
159 archive=a.get('/api.php?action=history')
160 check(len(archive)==2 and archive[0]['id']>archive[1]['id'] and archive[0]['outcome']=='draw','Rematches saved separately, newest first')
161 check(white.get(f'/api.php?action=replay&id={saved_id}')['positions']==saved['positions'] and white.get(f'/api.php?action=replay&id={saved_id}')['color']==saved['color'],'Rematch preserves original replay')
151 162 a.game_action('rematch', id); b.game_action('exit', id)
152 163 check(not a.game(id)['canRematch'], 'Exit disables opponent rematch')
153 164 check(not b.state()['games'], 'Exit hides own tile only')
165 check(len(b.get('/api.php?action=history'))==2,'Exiting keeps saved games')
154 166 a.game_action('rematch', id, expected=409)
155 167 a.game_action('exit', id)
156 168 match = a.post('create_link',kind='match')['url'].split('=')[1]
@@ -296,6 +308,21 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
296 308 check(con.execute('SELECT user_id FROM matchmaking').fetchall()==[('queue:far',)],'Unmatched entry remains queued')
297 309 check(con.execute('SELECT count(*) FROM rating_changes').fetchone()[0]==3,'Every completed result has one rating ledger entry')
298 310 con.close()
311 with sqlite3.connect(root/'data/microchess.sqlite') as archive_db:
312 private_id=archive_db.execute("INSERT INTO results(game_id,a,b,winner,reason,state,ended) SELECT game_id,'queue:oldest','queue:near',NULL,'Draw','{}',ended FROM results WHERE id=?",(saved_id,)).lastrowid
313 archive_db.execute("INSERT INTO replays SELECT ?,'queue:oldest',moves FROM replays WHERE result_id=?",(private_id,saved_id))
314 check(all(r['id']!=private_id for r in a.get('/api.php?action=history')),'History excludes other players games')
315 try:
316 a.get(f'/api.php?action=replay&id={private_id}')
317 check(False,'Other players replay unavailable')
318 except urllib.error.HTTPError as e:
319 check(e.code==404,'Other players replay unavailable')
320 with sqlite3.connect(root/'data/microchess.sqlite') as archive_db:
321 check(archive_db.execute('SELECT length(moves) FROM replays WHERE result_id=?',(saved_id,)).fetchone()[0]==23,'One move uses two bytes plus initial position')
322 archive_db.execute('UPDATE results SET ended=? WHERE id=?',(int(time.time())-10*365*86400,saved_id))
323 check(any(r['id']==saved_id for r in a.get('/api.php?action=history')),'Old replay remains in history without a retention limit')
324 check(a.get(f'/api.php?action=replay&id={saved_id}')['positions']==saved['positions'],'Old replay remains fully playable')
325 check(any(r['id']==saved_id for r in a.get('/api.php?action=export')['replays']),'Old replay remains available in exports')
299 326 print(f'API: {checks} assertions passed.')
300 327 finally:
301 328 os.killpg(process.pid,signal.SIGTERM);process.wait();log.close()
@@ -129,12 +129,20 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
129 check(response['feedback']['quality'] in [None, 'good', 'poor'], 'Only supported feedback values')
129 check(response['feedback']['quality'] in [None, 'good', 'poor'], 'Only supported feedback values')
130 white.post('move', game=id, version=current['version'], **move, expected=409)
130 white.post('move', game=id, version=current['version'], **move, expected=409)
131 check(black.game(id)['yourTurn'], 'Turn passes')
131 check(black.game(id)['yourTurn'], 'Turn passes')
132 check(black.game(id)['turnOrder']>current['turnOrder'],'New turn receives a later persistent queue position')
132 black.game_action('resign', id)
133 black.game_action('resign', id)
133 check(a.game(id)['status']=='ended' and b.game(id)['winner']==white.state()['user']['name'], 'Resignation result')
134 check(a.game(id)['status']=='ended' and b.game(id)['winner']==white.state()['user']['name'], 'Resignation result')
134 check(white.state()['user']['rating']==1216 and black.state()['user']['rating']==1184, 'Equal rating win transfers 16 points')
135 check(white.state()['user']['rating']==1216 and black.state()['user']['rating']==1184, 'Equal rating win transfers 16 points')
135 black.game_action('resign', id, expected=409)
136 black.game_action('resign', id, expected=409)
136 check(black.state()['user']['ratedGames']==1, 'Duplicate result cannot change rating twice')
137 check(black.state()['user']['ratedGames']==1, 'Duplicate result cannot change rating twice')
137 check(sum(a.state()['friends'][0][k] for k in ['wins','losses','ties'])==1, 'Stats recorded once')
138 check(sum(a.state()['friends'][0][k] for k in ['wins','losses','ties'])==1, 'Stats recorded once')
139 archive=white.get('/api.php?action=history')
140 check(len(archive)==1 and archive[0]['outcome']=='win','Winner has saved game')
141 saved_id=archive[0]['id']
142 saved=white.get(f'/api.php?action=replay&id={saved_id}')
143 check(len(saved['positions'])==2 and saved['positions'][-1]['board']==white.game(id)['state']['board'],'Replay reconstructs opening and final board')
144 check(black.get('/api.php?action=history')[0]['outcome']=='loss','Both participants can access their result')
145 check(saved['color']=='w','Replay retains player orientation')
138 old_color = a.game(id)['color']
146 old_color = a.game(id)['color']
139 a.game_action('rematch', id)
147 a.game_action('rematch', id)
140 check(b.game(id)['opponentRematch'], 'Rematch notification')
148 check(b.game(id)['opponentRematch'], 'Rematch notification')
@@ -148,9 +156,13 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
148 check(a.state()['friends'][0]['ties']==1, 'Draw stats')
156 check(a.state()['friends'][0]['ties']==1, 'Draw stats')
149 check(white.state()['user']['rating']==1215 and black.state()['user']['rating']==1185, 'Rematch draw transfers one point to lower rated player')
157 check(white.state()['user']['rating']==1215 and black.state()['user']['rating']==1185, 'Rematch draw transfers one point to lower rated player')
150 check(a.state()['user']['ratedGames']==b.state()['user']['ratedGames']==2, 'Rematch rated separately')
158 check(a.state()['user']['ratedGames']==b.state()['user']['ratedGames']==2, 'Rematch rated separately')
159 archive=a.get('/api.php?action=history')
160 check(len(archive)==2 and archive[0]['id']>archive[1]['id'] and archive[0]['outcome']=='draw','Rematches saved separately, newest first')
161 check(white.get(f'/api.php?action=replay&id={saved_id}')['positions']==saved['positions'] and white.get(f'/api.php?action=replay&id={saved_id}')['color']==saved['color'],'Rematch preserves original replay')
151 a.game_action('rematch', id); b.game_action('exit', id)
162 a.game_action('rematch', id); b.game_action('exit', id)
152 check(not a.game(id)['canRematch'], 'Exit disables opponent rematch')
163 check(not a.game(id)['canRematch'], 'Exit disables opponent rematch')
153 check(not b.state()['games'], 'Exit hides own tile only')
164 check(not b.state()['games'], 'Exit hides own tile only')
165 check(len(b.get('/api.php?action=history'))==2,'Exiting keeps saved games')
154 a.game_action('rematch', id, expected=409)
166 a.game_action('rematch', id, expected=409)
155 a.game_action('exit', id)
167 a.game_action('exit', id)
156 match = a.post('create_link',kind='match')['url'].split('=')[1]
168 match = a.post('create_link',kind='match')['url'].split('=')[1]
@@ -296,6 +308,21 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
296 check(con.execute('SELECT user_id FROM matchmaking').fetchall()==[('queue:far',)],'Unmatched entry remains queued')
308 check(con.execute('SELECT user_id FROM matchmaking').fetchall()==[('queue:far',)],'Unmatched entry remains queued')
297 check(con.execute('SELECT count(*) FROM rating_changes').fetchone()[0]==3,'Every completed result has one rating ledger entry')
309 check(con.execute('SELECT count(*) FROM rating_changes').fetchone()[0]==3,'Every completed result has one rating ledger entry')
298 con.close()
310 con.close()
311 with sqlite3.connect(root/'data/microchess.sqlite') as archive_db:
312 private_id=archive_db.execute("INSERT INTO results(game_id,a,b,winner,reason,state,ended) SELECT game_id,'queue:oldest','queue:near',NULL,'Draw','{}',ended FROM results WHERE id=?",(saved_id,)).lastrowid
313 archive_db.execute("INSERT INTO replays SELECT ?,'queue:oldest',moves FROM replays WHERE result_id=?",(private_id,saved_id))
314 check(all(r['id']!=private_id for r in a.get('/api.php?action=history')),'History excludes other players games')
315 try:
316 a.get(f'/api.php?action=replay&id={private_id}')
317 check(False,'Other players replay unavailable')
318 except urllib.error.HTTPError as e:
319 check(e.code==404,'Other players replay unavailable')
320 with sqlite3.connect(root/'data/microchess.sqlite') as archive_db:
321 check(archive_db.execute('SELECT length(moves) FROM replays WHERE result_id=?',(saved_id,)).fetchone()[0]==23,'One move uses two bytes plus initial position')
322 archive_db.execute('UPDATE results SET ended=? WHERE id=?',(int(time.time())-10*365*86400,saved_id))
323 check(any(r['id']==saved_id for r in a.get('/api.php?action=history')),'Old replay remains in history without a retention limit')
324 check(a.get(f'/api.php?action=replay&id={saved_id}')['positions']==saved['positions'],'Old replay remains fully playable')
325 check(any(r['id']==saved_id for r in a.get('/api.php?action=export')['replays']),'Old replay remains available in exports')
299 print(f'API: {checks} assertions passed.')
326 print(f'API: {checks} assertions passed.')
300 finally:
327 finally:
301 os.killpg(process.pid,signal.SIGTERM);process.wait();log.close()
328 os.killpg(process.pid,signal.SIGTERM);process.wait();log.close()