'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}`;
}
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('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 from Wikimedia Commons by C. Burnett and Iago Casabiell González. 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))); } 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) { modal.classList.remove('avatar-picker'); $('#modal-content').innerHTML = html; if (!modal.open) modal.showModal(); } function closeModal () { 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 (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(); else if (mobileLayout.matches) $('#friends-toggle').focus(); } mobileLayout.addEventListener('change', () => showSidebar(false)); if ($('#sidebar')) $('#sidebar').inert = mobileLayout.matches; $('#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, 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; 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(); } 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?'}
`); } } 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 ? '' : ''}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.
`); }); } if ($('#match-link')) $('#match-link').onclick = () => createLink('match'); if ($('#friend-link')) $('#friend-link').onclick = () => createLink('friend'); $('#settings-button').onclick = () => { if (!state) return; showModal(`Signed in as ${esc(state.user.name)}.
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.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(`De laatste zet was ${g.inactiveDays} dagen geleden. Wil je het spel stoppen?
`); } 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) { const f = state.friends.find(f => f.id === el.dataset.friend); showModal(`YOUR FRIENDLY RIVALRYYou 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); 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(); });