'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 YOURS

A little character for your next rivalry. Select a piece to save it.

${[['all', 'All pieces'], ['standard', 'Chess'], ['fairy', 'Fairy chess']].map(([id, label]) => ``).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 => ``).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 SIDE

Choose 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('

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; 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(`

Invitation

${esc(i.error)}

`); 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?'}

`); } window.microchessPwa?.intro(); } 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 ? '' : ''}
`; } 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); // Prefer WAAPI over element.style — CSP style-src 'self' blocks inline CSSOM writes. 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', fill: 'forwards' }); else fill.animate([{ transform: `scaleX(${share})` }], { duration: 0, fill: 'forwards' }); } renderMoveFeedback(now, reduced); window.microchessPwa?.highlight(); 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 ? `
` : ''}
`; 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 ? `` : ''}
`; else content = board(g) + ``; return `
${avatarMarkup(g.opponent, g.opponentAvatar)}
${g.opponentRating}${g.status !== 'pending' ? materialBar(g) : ''}
${g.status !== 'pending' ? colorTagMarkup(g) : ''}${g.inactiveDays >= 7 ? '' : ''}
${content}
`; } function materialBarSkinName (name, fallback) { return PIECE_COLOR_ORDER.includes(name) ? name : fallback; } function materialBarSkins (g) { if (customColoursDisabled()) return { left: 'White', right: 'Black' }; return { left: materialBarSkinName(g.pieceSkinWhite, 'White'), right: materialBarSkinName(g.pieceSkinBlack, 'Black') }; } 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 { left, right } = materialBarSkins(g); const you = g.color === 'w' ? left : right; const label = `${left}: ${totals.w} material points. ${right}: ${totals.b} material points. You play ${you}${you === 'White' || you === 'Black' ? '' : ` (${g.color === 'w' ? 'White' : 'Black'})`}.`; const ariaSides = left === 'White' && right === 'Black' ? 'White on the left and Black on the right' : `${left} (White) on the left and ${right} (Black) on the right`; // Classes only — inline style= is blocked by CSP style-src 'self'. 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 += ``; }); html += '
'; if (promotion?.game === g.id) html += `
A NEW POSSIBILITY

Promote your pawn

Choose the piece for your next chapter.

${['q', 'r', 'b', 'n'].map(p => ``).join('')}
`; return html + '
'; } function renderFriends () { $('#friend-count').textContent = state.friends.length; $('#sidebar-count').textContent = state.friends.length; $('#friend-list').innerHTML = state.friends.map(f => ``).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)}
`).join('') : ''; $('#friend-count').textContent = state.friends.length + incoming.length; $('#account-summary').innerHTML = `${avatarMarkup(state.user.name, state.user.avatar, true)}`; } 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 ? '' : request?.incoming ? `` : 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' ? '' : g.drawOffer === 'you' ? '

Draw offered. Make your move to pass the offer to your opponent.

' : ''}${g.claimable ? '' : ''}
`); $('#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 ? '' : ''}
`; } function renderMatchmaking () { const target = $('#matchmaking-actions'); if (!target || !state) return; target.innerHTML = state.matchmaking?.status === 'searching' ? '

Finding an opponent…

' : ''; } 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.

${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 ? `` : ''}Export my data (JSON)
`); $('#disable-custom-colours').onchange = e => { action({ action: 'set_disable_custom_colours', disabled: e.target.checked }, () => toast(e.target.checked ? 'Custom colours hidden.' : 'Custom colours shown.')); }; window.microchessPwa?.settings(); }; if ($('#rules-button')) $('#rules-button').onclick = () => showModal(`MICROCHESS

Small board. Real chess.

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('

Remove this friend?

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('

Resign this game?

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 = `
${games.map(g => ``).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 = '

' + (game.shared ? 'Microchess ↗' : '') + '
'; 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] }; const whiteTip = !customColoursDisabled() && (replay.pieceSkinWhite || 'White') !== 'White' ? `Playing as ${replay.pieceSkinWhite} (White)` : 'Playing as White'; const blackTip = !customColoursDisabled() && (replay.pieceSkinBlack || 'Black') !== 'Black' ? `Playing as ${replay.pieceSkinBlack} (Black)` : 'Playing as Black'; $('#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)}

`; }); }