'use strict';
const $ = (s, root = document) => root.querySelector(s);
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
const names = { p: 'Pawn', r: 'Rook', n: 'Knight', b: 'Bishop', q: 'Queen', k: 'King' };
const materialValues = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 };
const pieceUrl = p => `assets/pieces/${p.toLowerCase()}${p === p.toUpperCase() ? 'l' : 'd'}t.svg`;
const initials = name => esc(name.slice(0, 2).toUpperCase());
const avatarUrl = id => `assets/avatars/${encodeURIComponent(id)}.png`;
function avatarMarkup (name, id, editable = false)
{
const content = id ? ` ` : initials(name);
return editable ? `${content} ` : `${content} `;
}
let avatarOptions = null, avatarGroup = 'all', avatarColor = 'all';
async function chooseAvatar ()
{
if (!state) return;
showModal('
Choose your avatar Loading the pieces…
');
modal.classList.add('avatar-picker');
try
{
if (!avatarOptions) { const response = await fetch('assets/avatars/catalog.json'); if (!response.ok) throw new Error('Unable to load avatars. Please try again.'); avatarOptions = await response.json(); }
if (!modal.open || !modal.classList.contains('avatar-picker')) return;
avatarGroup = 'all'; avatarColor = 'all';
$('#modal-content').innerHTML = `MAKE IT YOURS Choose your avatar A little character for your next rivalry. Select a piece to save it.
${[['all', 'All pieces'], ['standard', 'Chess'], ['fairy', 'Fairy chess']].map(([id, label]) => `${label} `).join('')}
All colors ${[...new Set(avatarOptions.map(a => a.color))].sort().map(c => `${esc(c)} `).join('')}
Pieces by Wikimedia Commons contributors. Sources & licenses ↗
`;
renderAvatarChoices();
} catch (e) { toast(e.message); if (modal.classList.contains('avatar-picker')) closeModal(); }
}
function renderAvatarChoices ()
{
const options = avatarOptions.filter(a => (avatarGroup === 'all' || a.group === avatarGroup) && (avatarColor === 'all' || a.color === avatarColor));
$('#avatar-choices').innerHTML = options.map(a => `${esc(a.name)} `).join('') || 'No pieces in this color. Try another color.
';
$('#avatar-option-count').textContent = `${options.length} pieces`;
document.querySelectorAll('[data-avatar-group]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.avatarGroup === avatarGroup)));
}
let state, selected = null, promotion = null, busy = false, drag = null, lastRender = '', toastTimer, inviteShown = false;
const moveHolds = new Map();
const moveFeedback = new Map();
let moveHoldTimer;
let inviteToken = new URLSearchParams(location.search).get('invite');
const modal = $('#modal');
function toast (message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 5000); }
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(); }
function clearReplay () { stopReplay(); if (modal?.classList.contains('replay-modal')) { $('#modal-content').innerHTML = ''; modal.classList.remove('replay-modal'); } }
function closeModal () { if (!modal) return; clearReplay(); modal.close(); }
if ($('#modal-close')) $('#modal-close').onclick = closeModal;
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(); } });
function dismissInvite () { inviteToken = null; history.replaceState(null, '', location.pathname); }
modal?.addEventListener('close', () => { if (!modal.open) clearReplay(); if (inviteShown) dismissInvite(); });
const mobileLayout = matchMedia('(max-width: 760px)');
function showSidebar (open)
{
const sidebar = $('#sidebar'); if (!sidebar) return;
sidebar.classList.toggle('open', open);
sidebar.inert = mobileLayout.matches && !open;
$('#sidebar-backdrop').hidden = !open;
$('#friends-toggle').setAttribute('aria-expanded', String(open));
$('#main').inert = mobileLayout.matches && open;
document.body.classList.toggle('sidebar-open', mobileLayout.matches && open);
if (open) { $('#friends-close').focus(); animateSavedGames(); }
else if (mobileLayout.matches) $('#friends-toggle').focus();
}
mobileLayout.addEventListener('change', () => showSidebar(false));
if ($('#sidebar')) $('#sidebar').inert = mobileLayout.matches;
if ($('#friends-toggle')) $('#friends-toggle').onclick = () => showSidebar(!$('#sidebar').classList.contains('open'));
if ($('#friends-close')) $('#friends-close').onclick = () => showSidebar(false);
if ($('#sidebar-backdrop')) $('#sidebar-backdrop').onclick = () => showSidebar(false);
document.addEventListener('keydown', e => { if (e.key === 'Escape') { showSidebar(false); selected = null; promotion = null; claimIntended = null; renderGames(); } });
async function api (data)
{
const response = await fetch('api.php', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': state.csrf }, body: JSON.stringify(data) });
const result = await response.json(); if (!response.ok) throw new Error(result.error || 'Request failed.'); return result;
}
async function action (data, success)
{
if (busy) return; busy = true;
try
{
const result = await api(data);
if (data.action === 'move')
{
moveHolds.set(data.game, { user: state.user.id, version: data.version, turnOrder: state.games.find(g => g.id === data.game)?.turnOrder, until: null });
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 });
}
selected = null; promotion = null; if (success) await success(result); await refresh(true);
}
catch (e) { toast(e.message); await refresh(true); }
finally { busy = false; }
}
async function refresh (force = false)
{
if (!$('#your-games') || (busy && !force) || drag) return;
try
{
const response = await fetch('api.php' + (inviteToken ? '?invite=' + encodeURIComponent(inviteToken) : ''));
const data = await response.json();
if (response.status === 401) { showModal('Sign in to continue Your session has expired. Your games are saved.
Sign in '); return; }
if (!response.ok) throw new Error(data.error || 'Unable to load games.');
state = data;
if (selected) { const g = state.games.find(g => g.id === selected.game); if (!g?.yourTurn || g.version !== selected.version) { selected = null; promotion = null; } }
const signature = JSON.stringify(data);
if (signature !== lastRender) { lastRender = signature; renderGames(); renderFriends(); renderMatchmaking(); refreshRivalry(); animateSavedGames(); }
if (data.invite && !inviteShown)
{
inviteShown = true; const i = data.invite;
if (i.error) showModal(`Invitation ${esc(i.error)}
Got it `);
else showModal(`${i.kind === 'friend' ? 'FRIEND REQUEST' : 'YOU’RE INVITED'} ${esc(i.name)} ${i.kind === 'friend' ? 'wants to be friends.' : 'challenges you.'} ${i.kind === 'friend' ? 'Accept to add each other to your friends lists.' : 'A fresh board, a friendly rivalry. Ready to play?'}
Accept Reject
`);
}
} catch (e) { toast(e.message || 'Connection lost. We’ll try again shortly.'); }
}
function empty (yours) { return `♘ ${yours ? 'Your next rivalry starts here.' : 'All caught up.'} ${yours ? 'Challenge a friend or share a game link. Your games and invitations will appear here.' : 'Games appear here while your opponent is thinking.'}
${yours ? '
Invite someone to play ↗ ' : ''}
`; }
function renderGames ()
{
if (!state) return;
clearTimeout(moveHoldTimer);
let relocating = false;
const now = performance.now();
for (const [id, hold] of moveHolds)
{
const g = state.games.find(g => g.id === id);
if (hold.user !== state.user.id || !g || g.status !== 'active' || (g.version > hold.version && g.yourTurn))
{
moveHolds.delete(id); continue;
}
// Start the pause when the confirmed board position is first displayed.
if (hold.until === null && g.version > hold.version) hold.until = now + 3000;
if (hold.until !== null && hold.until <= now && !drag) { moveHolds.delete(id); relocating = true; }
}
const deadlines = [...moveHolds.values()].filter(h => h.until !== null).map(h => h.until);
if (deadlines.length) moveHoldTimer = setTimeout(renderGames, Math.max(drag ? 100 : 1, Math.min(...deadlines) - now));
const selector = '#main .game-card, .waiting-heading, #main > footer';
const key = el => el.dataset.game || el.tagName;
const animate = !matchMedia('(prefers-reduced-motion: reduce)').matches &&
(relocating || [...document.querySelectorAll(selector)].some(el => el.getAnimations().length));
const before = new Map(animate ? [...document.querySelectorAll(selector)].map(el => [key(el), el.getBoundingClientRect()]) : []);
const yours = state.games.filter(g => g.yourTurn || g.status === 'ended' && !g.rematch || 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);
const waiting = state.games.filter(g => !yours.includes(g));
$('#your-count').textContent = yours.length; $('#waiting-count').textContent = waiting.length + (state.matchmaking ? 1 : 0);
// Continue from the visible fill even when polling/selection recreates the cards mid-animation.
const materialBefore = new Map([...document.querySelectorAll('#main .material-bar')].map(el =>
{
const fill = $('.material-white', el), animation = fill.getAnimations()[0];
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 }];
}));
$('#your-games').innerHTML = yours.map(card).join('') || empty(true);
$('#waiting-games').innerHTML = (state.matchmaking ? matchmakingCard() : '') + waiting.map(card).join('') || empty(false);
const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
for (const el of document.querySelectorAll('#main .material-bar'))
{
const fill = $('.material-white', el), share = Number(el.dataset.share), old = materialBefore.get(el.closest('[data-game]').dataset.game);
fill.style.transform = `scaleX(${share})`;
if (!reduced && old && Math.abs(old.share - share) > .0001) fill.animate([{ transform: `scaleX(${old.share})` }, { transform: `scaleX(${share})` }], { duration: old.target === el.dataset.share ? old.remaining : 650, easing: 'linear' });
}
renderMoveFeedback(now, reduced);
if (animate)
{
for (const el of document.querySelectorAll(selector))
{
const old = before.get(key(el));
el.getAnimations().forEach(animation => animation.cancel());
if (!old) continue;
const rect = el.getBoundingClientRect(), dx = old.left - rect.left, dy = old.top - rect.top;
if (Math.abs(dx) < 1 && Math.abs(dy) < 1) continue;
el.animate([
{ transform: `translate(${dx}px, ${dy}px)`, zIndex: 2 },
{ transform: 'translate(0, 0)', zIndex: 2 }
], { duration: 650, easing: 'cubic-bezier(.22, 1, .36, 1)' });
}
}
}
function card (g)
{
let content = '';
if (g.replay) content = board(g);
else if (g.status === 'pending') content = `♘ ${g.incoming ? 'A little challenge?' : 'Challenge sent.'} ${g.incoming ? `${esc(g.opponent)} invited you to play. Your board is waiting.` : `Waiting for ${esc(g.opponent)} to accept your challenge.`}
${g.incoming ? `
Accept Reject
` : '
'}
`;
else if (g.status === 'ended') content = `${board(g)}
${g.outcome === 'win' ? 'You won!' : g.outcome === 'loss' ? 'You lost' : 'A game well matched.'} ${esc(g.reason)} ${g.opponentRematch && g.canRematch ? `${esc(g.opponent)} wants a rematch. ` : ''}${g.canRematch ? `${g.rematch ? 'Requested' : 'Rematch'} ` : ''}Exit
`;
else content = board(g) + ``;
return `${content} `;
}
function materialBar (g)
{
const totals = { w: 0, b: 0 };
for (const p of g.state.board) if (p !== '.') totals[p === p.toUpperCase() ? 'w' : 'b'] += materialValues[p.toLowerCase()];
const total = totals.w + totals.b, share = total ? totals.w / total : .5;
const label = `White: ${totals.w} material points. Black: ${totals.b} material points. You play ${g.color === 'w' ? 'White' : 'Black'}.`;
return `
`;
}
function renderMoveFeedback (now, reduced)
{
for (const [id, feedback] of moveFeedback)
{
const g = state.games.find(g => g.id === id);
if (feedback.user !== state.user.id || !g || g.state.ply > feedback.ply) { moveFeedback.delete(id); continue; }
if (g.state.ply !== feedback.ply) continue;
if (feedback.start === null)
{
feedback.start = now;
setTimeout(() =>
{
if (moveFeedback.get(id) !== feedback) return;
moveFeedback.delete(id);
document.querySelector(`[data-game="${id}"] .move-feedback`)?.remove();
}, 1800);
}
const elapsed = now - feedback.start;
if (elapsed >= 1800) { moveFeedback.delete(id); continue; }
const el = document.querySelector(`[data-game="${id}"]`); if (!el) continue;
const overlay = document.createElement('div');
overlay.className = `move-feedback ${feedback.quality}`;
const label = { good: 'Looks good', poor: 'Watch out' }[feedback.quality];
el.append(overlay);
if (reduced) { overlay.style.opacity = '1'; continue; }
const frames = [{ opacity: 0, offset: 0 }, { opacity: 1, offset: .15 }, { opacity: .25, offset: .4 }, { opacity: 1, offset: .65 }, { opacity: 0, offset: 1 }];
const animation = overlay.animate(frames, { duration: 1800, easing: 'ease-in-out' });
animation.currentTime = elapsed;
}
}
function board (g)
{
const indices = Array.from({ length: 20 }, (_, i) => g.color === 'w' ? i : 19 - i);
const active = selected?.game === g.id ? selected.from : null;
const legal = g.legal.filter(m => m.from === active).map(m => m.to);
let html = '';
indices.forEach((i, view) =>
{
const p = g.state.board[i], square = String.fromCharCode(97 + i % 4) + (5 - Math.floor(i / 4));
const last = g.state.last && (i === g.state.last.from || i === g.state.last.to);
const checked = g.check && p.toLowerCase() === 'k' && (p === p.toUpperCase() ? 'w' : 'b') === g.state.turn;
const label = `${square}${p !== '.' ? ' ' + (p === p.toUpperCase() ? 'white ' : 'black ') + names[p.toLowerCase()] : ''}${legal.includes(i) ? ', legal destination' : ''}`;
html += `
${p !== '.' ? ` ` : ''}${view % 4 === 0 ? `${5 - Math.floor(i / 4)} ` : ''}${view >= 16 ? `${String.fromCharCode(97 + i % 4)} ` : ''} `;
});
html += '
';
if (promotion?.game === g.id) html += `
`;
return html + '
';
}
function renderFriends ()
{
$('#friend-count').textContent = state.friends.length; $('#sidebar-count').textContent = state.friends.length;
$('#friend-list').innerHTML = state.friends.map(f => `${avatarMarkup(f.name, f.avatar)}${esc(f.name)} ${f.rating} Elo · ${f.wins} wins · ${f.losses} losses · ${f.ties} ties ↗ `).join('') || 'Your friends will appear here. Send an invitation to get started.
';
const incoming = state.friendRequests.filter(r => r.incoming);
$('#friend-requests').innerHTML = incoming.length ? 'PENDING REQUESTS
' + incoming.map(r => `${avatarMarkup(r.name, r.avatar)}
${esc(r.name)} Accept Reject
`).join('') : '';
$('#friend-count').textContent = state.friends.length + incoming.length;
$('#account-summary').innerHTML = `${avatarMarkup(state.user.name, state.user.avatar, true)}${esc(state.user.name)}${state.user.rating} Elo ⌛ `;
}
function showRivalry (id)
{
const friend = state.friends.find(f => f.id === id);
const game = state.games.find(g => g.opponentId === id);
const f = friend || (game && { id, name: game.opponent, ...game.rivalry });
if (!f) return;
const request = state.friendRequests.find(r => r.id === id);
const actions = friend
? 'Challenge to a game ↗ Remove friend… '
: request?.incoming
? `Accept friend request Reject `
: request
? 'Friend request sent '
: `Send friend request `;
showModal(`YOUR FRIENDLY RIVALRY ${esc(f.name)} ${f.wins} Wins
${f.losses} Losses
${f.ties} Ties
${actions}
`);
$('#modal-content').dataset.friend = id;
$('#modal-content').dataset.rivalry = id;
}
function refreshRivalry ()
{
const id = $('#modal-content').dataset.rivalry;
if (modal.open && id) showRivalry(id);
}
function options (g) { showModal(`Your game with ${esc(g.opponent)} ${g.check ? 'You are in check. Find a move that protects your king.' : 'Take your time. The board will be here.'}
${g.drawOffer === 'opponent' ? '
Accept draw ' : g.drawOffer === 'you' ? '
Draw offered. Make your move to pass the offer to your opponent.
' : '
Offer a draw '}${g.claimable ? '
Claim draw ' : '
Claim draw with intended move '}
Resign… `); $('#modal-content').dataset.game = g.id; }
function chooseSquare (g, i)
{
if (!g.yourTurn || busy || promotion) return;
if (selected?.game === g.id && g.legal.some(m => m.from === selected.from && m.to === i)) { attemptMove(g, selected.from, i); return; }
const p = g.state.board[i];
if (p !== '.' && (p === p.toUpperCase() ? 'w' : 'b') === g.color) { selected = selected?.game === g.id && selected.from === i ? null : { game: g.id, from: i, version: g.version }; }
else selected = null;
renderGames();
}
let claimIntended = null;
function attemptMove (g, from, to, promote)
{
const moves = g.legal.filter(m => m.from === from && m.to === to); if (!moves.length) return;
if (moves[0].promotion && !promote) { promotion = { game: g.id, from, to }; renderGames(); return; }
const kind = claimIntended === g.id ? 'claim_draw' : 'move'; claimIntended = null;
action({ action: kind, game: g.id, version: g.version, from, to, promotion: promote ?? null });
}
function matchmakingCard ()
{
const searching = state.matchmaking.status === 'searching';
return `♘ ${searching ? 'Finding an opponent…' : 'No opponent found'} ${searching ? '' : 'Try again '}${searching ? 'Cancel search' : 'Dismiss'}
`;
}
function renderMatchmaking ()
{
const target = $('#matchmaking-actions');
if (!target || !state) return;
target.innerHTML = state.matchmaking?.status === 'searching'
? 'Finding an opponent…
Cancel search '
: 'Challenge a random player ';
}
async function createLink (kind) { await action({ action: 'create_link', kind }, r => { showModal(`${kind === 'friend' ? 'GOOD COMPANY' : 'GAME ON'} ${kind === 'friend' ? 'Invite a friend.' : 'Send a little challenge.'} Share this link. ${kind === 'friend' ? 'You’ll become friends when the other person clicks accept.' : 'The first person to accept starts a game with you.'} It expires in one month.
Copy link ↗
${kind === 'match' ? '
' : ''}`); renderMatchmaking(); }); }
if ($('#match-link')) $('#match-link').onclick = () => createLink('match');
if ($('#friend-link')) $('#friend-link').onclick = () => createLink('friend');
if ($('#settings-button')) $('#settings-button').onclick = () => { if (!state) return; showModal(`Your account Signed in as ${esc(state.user.name)}.
${state.user.rating} Elo
${state.local ? `
Switch to ${state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1'} ` : ''}
Export my data (JSON) Sign out `); };
if ($('#rules-button')) $('#rules-button').onclick = () => showModal(`MICROCHESS Small board. Real chess. The usual rules of chess, on a 4 × 5 board.
Each side starts with a king, rook, bishop, knight and one pawn. White moves first. Pawns move one square forward, capture diagonally and never move two squares. There is no castling or en passant. Reach the last rank to promote to a queen, rook, bishop or knight. Protect your king. Checkmate wins; stalemate and dead positions draw. Claim a draw after three repetitions or 50 moves by each side without a pawn move or capture. You may also claim with an intended move, via the game menu. Five repetitions or 75 moves draw automatically. Click a piece to see legal destinations, then click a dot. Or drag it to a destination. The bar below your opponent’s name compares remaining material: White on the left, Black on the right. Pawn 1, knight/bishop 3, rook 5, queen 9; kings are not counted. After your move, a blue pulse marks a clear estimated gain; red marks a likely material loss or mating threat. This quick tactical check can miss deeper ideas. Quiet or uncertain moves get no pulse. Pieces by Cburnett, from Wikimedia Commons , CC BY-SA 3.0 . Unmodified SVGs.
`);
document.addEventListener('click', e =>
{
const el = e.target.closest('button'); if (!el) return;
const gameEl = el.closest('[data-game]'); const g = gameEl && state?.games.find(g => g.id === Number(gameEl.dataset.game));
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.'); });
if (el.dataset.matchmaking) action({ action: el.dataset.matchmaking }, () => { if (modal.open) closeModal(); });
if (el.id === 'history-button') showHistory();
if (el.id === 'avatar-button') chooseAvatar();
if (el.dataset.createLink) createLink(el.dataset.createLink);
if (el.hasAttribute('data-square') && g) { if (suppressClick) { suppressClick = false; return; } chooseSquare(g, Number(el.dataset.square)); }
if (el.dataset.gameAction && g) { if (el.dataset.gameAction === 'stop-confirm') { showModal(`Stop this game? This game has been inactive for ${g.inactiveDays} days. Would you like to stop it?
Stop game Cancel
`); } else if (el.dataset.gameAction === 'options') options(g); else action({ action: el.dataset.gameAction, game: g.id, version: g.version }); }
if (el.dataset.promotion && g && promotion) attemptMove(g, promotion.from, promotion.to, el.dataset.promotion);
if (el.hasAttribute('data-cancel-promotion')) { promotion = null; claimIntended = null; renderGames(); }
if (el.dataset.friend || el.dataset.opponent) showRivalry(el.dataset.friend || el.dataset.opponent);
});
$('#modal-content').addEventListener('click', async e =>
{
const b = e.target.closest('button'); if (!b) return;
if (b.dataset.stopGame) { await action({ action: 'stop_inactive', game: Number(b.dataset.stopGame), version: Number(b.dataset.version) }, () => closeModal()); return; }
if (b.dataset.avatarGroup) { avatarGroup = b.dataset.avatarGroup; renderAvatarChoices(); return; }
if (b.hasAttribute('data-avatar-choice')) { await action({ action: 'set_avatar', avatar: b.dataset.avatarChoice || null }, () => { closeModal(); toast('Avatar updated.'); }); return; }
if (b.dataset.modalAction === 'close') closeModal();
if (b.dataset.modalAction === 'accept-invite') await action({ action: 'accept_link', token: inviteToken }, () => { closeModal(); toast('Invitation accepted.'); });
if (b.dataset.modalAction === 'copy') { const input = $('#share-url'); try { await navigator.clipboard.writeText(input.value); b.textContent = 'Copied ✓'; } catch { input.focus(); input.select(); toast('Select and copy the link.'); } }
if (b.dataset.modalAction === 'switch') await action({ action: 'switch_user', user: state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1' }, () => { lastRender = ''; closeModal(); });
if (b.dataset.modalAction === 'logout') await action({ action: 'logout' }, () => location.reload());
if (b.dataset.friendAction)
{
const id = $('#modal-content').dataset.friend;
if (b.dataset.friendAction === 'remove') { showModal('Remove this friend? You will both be removed from each other’s friends list. Your game history is kept.
Remove friend Cancel
'); }
else await action({ action: b.dataset.friendAction === 'challenge' ? 'challenge' : 'remove_friend', friend: id }, () => { closeModal(); toast(b.dataset.friendAction === 'challenge' ? 'Challenge sent.' : 'Friend removed.'); });
}
if (b.dataset.option)
{
const g = state.games.find(g => g.id === Number($('#modal-content').dataset.game)); if (!g) return;
if (b.dataset.option === 'resign-confirm') { showModal('Resign this game? Your opponent will win this game. You can request a rematch afterwards.
Resign Cancel
'); return; }
if (b.dataset.option === 'claim-intended') { claimIntended = g.id; closeModal(); toast('Select your intended move to claim a draw.'); return; }
await action({ action: b.dataset.option, game: g.id, version: g.version }, () => closeModal());
}
});
$('#modal-content').addEventListener('change', e => { if (e.target.id === 'avatar-color') { avatarColor = e.target.value; renderAvatarChoices(); } });
let suppressClick = false;
document.addEventListener('pointerdown', e =>
{
const sq = e.target.closest('[data-square]'); if (!sq || e.button !== 0 || busy || promotion) return;
const g = state?.games.find(g => g.id === Number(sq.closest('[data-game]').dataset.game)); if (!g?.yourTurn) return;
const from = Number(sq.dataset.square), p = g.state.board[from]; if (p === '.' || (p === p.toUpperCase() ? 'w' : 'b') !== g.color) return;
drag = { game: g.id, from, p, x: e.clientX, y: e.clientY, id: e.pointerId, moving: false };
});
document.addEventListener('pointermove', e =>
{
if (!drag || e.pointerId !== drag.id) return;
if (!drag.moving && Math.hypot(e.clientX - drag.x, e.clientY - drag.y) > 7) { drag.moving = true; const g = state.games.find(g => g.id === drag.game); selected = { game: g.id, from: drag.from, version: g.version }; renderGames(); const img = document.createElement('img'); img.className = 'drag-ghost'; img.src = pieceUrl(drag.p); document.body.append(img); }
if (drag.moving) { e.preventDefault(); const img = $('.drag-ghost'); img.style.left = e.clientX + 'px'; img.style.top = e.clientY + 'px'; }
}, { passive: false });
document.addEventListener('pointerup', e =>
{
if (!drag || e.pointerId !== drag.id) return; const d = drag; drag = null; $('.drag-ghost')?.remove();
if (d.moving) { suppressClick = true; setTimeout(() => suppressClick = false, 100); const sq = document.elementFromPoint(e.clientX, e.clientY)?.closest('[data-square]'); if (sq && Number(sq.closest('[data-game]').dataset.game) === d.game) attemptMove(state.games.find(g => g.id === d.game), d.from, Number(sq.dataset.square)); }
});
document.addEventListener('pointercancel', () => { drag = null; $('.drag-ghost')?.remove(); });
refresh(); setInterval(() => { if (!document.hidden) refresh(); }, 2500); document.addEventListener('visibilitychange', () => { if (!document.hidden) refresh(); });
let replay = null, replayTimer = null, historyRequest = 0;
function stopReplay () { clearInterval(replayTimer); replayTimer = null; }
async function historyFetch (query)
{
const response = await fetch('api.php?action=' + query);
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Unable to load saved games.');
return data;
}
async function showHistory ()
{
const request = ++historyRequest;
showModal('Game history Loading saved games…
');
try {
const games = await historyFetch('history');
if (request !== historyRequest || !modal.open || $('#modal-title')?.textContent !== 'Game history') return;
$('#modal-content').innerHTML = `Game history ${games.map(g => `
${esc(g.opponent)} ${g.outcome === 'win' ? 'Won' : g.outcome === 'loss' ? 'Lost' : 'Draw'} ${esc(new Date(g.ended * 1000).toLocaleDateString())} `).join('') || '
No saved games yet.
'}
`;
} catch (e) { toast(e.message); }
}
async function openReplay (id)
{
const source = $('#modal-content').firstElementChild;
const request = ++historyRequest;
try {
const game = await historyFetch('replay&id=' + id);
if (request !== historyRequest || !modal.open || source !== $('#modal-content').firstElementChild) return;
showReplay(game);
} catch (e) { toast(e.message); }
}
function showReplay (game)
{
const content = '
⏮ ⏪ ▶ ⏩ ⏭
';
if ($('#replay-page')) { stopReplay(); $('#modal-content').innerHTML = content; }
else { showModal(content); modal.classList.add('replay-modal'); }
replay = { ...game, index: 0 };
renderReplay();
}
async function copyReplayLink ()
{
const url = new URL('./', location.href); url.searchParams.set('replay', replay.shareToken);
try { await navigator.clipboard.writeText(url.href); toast('Game link copied.'); }
catch {
// Keep a usable copy fallback when clipboard access is unavailable.
const input = document.createElement('input'); input.value = url.href; input.readOnly = true; input.setAttribute('aria-label', 'Game link');
$('.replay-bottom').append(input); input.select(); toast('Select and copy the game link.');
}
}
function renderReplay ()
{
if (!replay || !$('#replay-card')) return;
const g = { ...replay, id: 'replay', replay: true, status: 'replay', yourTurn: false, legal: [], check: false, state: replay.positions[replay.index] };
$('#replay-card').innerHTML = `${board(g)} `;
$('#replay-progress').textContent = `${replay.index} / ${replay.positions.length - 1} · ${replay.shared ? replay.outcome : replay.outcome === 'win' ? 'Won' : replay.outcome === 'loss' ? 'Lost' : 'Draw'} · ${replay.reason}`;
const last = replay.positions.length - 1;
$('[data-replay-control="play"]').textContent = replayTimer ? '⏸' : '▶';
$('[data-replay-control="play"]').setAttribute('aria-label', replayTimer ? 'Pause' : 'Play');
$('[data-replay-control="play"]').disabled = last < 1;
$('[data-replay-control="start"]').disabled = $('[data-replay-control="back"]').disabled = replay.index === 0;
$('[data-replay-control="next"]').disabled = $('[data-replay-control="end"]').disabled = replay.index === last;
}
$('#modal-content').addEventListener('click', e => {
const b = e.target.closest('button'); if (!b) return;
if (b.dataset.replayId) openReplay(b.dataset.replayId);
if (b.id === 'history-return') showHistory();
if (b.id === 'replay-share') copyReplayLink();
const control = b.dataset.replayControl;
if (!control || !replay) return;
if (control === 'play') {
if (replayTimer) stopReplay();
else {
if (replay.index === replay.positions.length - 1) replay.index = 0;
replayTimer = setInterval(() => {
replay.index++;
if (replay.index >= replay.positions.length - 1) stopReplay();
renderReplay();
}, 500);
}
} else {
stopReplay();
const last = replay.positions.length - 1;
replay.index = control === 'start' ? 0 : control === 'end' ? last : Math.max(0, Math.min(last, replay.index + (control === 'back' ? -1 : 1)));
}
renderReplay();
});
const savedAnimations = new Set();
function animateSavedGames ()
{
for (const g of state.games) {
if (!g.replayId) continue;
const key = `microchess-saved:${state.user.id}:${g.replayId}`;
let seen = savedAnimations.has(key);
try { seen ||= localStorage.getItem(key) === '1'; } catch {}
const tile = $(`#your-games [data-game="${g.id}"]`), target = $('#history-button');
if (seen || !tile || !target || !target.getBoundingClientRect().width) continue;
savedAnimations.add(key);
try { localStorage.setItem(key, '1'); } catch {}
if (matchMedia('(prefers-reduced-motion: reduce)').matches) continue;
const start = tile.getBoundingClientRect(), end = target.getBoundingClientRect();
const icon = document.createElement('span'); icon.className = 'saved-hourglass'; icon.textContent = '⌛'; icon.setAttribute('aria-hidden', 'true');
icon.style.left = `${start.left + start.width / 2 - 12}px`; icon.style.top = `${start.top + 45}px`; document.body.append(icon);
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)' });
flight.onfinish = () => { icon.remove(); $('#history-button')?.animate([{ transform: 'translateY(0)' }, { transform: 'translateY(-9px)' }, { transform: 'translateY(0)' }], { duration: 360, easing: 'ease-out' }); };
}
}
if (new URLSearchParams(location.search).has('replay')) {
const token = new URLSearchParams(location.search).get('replay');
fetch('api.php?action=shared_replay&token=' + encodeURIComponent(token), { credentials: 'omit' }).then(async response => {
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Unable to load saved games.');
showReplay(data);
}).catch(e => {
$('#modal-content').innerHTML = `Game unavailable ${esc(e.message)}
`;
});
}