'use strict';
const $ = (s, root = document) => root.querySelector(s);
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
// Server embeds the deploy commit in ; append to static URLs.
const assetVersion = document.querySelector('meta[name="asset-version"]')?.content || '';
const withAssetVersion = url => {
if (!assetVersion) return url;
return url + (url.includes('?') ? '&' : '?') + 'v=' + encodeURIComponent(assetVersion);
};
(() => {
// Backup only: HTML already no-stores and links use ?v=. Helps stuck PWA/shell tabs.
if (!assetVersion) return;
const key = 'microchess-asset-version';
const prev = localStorage.getItem(key);
if (prev === assetVersion) return;
localStorage.setItem(key, assetVersion);
if (prev) location.reload();
})();
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 PIECE_COLOR_ORDER = ['White', 'Black', 'Red', 'Blue', 'Green', 'Yellow'];
const CUSTOM_PIECE_SKINS = new Set(['Red', 'Blue', 'Green', 'Yellow']);
const pieceFileNames = { k: 'king', q: 'queen', r: 'rook', b: 'bishop', n: 'knight', p: 'pawn' };
function customColoursDisabled ()
{
// Account preference (default off → custom colours visible).
return !!(state?.user?.disableCustomColours);
}
const classicPieceUrl = p => withAssetVersion(`assets/pieces/${p.toLowerCase()}${p === p.toUpperCase() ? 'l' : 'd'}t.svg`);
const pieceUrl = (p, skin) =>
{
if (!skin || customColoursDisabled() || !CUSTOM_PIECE_SKINS.has(skin)) return classicPieceUrl(p);
return withAssetVersion(`assets/avatars/${skin.toLowerCase()}-${pieceFileNames[p.toLowerCase()]}.png`);
};
function skinForPiece (g, p)
{
if (!g || p === '.') return null;
const whiteSkin = g.pieceSkinWhite || 'White';
const blackSkin = g.pieceSkinBlack || 'Black';
return p === p.toUpperCase() ? whiteSkin : blackSkin;
}
function displayColorFor (g)
{
if (!g) return 'White';
if (customColoursDisabled()) return g.color === 'w' ? 'White' : 'Black';
return g.displayColor || (g.color === 'w' ? (g.pieceSkinWhite || 'White') : (g.pieceSkinBlack || 'Black'));
}
function rulesColorLabel (g) { return g.color === 'w' ? 'White' : 'Black'; }
function colorTagMarkup (g)
{
const display = displayColorFor(g);
const rules = rulesColorLabel(g);
const tip = !customColoursDisabled() && display !== rules ? `Playing as ${display} (${rules})` : `Playing as ${display}`;
const disc = display.toLowerCase();
return `${esc(display)}`;
}
function kingAvatarUrl (color)
{
return withAssetVersion(`assets/avatars/${color.toLowerCase()}-king.png`);
}
function nextColorSkipping (current, skip)
{
let i = PIECE_COLOR_ORDER.indexOf(current);
if (i < 0) i = 0;
for (let n = 0; n < PIECE_COLOR_ORDER.length; n++)
{
i = (i + 1) % PIECE_COLOR_ORDER.length;
if (PIECE_COLOR_ORDER[i] !== skip) return PIECE_COLOR_ORDER[i];
}
return current;
}
const initials = name => esc(name.slice(0, 2).toUpperCase());
const avatarUrl = id => withAssetVersion(`assets/avatars/${encodeURIComponent(id)}.png`);
function avatarMarkup (name, id, editable = false)
{
const content = id ? `` : initials(name);
return editable ? `` : `${content}`;
}
let avatarOptions = null, avatarGroup = 'all', avatarColor = 'all';
async function chooseAvatar ()
{
if (!state) return;
showModal('
Loading the pieces…
'); modal.classList.add('avatar-picker'); try { if (!avatarOptions) { const response = await fetch(withAssetVersion('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 YOURSA little character for your next rivalry. Select a piece to save it.
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 => ``).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))); } function openColorPreferences () { if (!state) return; const pref = { mode: state.user.colorMode === 'custom' ? 'custom' : 'default', preferred: state.user.preferredColor || 'White', alternative: state.user.alternativeColor || 'Black' }; if (pref.preferred === pref.alternative) pref.alternative = nextColorSkipping(pref.alternative, pref.preferred); const paint = () => { showModal(`YOUR SIDEChoose how your pieces look in new games. Opponents may use a different colour when both prefer the same one.
`); $('#color-mode-default').onchange = () => { pref.mode = 'default'; paint(); }; $('#color-mode-custom').onchange = () => { pref.mode = 'custom'; paint(); }; document.querySelectorAll('[data-color-role]').forEach(btn => { btn.onclick = () => { if (btn.dataset.colorRole === 'preferred') pref.preferred = nextColorSkipping(pref.preferred, pref.alternative); else pref.alternative = nextColorSkipping(pref.alternative, pref.preferred); paint(); }; }); $('#save-color-prefs').onclick = async () => { await action({ action: 'set_piece_colors', colorMode: pref.mode, preferredColor: pref.preferred, alternativeColor: pref.alternative }, () => { closeModal(); toast('Colour preference saved.'); }); }; }; paint(); } 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('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; window.microchessPwa?.sync(); 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(`${esc(i.error)}
`); else showModal(`${i.kind === 'friend' ? 'FRIEND REQUEST' : 'YOU’RE INVITED'}${i.kind === 'friend' ? 'Accept to add each other to your friends lists.' : 'A fresh board, a friendly rivalry. Ready to play?'}
`); } window.microchessPwa?.intro(); } catch (e) { toast(e.message || 'Connection lost. We’ll try again shortly.'); } } function empty (yours) { return `${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 ? '' : ''}${g.incoming ? `${esc(g.opponent)} invited you to play.
Your board is waiting.` : `Waiting for ${esc(g.opponent)}
to accept your challenge.`}
Choose the piece for your next chapter.
Your friends will appear here.
Send an invitation to get started.
${g.check ? 'You are in check. Find a move that protects your king.' : 'Take your time. The board will be here.'}
Draw offered. Make your move to pass the offer to your opponent.
' : ''}${g.claimable ? '' : ''}Finding an opponent…
' : ''; } async function createLink (kind) { await action({ action: 'create_link', kind }, r => { showModal(`${kind === 'friend' ? 'GOOD COMPANY' : 'GAME ON'}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.
${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(`Signed in as ${esc(state.user.name)}.
${state.user.rating} Elo
The usual rules of chess, on a 4 × 5 board.
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.id === 'color-pref-button') openColorPreferences(); 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(`This game has been inactive for ${g.inactiveDays} days. Would you like to stop it?
`); } 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({ endpoint: await window.microchessPwa?.endpoint(), 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', endpoint: await window.microchessPwa?.endpoint() }, () => location.reload()); if (b.dataset.friendAction) { const id = $('#modal-content').dataset.friend; if (b.dataset.friendAction === 'remove') { showModal('You will both be removed from each other’s friends list. Your game history is kept.
'); } 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('Your opponent will win this game. You can request a rematch afterwards.
'); 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, skinForPiece(state?.games?.find(x => x.id === drag.game), 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('Loading saved games…
'); try { const games = await historyFetch('history'); if (request !== historyRequest || !modal.open || $('#modal-title')?.textContent !== 'Game history') return; $('#modal-content').innerHTML = `No saved games yet.
'}${esc(e.message)}
`; }); }