| 1 | 'use strict'; |
| 2 | const $ = (s, root = document) => root.querySelector(s); |
| 3 | const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); |
| 4 | // Server embeds the deploy commit in <meta name="asset-version">; append to static URLs. |
| 5 | const assetVersion = document.querySelector('meta[name="asset-version"]')?.content || ''; |
| 6 | const withAssetVersion = url => { |
| 7 | if (!assetVersion) return url; |
| 8 | return url + (url.includes('?') ? '&' : '?') + 'v=' + encodeURIComponent(assetVersion); |
| 9 | }; |
| 10 | (() => { |
| 11 | // Backup only: HTML already no-stores and links use ?v=. Helps stuck PWA/shell tabs. |
| 12 | if (!assetVersion) return; |
| 13 | const key = 'microchess-asset-version'; |
| 14 | const prev = localStorage.getItem(key); |
| 15 | if (prev === assetVersion) return; |
| 16 | localStorage.setItem(key, assetVersion); |
| 17 | if (prev) location.reload(); |
| 18 | })(); |
| 19 | const names = { p: 'Pawn', r: 'Rook', n: 'Knight', b: 'Bishop', q: 'Queen', k: 'King' }; |
| 20 | const materialValues = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 }; |
| 21 | const PIECE_COLOR_ORDER = ['White', 'Black', 'Red', 'Blue', 'Green', 'Yellow']; |
| 22 | const CUSTOM_PIECE_SKINS = new Set(['Red', 'Blue', 'Green', 'Yellow']); |
| 23 | const pieceFileNames = { k: 'king', q: 'queen', r: 'rook', b: 'bishop', n: 'knight', p: 'pawn' }; |
| 24 | function customColoursDisabled () |
| 25 | { |
| 26 | // Account preference (default off → custom colours visible). |
| 27 | return !!(state?.user?.disableCustomColours); |
| 28 | } |
| 29 | const classicPieceUrl = p => withAssetVersion(`assets/pieces/${p.toLowerCase()}${p === p.toUpperCase() ? 'l' : 'd'}t.svg`); |
| 30 | const pieceUrl = (p, skin) => |
| 31 | { |
| 32 | if (!skin || customColoursDisabled() || !CUSTOM_PIECE_SKINS.has(skin)) return classicPieceUrl(p); |
| 33 | return withAssetVersion(`assets/avatars/${skin.toLowerCase()}-${pieceFileNames[p.toLowerCase()]}.png`); |
| 34 | }; |
| 35 | function skinForPiece (g, p) |
| 36 | { |
| 37 | if (!g || p === '.') return null; |
| 38 | const whiteSkin = g.pieceSkinWhite || 'White'; |
| 39 | const blackSkin = g.pieceSkinBlack || 'Black'; |
| 40 | return p === p.toUpperCase() ? whiteSkin : blackSkin; |
| 41 | } |
| 42 | function displayColorFor (g) |
| 43 | { |
| 44 | if (!g) return 'White'; |
| 45 | if (customColoursDisabled()) return g.color === 'w' ? 'White' : 'Black'; |
| 46 | return g.displayColor || (g.color === 'w' ? (g.pieceSkinWhite || 'White') : (g.pieceSkinBlack || 'Black')); |
| 47 | } |
| 48 | function rulesColorLabel (g) { return g.color === 'w' ? 'White' : 'Black'; } |
| 49 | function colorTagMarkup (g) |
| 50 | { |
| 51 | const display = displayColorFor(g); |
| 52 | const rules = rulesColorLabel(g); |
| 53 | const tip = !customColoursDisabled() && display !== rules ? `Playing as ${display} (${rules})` : `Playing as ${display}`; |
| 54 | const disc = display.toLowerCase(); |
| 55 | return `<span class="color-tag" title="${esc(tip)}"><span class="color-disc ${esc(disc)}"></span>${esc(display)}</span>`; |
| 56 | } |
| 57 | function kingAvatarUrl (color) |
| 58 | { |
| 59 | return withAssetVersion(`assets/avatars/${color.toLowerCase()}-king.png`); |
| 60 | } |
| 61 | function nextColorSkipping (current, skip) |
| 62 | { |
| 63 | let i = PIECE_COLOR_ORDER.indexOf(current); |
| 64 | if (i < 0) i = 0; |
| 65 | for (let n = 0; n < PIECE_COLOR_ORDER.length; n++) |
| 66 | { |
| 67 | i = (i + 1) % PIECE_COLOR_ORDER.length; |
| 68 | if (PIECE_COLOR_ORDER[i] !== skip) return PIECE_COLOR_ORDER[i]; |
| 69 | } |
| 70 | return current; |
| 71 | } |
| 72 | const initials = name => esc(name.slice(0, 2).toUpperCase()); |
| 73 | const avatarUrl = id => withAssetVersion(`assets/avatars/${encodeURIComponent(id)}.png`); |
| 74 | function avatarMarkup (name, id, editable = false) |
| 75 | { |
| 76 | const content = id ? `<img src="${avatarUrl(id)}" alt="" draggable="false">` : initials(name); |
| 77 | return editable ? `<button id="avatar-button" class="avatar" aria-label="Choose your avatar" title="Choose your avatar">${content}</button>` : `<span class="avatar">${content}</span>`; |
| 78 | } |
| 79 | let avatarOptions = null, avatarGroup = 'all', avatarColor = 'all'; |
| 80 | async function chooseAvatar () |
| 81 | { |
| 82 | if (!state) return; |
| 83 | showModal('<h2 id="modal-title">Choose your avatar</h2><p>Loading the pieces…</p>'); |
| 84 | modal.classList.add('avatar-picker'); |
| 85 | try |
| 86 | { |
| 87 | 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(); } |
| 88 | if (!modal.open || !modal.classList.contains('avatar-picker')) return; |
| 89 | avatarGroup = 'all'; avatarColor = 'all'; |
| 90 | $('#modal-content').innerHTML = `<span class="eyebrow">MAKE IT YOURS</span><h2 id="modal-title">Choose your avatar</h2><p>A little character for your next rivalry. Select a piece to save it.</p><div class="avatar-filters"><div class="avatar-tabs" aria-label="Piece family">${[['all', 'All pieces'], ['standard', 'Chess'], ['fairy', 'Fairy chess']].map(([id, label]) => `<button class="secondary" data-avatar-group="${id}" aria-pressed="${id === 'all'}">${label}</button>`).join('')}</div><select id="avatar-color" aria-label="Filter avatars by color"><option value="all">All colors</option>${[...new Set(avatarOptions.map(a => a.color))].sort().map(c => `<option value="${esc(c)}">${esc(c)}</option>`).join('')}</select></div><div id="avatar-choices" class="avatar-choices" aria-label="Available avatars"></div><div class="avatar-picker-footer"><button class="text-button" data-avatar-choice="">Choose randomly</button><span id="avatar-option-count" class="inline-note" role="status"></span></div><p class="avatar-credits">Pieces by Wikimedia Commons contributors. <a href="${withAssetVersion('assets/avatars/CREDITS.md')}" target="_blank" rel="noopener">Sources & licenses ↗</a></p>`; |
| 91 | renderAvatarChoices(); |
| 92 | } catch (e) { toast(e.message); if (modal.classList.contains('avatar-picker')) closeModal(); } |
| 93 | } |
| 94 | function renderAvatarChoices () |
| 95 | { |
| 96 | const options = avatarOptions.filter(a => (avatarGroup === 'all' || a.group === avatarGroup) && (avatarColor === 'all' || a.color === avatarColor)); |
| 97 | $('#avatar-choices').innerHTML = options.map(a => `<button class="avatar-choice" data-avatar-choice="${esc(a.id)}" aria-label="${esc(a.name)}" aria-pressed="${state.user.avatar === a.id}"><img src="${avatarUrl(a.id)}" alt="" loading="lazy"><span>${esc(a.name)}</span></button>`).join('') || '<p class="avatar-no-results">No pieces in this color. Try another color.</p>'; |
| 98 | $('#avatar-option-count').textContent = `${options.length} pieces`; |
| 99 | document.querySelectorAll('[data-avatar-group]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.avatarGroup === avatarGroup))); |
| 100 | } |
| 101 | |
| 102 | function openColorPreferences () |
| 103 | { |
| 104 | if (!state) return; |
| 105 | const pref = { |
| 106 | mode: state.user.colorMode === 'custom' ? 'custom' : 'default', |
| 107 | preferred: state.user.preferredColor || 'White', |
| 108 | alternative: state.user.alternativeColor || 'Black' |
| 109 | }; |
| 110 | if (pref.preferred === pref.alternative) pref.alternative = nextColorSkipping(pref.alternative, pref.preferred); |
| 111 | const paint = () => |
| 112 | { |
| 113 | showModal(`<span class="eyebrow">YOUR SIDE</span><h2 id="modal-title">Piece colours</h2><p>Choose how your pieces look in new games. Opponents may use a different colour when both prefer the same one.</p><div class="color-mode-options" role="radiogroup" aria-label="Colour mode"><label class="color-mode-option"><input type="radio" name="color-mode" id="color-mode-default" value="default" ${pref.mode !== 'custom' ? 'checked' : ''}> <span><strong>Default Colours</strong><small>Play as White or Black by the rules side, as usual.</small></span></label><label class="color-mode-option"><input type="radio" name="color-mode" id="color-mode-custom" value="custom" ${pref.mode === 'custom' ? 'checked' : ''}> <span><strong>Custom Colour</strong><small>Pick a preferred colour and an alternative if both players clash.</small></span></label></div><div id="custom-color-pickers" class="custom-color-pickers"${pref.mode === 'custom' ? '' : ' hidden'}><button type="button" class="color-king-choice" data-color-role="preferred" aria-label="Preferred colour ${esc(pref.preferred)}"><img src="${kingAvatarUrl(pref.preferred)}" alt=""><span>Preferred</span><strong>${esc(pref.preferred)}</strong></button><button type="button" class="color-king-choice" data-color-role="alternative" aria-label="Alternative colour ${esc(pref.alternative)}"><img src="${kingAvatarUrl(pref.alternative)}" alt=""><span>Alternative</span><strong>${esc(pref.alternative)}</strong></button></div><div class="actions"><button class="primary" id="save-color-prefs">Save</button><button class="secondary" data-modal-action="close">Cancel</button></div>`); |
| 114 | $('#color-mode-default').onchange = () => { pref.mode = 'default'; paint(); }; |
| 115 | $('#color-mode-custom').onchange = () => { pref.mode = 'custom'; paint(); }; |
| 116 | document.querySelectorAll('[data-color-role]').forEach(btn => |
| 117 | { |
| 118 | btn.onclick = () => |
| 119 | { |
| 120 | if (btn.dataset.colorRole === 'preferred') pref.preferred = nextColorSkipping(pref.preferred, pref.alternative); |
| 121 | else pref.alternative = nextColorSkipping(pref.alternative, pref.preferred); |
| 122 | paint(); |
| 123 | }; |
| 124 | }); |
| 125 | $('#save-color-prefs').onclick = async () => |
| 126 | { |
| 127 | await action({ action: 'set_piece_colors', colorMode: pref.mode, preferredColor: pref.preferred, alternativeColor: pref.alternative }, () => |
| 128 | { |
| 129 | closeModal(); |
| 130 | toast('Colour preference saved.'); |
| 131 | }); |
| 132 | }; |
| 133 | }; |
| 134 | paint(); |
| 135 | } |
| 136 | |
| 137 | let state, selected = null, promotion = null, busy = false, drag = null, lastRender = '', toastTimer, inviteShown = false; |
| 138 | const moveHolds = new Map(); |
| 139 | const moveFeedback = new Map(); |
| 140 | let moveHoldTimer; |
| 141 | let inviteToken = new URLSearchParams(location.search).get('invite'); |
| 142 | const modal = $('#modal'); |
| 143 | function toast (message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 5000); } |
| 144 | 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(); } |
| 145 | function clearReplay () { stopReplay(); if (modal?.classList.contains('replay-modal')) { $('#modal-content').innerHTML = ''; modal.classList.remove('replay-modal'); } } |
| 146 | function closeModal () { if (!modal) return; clearReplay(); modal.close(); } |
| 147 | if ($('#modal-close')) $('#modal-close').onclick = closeModal; |
| 148 | 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(); } }); |
| 149 | function dismissInvite () { inviteToken = null; history.replaceState(null, '', location.pathname); } |
| 150 | modal?.addEventListener('close', () => { if (!modal.open) clearReplay(); if (inviteShown) dismissInvite(); }); |
| 151 | const mobileLayout = matchMedia('(max-width: 760px)'); |
| 152 | function showSidebar (open) |
| 153 | { |
| 154 | const sidebar = $('#sidebar'); if (!sidebar) return; |
| 155 | sidebar.classList.toggle('open', open); |
| 156 | sidebar.inert = mobileLayout.matches && !open; |
| 157 | $('#sidebar-backdrop').hidden = !open; |
| 158 | $('#friends-toggle').setAttribute('aria-expanded', String(open)); |
| 159 | $('#main').inert = mobileLayout.matches && open; |
| 160 | document.body.classList.toggle('sidebar-open', mobileLayout.matches && open); |
| 161 | if (open) { $('#friends-close').focus(); animateSavedGames(); } |
| 162 | else if (mobileLayout.matches) $('#friends-toggle').focus(); |
| 163 | } |
| 164 | mobileLayout.addEventListener('change', () => showSidebar(false)); |
| 165 | if ($('#sidebar')) $('#sidebar').inert = mobileLayout.matches; |
| 166 | if ($('#friends-toggle')) $('#friends-toggle').onclick = () => showSidebar(!$('#sidebar').classList.contains('open')); |
| 167 | if ($('#friends-close')) $('#friends-close').onclick = () => showSidebar(false); |
| 168 | if ($('#sidebar-backdrop')) $('#sidebar-backdrop').onclick = () => showSidebar(false); |
| 169 | document.addEventListener('keydown', e => { if (e.key === 'Escape') { showSidebar(false); selected = null; promotion = null; claimIntended = null; renderGames(); } }); |
| 170 | async function api (data) |
| 171 | { |
| 172 | const response = await fetch('api.php', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': state.csrf }, body: JSON.stringify(data) }); |
| 173 | const result = await response.json(); if (!response.ok) throw new Error(result.error || 'Request failed.'); return result; |
| 174 | } |
| 175 | async function action (data, success) |
| 176 | { |
| 177 | if (busy) return; busy = true; |
| 178 | try |
| 179 | { |
| 180 | const result = await api(data); |
| 181 | if (data.action === 'move') |
| 182 | { |
| 183 | moveHolds.set(data.game, { user: state.user.id, version: data.version, turnOrder: state.games.find(g => g.id === data.game)?.turnOrder, until: null }); |
| 184 | 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 }); |
| 185 | } |
| 186 | selected = null; promotion = null; if (success) await success(result); await refresh(true); |
| 187 | } |
| 188 | catch (e) { toast(e.message); await refresh(true); } |
| 189 | finally { busy = false; } |
| 190 | } |
| 191 | async function refresh (force = false) |
| 192 | { |
| 193 | if (!$('#your-games') || (busy && !force) || drag) return; |
| 194 | try |
| 195 | { |
| 196 | const response = await fetch('api.php' + (inviteToken ? '?invite=' + encodeURIComponent(inviteToken) : '')); |
| 197 | const data = await response.json(); |
| 198 | if (response.status === 401) { showModal('<h2>Sign in to continue</h2><p>Your session has expired. Your games are saved.</p><a class="button primary" href="auth.php' + esc(location.search || '') + '">Sign in</a>'); return; } |
| 199 | if (!response.ok) throw new Error(data.error || 'Unable to load games.'); |
| 200 | state = data; |
| 201 | window.microchessPwa?.sync(); |
| 202 | if (selected) { const g = state.games.find(g => g.id === selected.game); if (!g?.yourTurn || g.version !== selected.version) { selected = null; promotion = null; } } |
| 203 | const signature = JSON.stringify(data); |
| 204 | if (signature !== lastRender) { lastRender = signature; renderGames(); renderFriends(); renderMatchmaking(); refreshRivalry(); animateSavedGames(); } |
| 205 | if (data.invite && !inviteShown) |
| 206 | { |
| 207 | inviteShown = true; const i = data.invite; |
| 208 | if (i.error) showModal(`<h2>Invitation</h2><p>${esc(i.error)}</p><button class="primary" data-modal-action="close">Got it</button>`); |
| 209 | else showModal(`<span class="eyebrow">${i.kind === 'friend' ? 'FRIEND REQUEST' : 'YOU’RE INVITED'}</span><h2>${esc(i.name)} ${i.kind === 'friend' ? 'wants to be friends.' : 'challenges you.'}</h2><p>${i.kind === 'friend' ? 'Accept to add each other to your friends lists.' : 'A fresh board, a friendly rivalry. Ready to play?'}</p><div class="actions"><button class="primary" data-modal-action="accept-invite">Accept</button><button class="secondary" data-modal-action="close">Reject</button></div>`); |
| 210 | } |
| 211 | window.microchessPwa?.intro(); |
| 212 | } catch (e) { toast(e.message || 'Connection lost. We’ll try again shortly.'); } |
| 213 | } |
| 214 | function empty (yours) { return `<div class="empty"><span class="empty-icon">♘</span><h3>${yours ? 'Your next rivalry starts here.' : 'All caught up.'}</h3><p>${yours ? 'Challenge a friend or share a game link. Your games and invitations will appear here.' : 'Games appear here while your opponent is thinking.'}</p>${yours ? '<button class="text-button" data-create-link="match">Invite someone to play ↗</button>' : ''}</div>`; } |
| 215 | function renderGames () |
| 216 | { |
| 217 | if (!state) return; |
| 218 | clearTimeout(moveHoldTimer); |
| 219 | let relocating = false; |
| 220 | const now = performance.now(); |
| 221 | for (const [id, hold] of moveHolds) |
| 222 | { |
| 223 | const g = state.games.find(g => g.id === id); |
| 224 | if (hold.user !== state.user.id || !g || g.status !== 'active' || (g.version > hold.version && g.yourTurn)) |
| 225 | { |
| 226 | moveHolds.delete(id); continue; |
| 227 | } |
| 228 | // Start the pause when the confirmed board position is first displayed. |
| 229 | if (hold.until === null && g.version > hold.version) hold.until = now + 3000; |
| 230 | if (hold.until !== null && hold.until <= now && !drag) { moveHolds.delete(id); relocating = true; } |
| 231 | } |
| 232 | const deadlines = [...moveHolds.values()].filter(h => h.until !== null).map(h => h.until); |
| 233 | if (deadlines.length) moveHoldTimer = setTimeout(renderGames, Math.max(drag ? 100 : 1, Math.min(...deadlines) - now)); |
| 234 | const selector = '#main .game-card, .waiting-heading, #main > footer'; |
| 235 | const key = el => el.dataset.game || el.tagName; |
| 236 | const animate = !matchMedia('(prefers-reduced-motion: reduce)').matches && |
| 237 | (relocating || [...document.querySelectorAll(selector)].some(el => el.getAnimations().length)); |
| 238 | const before = new Map(animate ? [...document.querySelectorAll(selector)].map(el => [key(el), el.getBoundingClientRect()]) : []); |
| 239 | 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); |
| 240 | const waiting = state.games.filter(g => !yours.includes(g)); |
| 241 | $('#your-count').textContent = yours.length; $('#waiting-count').textContent = waiting.length + (state.matchmaking ? 1 : 0); |
| 242 | // Continue from the visible fill even when polling/selection recreates the cards mid-animation. |
| 243 | const materialBefore = new Map([...document.querySelectorAll('#main .material-bar')].map(el => |
| 244 | { |
| 245 | const fill = $('.material-white', el), animation = fill.getAnimations()[0]; |
| 246 | 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 }]; |
| 247 | })); |
| 248 | $('#your-games').innerHTML = yours.map(card).join('') || empty(true); |
| 249 | $('#waiting-games').innerHTML = (state.matchmaking ? matchmakingCard() : '') + waiting.map(card).join('') || empty(false); |
| 250 | const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches; |
| 251 | for (const el of document.querySelectorAll('#main .material-bar')) |
| 252 | { |
| 253 | const fill = $('.material-white', el), share = Number(el.dataset.share), old = materialBefore.get(el.closest('[data-game]').dataset.game); |
| 254 | // Prefer WAAPI over element.style — CSP style-src 'self' blocks inline CSSOM writes. |
| 255 | if (!reduced && old && Math.abs(old.share - share) > .0001) |
| 256 | fill.animate([{ transform: `scaleX(${old.share})` }, { transform: `scaleX(${share})` }], { duration: old.target === el.dataset.share ? old.remaining : 650, easing: 'linear', fill: 'forwards' }); |
| 257 | else |
| 258 | fill.animate([{ transform: `scaleX(${share})` }], { duration: 0, fill: 'forwards' }); |
| 259 | } |
| 260 | renderMoveFeedback(now, reduced); |
| 261 | window.microchessPwa?.highlight(); |
| 262 | if (animate) |
| 263 | { |
| 264 | for (const el of document.querySelectorAll(selector)) |
| 265 | { |
| 266 | const old = before.get(key(el)); |
| 267 | el.getAnimations().forEach(animation => animation.cancel()); |
| 268 | if (!old) continue; |
| 269 | const rect = el.getBoundingClientRect(), dx = old.left - rect.left, dy = old.top - rect.top; |
| 270 | if (Math.abs(dx) < 1 && Math.abs(dy) < 1) continue; |
| 271 | el.animate([ |
| 272 | { transform: `translate(${dx}px, ${dy}px)`, zIndex: 2 }, |
| 273 | { transform: 'translate(0, 0)', zIndex: 2 } |
| 274 | ], { duration: 650, easing: 'cubic-bezier(.22, 1, .36, 1)' }); |
| 275 | } |
| 276 | } |
| 277 | } |
| 278 | function card (g) |
| 279 | { |
| 280 | let content = ''; |
| 281 | if (g.replay) content = board(g); |
| 282 | else if (g.status === 'pending') content = `<div class="pending-content"><span class="big-icon">♘</span><h3>${g.incoming ? 'A little challenge?' : 'Challenge sent.'}</h3><p>${g.incoming ? `${esc(g.opponent)} invited you to play.<br>Your board is waiting.` : `Waiting for ${esc(g.opponent)}<br>to accept your challenge.`}</p>${g.incoming ? `<div class="actions"><button class="primary" data-game-action="accept">Accept</button><button class="secondary" data-game-action="reject">Reject</button></div>` : '<span class="inline-note"></span>'}</div>`; |
| 283 | else if (g.status === 'ended') content = `<div class="ended-board">${board(g)}<div class="end-content"><div class="end-status"><h3>${g.outcome === 'win' ? 'You won!' : g.outcome === 'loss' ? 'You lost' : 'A game well matched.'}</h3><small>${esc(g.reason)}</small>${g.opponentRematch && g.canRematch ? `<small>${esc(g.opponent)} wants a rematch.</small>` : ''}</div><div class="actions">${g.canRematch ? `<button class="primary" data-game-action="rematch" ${g.rematch ? 'disabled' : ''}>${g.rematch ? 'Requested' : 'Rematch'}</button>` : ''}<button class="secondary" data-game-action="exit">Exit</button></div></div></div>`; |
| 284 | else content = board(g) + `<div class="card-footer"><span class="${g.yourTurn ? 'turn-label' : ''}">${g.check ? 'Check · ' : ''}${g.yourTurn ? 'Your move' : 'Waiting for a move'}</span>${g.yourTurn ? `<button class="text-button" data-game-action="options" aria-label="Game options">${g.drawOffer === 'opponent' ? 'Draw offered · ' : ''}•••</button>` : `<span>Move ${Math.floor(g.state.ply / 2) + 1}</span>`}</div>`; |
| 285 | return `<article class="game-card ${!g.yourTurn && g.status === 'active' ? 'waiting' : ''}" data-game="${g.id}" aria-label="Game with ${esc(g.opponent)}"><div class="card-header">${avatarMarkup(g.opponent, g.opponentAvatar)}<div class="opponent-info"><strong><button class="opponent-name" data-opponent="${esc(g.opponentId)}">${esc(g.opponent)}</button> <small class="rating" aria-label="${g.opponentRating} Elo">${g.opponentRating}</small></strong>${g.status !== 'pending' ? materialBar(g) : ''}</div>${g.status !== 'pending' ? colorTagMarkup(g) : ''}${g.inactiveDays >= 7 ? '<button class="stop-inactive" data-game-action="stop-confirm" aria-label="Stop inactive game" title="Stop inactive game">×</button>' : ''}</div>${content}</article>`; |
| 286 | } |
| 287 | function materialBarSkinName (name, fallback) |
| 288 | { |
| 289 | return PIECE_COLOR_ORDER.includes(name) ? name : fallback; |
| 290 | } |
| 291 | function materialBarSkins (g) |
| 292 | { |
| 293 | if (customColoursDisabled()) return { left: 'White', right: 'Black' }; |
| 294 | return { |
| 295 | left: materialBarSkinName(g.pieceSkinWhite, 'White'), |
| 296 | right: materialBarSkinName(g.pieceSkinBlack, 'Black') |
| 297 | }; |
| 298 | } |
| 299 | function materialBar (g) |
| 300 | { |
| 301 | const totals = { w: 0, b: 0 }; |
| 302 | for (const p of g.state.board) if (p !== '.') totals[p === p.toUpperCase() ? 'w' : 'b'] += materialValues[p.toLowerCase()]; |
| 303 | const total = totals.w + totals.b, share = total ? totals.w / total : .5; |
| 304 | const { left, right } = materialBarSkins(g); |
| 305 | const you = g.color === 'w' ? left : right; |
| 306 | const label = `${left}: ${totals.w} material points. ${right}: ${totals.b} material points. You play ${you}${you === 'White' || you === 'Black' ? '' : ` (${g.color === 'w' ? 'White' : 'Black'})`}.`; |
| 307 | const ariaSides = left === 'White' && right === 'Black' |
| 308 | ? 'White on the left and Black on the right' |
| 309 | : `${left} (White) on the left and ${right} (Black) on the right`; |
| 310 | // Classes only — inline style= is blocked by CSP style-src 'self'. |
| 311 | return `<div class="material-bar material-right-${right.toLowerCase()}" data-share="${share}" role="meter" aria-label="Material balance, ${esc(ariaSides)}" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${Math.round(share * 100)}" aria-valuetext="${esc(label)}" title="${esc(label)} Pawn 1 · Knight/Bishop 3 · Rook 5 · Queen 9. Kings are not counted." tabindex="0"><span class="material-white material-left-${left.toLowerCase()}"></span></div>`; |
| 312 | } |
| 313 | function renderMoveFeedback (now, reduced) |
| 314 | { |
| 315 | for (const [id, feedback] of moveFeedback) |
| 316 | { |
| 317 | const g = state.games.find(g => g.id === id); |
| 318 | if (feedback.user !== state.user.id || !g || g.state.ply > feedback.ply) { moveFeedback.delete(id); continue; } |
| 319 | if (g.state.ply !== feedback.ply) continue; |
| 320 | if (feedback.start === null) |
| 321 | { |
| 322 | feedback.start = now; |
| 323 | setTimeout(() => |
| 324 | { |
| 325 | if (moveFeedback.get(id) !== feedback) return; |
| 326 | moveFeedback.delete(id); |
| 327 | document.querySelector(`[data-game="${id}"] .move-feedback`)?.remove(); |
| 328 | }, 1800); |
| 329 | } |
| 330 | const elapsed = now - feedback.start; |
| 331 | if (elapsed >= 1800) { moveFeedback.delete(id); continue; } |
| 332 | const el = document.querySelector(`[data-game="${id}"]`); if (!el) continue; |
| 333 | const overlay = document.createElement('div'); |
| 334 | overlay.className = `move-feedback ${feedback.quality}`; |
| 335 | const label = { good: 'Looks good', poor: 'Watch out' }[feedback.quality]; |
| 336 | el.append(overlay); |
| 337 | if (reduced) { overlay.style.opacity = '1'; continue; } |
| 338 | const frames = [{ opacity: 0, offset: 0 }, { opacity: 1, offset: .15 }, { opacity: .25, offset: .4 }, { opacity: 1, offset: .65 }, { opacity: 0, offset: 1 }]; |
| 339 | const animation = overlay.animate(frames, { duration: 1800, easing: 'ease-in-out' }); |
| 340 | animation.currentTime = elapsed; |
| 341 | } |
| 342 | } |
| 343 | function board (g) |
| 344 | { |
| 345 | const indices = Array.from({ length: 20 }, (_, i) => g.color === 'w' ? i : 19 - i); |
| 346 | const active = selected?.game === g.id ? selected.from : null; |
| 347 | const legal = g.legal.filter(m => m.from === active).map(m => m.to); |
| 348 | let html = '<div class="board-wrap"><div class="board" role="group" aria-label="Microchess board">'; |
| 349 | indices.forEach((i, view) => |
| 350 | { |
| 351 | const p = g.state.board[i], square = String.fromCharCode(97 + i % 4) + (5 - Math.floor(i / 4)); |
| 352 | const last = g.state.last && (i === g.state.last.from || i === g.state.last.to); |
| 353 | const checked = g.check && p.toLowerCase() === 'k' && (p === p.toUpperCase() ? 'w' : 'b') === g.state.turn; |
| 354 | const label = `${square}${p !== '.' ? ' ' + (p === p.toUpperCase() ? 'white ' : 'black ') + names[p.toLowerCase()] : ''}${legal.includes(i) ? ', legal destination' : ''}`; |
| 355 | html += `<button class="square ${(i % 4 + Math.floor(i / 4)) % 2 === 0 ? 'dark' : ''} ${active === i ? 'selected' : ''} ${legal.includes(i) ? 'legal' : ''} ${p !== '.' ? 'occupied' : ''} ${last ? 'last' : ''} ${checked ? 'checked' : ''}" data-square="${i}" aria-label="${label}" ${g.yourTurn ? '' : 'disabled'} ${active === i ? 'aria-pressed="true"' : ''}>${p !== '.' ? `<img src="${pieceUrl(p, skinForPiece(g, p))}" alt="" draggable="false">` : ''}${view % 4 === 0 ? `<span class="coordinate rank">${5 - Math.floor(i / 4)}</span>` : ''}${view >= 16 ? `<span class="coordinate">${String.fromCharCode(97 + i % 4)}</span>` : ''}</button>`; |
| 356 | }); |
| 357 | html += '</div>'; |
| 358 | if (promotion?.game === g.id) html += `<div class="promotion" role="group" aria-label="Choose promotion"><span class="eyebrow">A NEW POSSIBILITY</span><h3>Promote your pawn</h3><p>Choose the piece for your next chapter.</p><div class="promotion-options">${['q', 'r', 'b', 'n'].map(p => `<button data-promotion="${p}"><img src="${pieceUrl(g.color === 'w' ? p.toUpperCase() : p, displayColorFor(g))}" alt="">${names[p]}</button>`).join('')}</div><button class="text-button" data-cancel-promotion>Cancel</button></div>`; |
| 359 | return html + '</div>'; |
| 360 | } |
| 361 | function renderFriends () |
| 362 | { |
| 363 | $('#friend-count').textContent = state.friends.length; $('#sidebar-count').textContent = state.friends.length; |
| 364 | $('#friend-list').innerHTML = state.friends.map(f => `<button class="friend" data-friend="${esc(f.id)}">${avatarMarkup(f.name, f.avatar)}<span><strong>${esc(f.name)}</strong><small>${f.rating} Elo · ${f.wins} wins · ${f.losses} losses · ${f.ties} ties</small></span><span>↗</span></button>`).join('') || '<p class="inline-note">Your friends will appear here.<br>Send an invitation to get started.</p>'; |
| 365 | const incoming = state.friendRequests.filter(r => r.incoming); |
| 366 | $('#friend-requests').innerHTML = incoming.length ? '<div class="friends-label">PENDING REQUESTS</div>' + incoming.map(r => `<div class="friend-request">${avatarMarkup(r.name, r.avatar)}<div><strong>${esc(r.name)}</strong><div class="actions"><button class="primary" data-request-action="accept_friend_request" data-request-user="${esc(r.id)}">Accept</button><button class="secondary" data-request-action="reject_friend_request" data-request-user="${esc(r.id)}">Reject</button></div></div></div>`).join('') : ''; |
| 367 | $('#friend-count').textContent = state.friends.length + incoming.length; |
| 368 | $('#account-summary').innerHTML = `${avatarMarkup(state.user.name, state.user.avatar, true)}<button type="button" id="color-pref-button" class="account-name-button" title="Piece colours"><span>${esc(state.user.name)}</span><small>${state.user.rating} Elo</small></button><button id="history-button" class="text-button" aria-label="Game history" title="Game history">⌛</button>`; |
| 369 | } |
| 370 | function showRivalry (id) |
| 371 | { |
| 372 | const friend = state.friends.find(f => f.id === id); |
| 373 | const game = state.games.find(g => g.opponentId === id); |
| 374 | const f = friend || (game && { id, name: game.opponent, ...game.rivalry }); |
| 375 | if (!f) return; |
| 376 | const request = state.friendRequests.find(r => r.id === id); |
| 377 | const actions = friend |
| 378 | ? '<button class="primary" data-friend-action="challenge">Challenge to a game ↗</button><button class="text-button" data-friend-action="remove">Remove friend…</button>' |
| 379 | : request?.incoming |
| 380 | ? `<button class="primary" data-request-action="accept_friend_request" data-request-user="${esc(id)}">Accept friend request</button><button class="secondary" data-request-action="reject_friend_request" data-request-user="${esc(id)}">Reject</button>` |
| 381 | : request |
| 382 | ? '<button class="secondary" disabled>Friend request sent</button>' |
| 383 | : `<button class="primary" data-request-action="send_friend_request" data-request-user="${esc(id)}">Send friend request</button>`; |
| 384 | showModal(`<span class="eyebrow">YOUR FRIENDLY RIVALRY</span><h2>${esc(f.name)}</h2><div class="stats"><div><strong>${f.wins}</strong><span>Wins</span></div><div><strong>${f.losses}</strong><span>Losses</span></div><div><strong>${f.ties}</strong><span>Ties</span></div></div><div class="settings-actions">${actions}</div>`); |
| 385 | $('#modal-content').dataset.friend = id; |
| 386 | $('#modal-content').dataset.rivalry = id; |
| 387 | } |
| 388 | function refreshRivalry () |
| 389 | { |
| 390 | const id = $('#modal-content').dataset.rivalry; |
| 391 | if (modal.open && id) showRivalry(id); |
| 392 | } |
| 393 | function options (g) { showModal(`<h2>Your game with ${esc(g.opponent)}</h2><p>${g.check ? 'You are in check. Find a move that protects your king.' : 'Take your time. The board will be here.'}</p><div class="settings-actions">${g.drawOffer === 'opponent' ? '<button class="primary" data-option="accept_draw">Accept draw</button>' : g.drawOffer === 'you' ? '<p>Draw offered. Make your move to pass the offer to your opponent.</p>' : '<button class="secondary" data-option="offer_draw">Offer a draw</button>'}${g.claimable ? '<button class="secondary" data-option="claim_draw">Claim draw</button>' : '<button class="secondary" data-option="claim-intended">Claim draw with intended move</button>'}<button class="danger" data-option="resign-confirm">Resign…</button></div>`); $('#modal-content').dataset.game = g.id; } |
| 394 | function chooseSquare (g, i) |
| 395 | { |
| 396 | if (!g.yourTurn || busy || promotion) return; |
| 397 | if (selected?.game === g.id && g.legal.some(m => m.from === selected.from && m.to === i)) { attemptMove(g, selected.from, i); return; } |
| 398 | const p = g.state.board[i]; |
| 399 | 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 }; } |
| 400 | else selected = null; |
| 401 | renderGames(); |
| 402 | } |
| 403 | let claimIntended = null; |
| 404 | function attemptMove (g, from, to, promote) |
| 405 | { |
| 406 | const moves = g.legal.filter(m => m.from === from && m.to === to); if (!moves.length) return; |
| 407 | if (moves[0].promotion && !promote) { promotion = { game: g.id, from, to }; renderGames(); return; } |
| 408 | const kind = claimIntended === g.id ? 'claim_draw' : 'move'; claimIntended = null; |
| 409 | action({ action: kind, game: g.id, version: g.version, from, to, promotion: promote ?? null }); |
| 410 | } |
| 411 | function matchmakingCard () |
| 412 | { |
| 413 | const searching = state.matchmaking.status === 'searching'; |
| 414 | return `<article class="game-card"><div class="pending-content"><span class="big-icon">♘</span><h3>${searching ? 'Finding an opponent…' : 'No opponent found'}</h3><div class="actions">${searching ? '' : '<button class="primary" data-matchmaking="join_matchmaking">Try again</button>'}<button class="secondary" data-matchmaking="cancel_matchmaking">${searching ? 'Cancel search' : 'Dismiss'}</button></div></div></article>`; |
| 415 | } |
| 416 | function renderMatchmaking () |
| 417 | { |
| 418 | const target = $('#matchmaking-actions'); |
| 419 | if (!target || !state) return; |
| 420 | target.innerHTML = state.matchmaking?.status === 'searching' |
| 421 | ? '<p role="status">Finding an opponent…</p><button class="secondary" data-matchmaking="cancel_matchmaking">Cancel search</button>' |
| 422 | : '<button class="secondary" data-matchmaking="join_matchmaking">Challenge a random player</button>'; |
| 423 | } |
| 424 | async function createLink (kind) { await action({ action: 'create_link', kind }, r => { showModal(`<span class="eyebrow">${kind === 'friend' ? 'GOOD COMPANY' : 'GAME ON'}</span><h2>${kind === 'friend' ? 'Invite a friend.' : 'Send a little challenge.'}</h2><p>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.</p><input aria-label="Invitation link" id="share-url" readonly value="${esc(r.url)}"><div class="actions"><button class="primary" data-modal-action="copy">Copy link ↗</button></div>${kind === 'match' ? '<div id="matchmaking-actions" class="settings-actions"></div>' : ''}`); renderMatchmaking(); }); } |
| 425 | if ($('#match-link')) $('#match-link').onclick = () => createLink('match'); |
| 426 | if ($('#friend-link')) $('#friend-link').onclick = () => createLink('friend'); |
| 427 | if ($('#settings-button')) $('#settings-button').onclick = () => { if (!state) return; showModal(`<h2>Your account</h2><p>Signed in as ${esc(state.user.name)}.</p><p>${state.user.rating} Elo</p><label class="settings-check"><input type="checkbox" id="disable-custom-colours" ${customColoursDisabled() ? 'checked' : ''}> Disable custom colours</label><div id="notification-settings"></div><div class="settings-actions"><button class="secondary" data-install-app>Add to home screen</button><p id="install-help" hidden></p>${state.local ? `<button class="secondary" data-modal-action="switch">Switch to ${state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1'}</button>` : ''}<a class="button secondary" href="api.php?action=export" download>Export my data (JSON)</a><button class="secondary" data-modal-action="logout">Sign out</button></div>`); $('#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(); }; |
| 428 | if ($('#rules-button')) $('#rules-button').onclick = () => showModal(`<span class="eyebrow">MICROCHESS</span><h2>Small board. Real chess.</h2><p>The usual rules of chess, on a 4 × 5 board.</p><ul class="rules-list"><li>Each side starts with a king, rook, bishop, knight and one pawn. White moves first.</li><li>Pawns move one square forward, capture diagonally and never move two squares. There is no castling or en passant.</li><li>Reach the last rank to promote to a queen, rook, bishop or knight.</li><li>Protect your king. Checkmate wins; stalemate and dead positions draw.</li><li>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.</li><li>Click a piece to see legal destinations, then click a dot. Or drag it to a destination.</li><li>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.</li><li>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.</li></ul><p class="inline-note">Pieces by Cburnett, from <a href="https://commons.wikimedia.org/wiki/Category:SVG_chess_pieces" target="_blank" rel="noreferrer">Wikimedia Commons</a>, <a href="https://creativecommons.org/licenses/by-sa/3.0/" target="_blank" rel="noreferrer">CC BY-SA 3.0</a>. Unmodified SVGs.</p>`); |
| 429 | document.addEventListener('click', e => |
| 430 | { |
| 431 | const el = e.target.closest('button'); if (!el) return; |
| 432 | const gameEl = el.closest('[data-game]'); const g = gameEl && state?.games.find(g => g.id === Number(gameEl.dataset.game)); |
| 433 | 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.'); }); |
| 434 | if (el.dataset.matchmaking) action({ action: el.dataset.matchmaking }, () => { if (modal.open) closeModal(); }); |
| 435 | if (el.id === 'history-button') showHistory(); |
| 436 | if (el.id === 'avatar-button') chooseAvatar(); |
| 437 | if (el.id === 'color-pref-button') openColorPreferences(); |
| 438 | if (el.dataset.createLink) createLink(el.dataset.createLink); |
| 439 | if (el.hasAttribute('data-square') && g) { if (suppressClick) { suppressClick = false; return; } chooseSquare(g, Number(el.dataset.square)); } |
| 440 | if (el.dataset.gameAction && g) { if (el.dataset.gameAction === 'stop-confirm') { showModal(`<h2 id="modal-title">Stop this game?</h2><p>This game has been inactive for ${g.inactiveDays} days. Would you like to stop it?</p><div class="actions"><button class="danger" data-stop-game="${g.id}" data-version="${g.version}">Stop game</button><button class="secondary" data-modal-action="close">Cancel</button></div>`); } else if (el.dataset.gameAction === 'options') options(g); else action({ action: el.dataset.gameAction, game: g.id, version: g.version }); } |
| 441 | if (el.dataset.promotion && g && promotion) attemptMove(g, promotion.from, promotion.to, el.dataset.promotion); |
| 442 | if (el.hasAttribute('data-cancel-promotion')) { promotion = null; claimIntended = null; renderGames(); } |
| 443 | if (el.dataset.friend || el.dataset.opponent) showRivalry(el.dataset.friend || el.dataset.opponent); |
| 444 | }); |
| 445 | $('#modal-content').addEventListener('click', async e => |
| 446 | { |
| 447 | const b = e.target.closest('button'); if (!b) return; |
| 448 | if (b.dataset.stopGame) { await action({ action: 'stop_inactive', game: Number(b.dataset.stopGame), version: Number(b.dataset.version) }, () => closeModal()); return; } |
| 449 | if (b.dataset.avatarGroup) { avatarGroup = b.dataset.avatarGroup; renderAvatarChoices(); return; } |
| 450 | if (b.hasAttribute('data-avatar-choice')) { await action({ action: 'set_avatar', avatar: b.dataset.avatarChoice || null }, () => { closeModal(); toast('Avatar updated.'); }); return; } |
| 451 | if (b.dataset.modalAction === 'close') closeModal(); |
| 452 | if (b.dataset.modalAction === 'accept-invite') await action({ action: 'accept_link', token: inviteToken }, () => { closeModal(); toast('Invitation accepted.'); }); |
| 453 | 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.'); } } |
| 454 | 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(); }); |
| 455 | if (b.dataset.modalAction === 'logout') await action({ action: 'logout', endpoint: await window.microchessPwa?.endpoint() }, () => location.reload()); |
| 456 | if (b.dataset.friendAction) |
| 457 | { |
| 458 | const id = $('#modal-content').dataset.friend; |
| 459 | if (b.dataset.friendAction === 'remove') { showModal('<h2>Remove this friend?</h2><p>You will both be removed from each other’s friends list. Your game history is kept.</p><div class="actions"><button class="danger" data-friend-action="confirm-remove">Remove friend</button><button class="secondary" data-modal-action="close">Cancel</button></div>'); } |
| 460 | else await action({ action: b.dataset.friendAction === 'challenge' ? 'challenge' : 'remove_friend', friend: id }, () => { closeModal(); toast(b.dataset.friendAction === 'challenge' ? 'Challenge sent.' : 'Friend removed.'); }); |
| 461 | } |
| 462 | if (b.dataset.option) |
| 463 | { |
| 464 | const g = state.games.find(g => g.id === Number($('#modal-content').dataset.game)); if (!g) return; |
| 465 | if (b.dataset.option === 'resign-confirm') { showModal('<h2>Resign this game?</h2><p>Your opponent will win this game. You can request a rematch afterwards.</p><div class="actions"><button class="danger" data-option="resign">Resign</button><button class="secondary" data-modal-action="close">Cancel</button></div>'); return; } |
| 466 | if (b.dataset.option === 'claim-intended') { claimIntended = g.id; closeModal(); toast('Select your intended move to claim a draw.'); return; } |
| 467 | await action({ action: b.dataset.option, game: g.id, version: g.version }, () => closeModal()); |
| 468 | } |
| 469 | }); |
| 470 | $('#modal-content').addEventListener('change', e => { if (e.target.id === 'avatar-color') { avatarColor = e.target.value; renderAvatarChoices(); } }); |
| 471 | let suppressClick = false; |
| 472 | document.addEventListener('pointerdown', e => |
| 473 | { |
| 474 | const sq = e.target.closest('[data-square]'); if (!sq || e.button !== 0 || busy || promotion) return; |
| 475 | const g = state?.games.find(g => g.id === Number(sq.closest('[data-game]').dataset.game)); if (!g?.yourTurn) return; |
| 476 | const from = Number(sq.dataset.square), p = g.state.board[from]; if (p === '.' || (p === p.toUpperCase() ? 'w' : 'b') !== g.color) return; |
| 477 | drag = { game: g.id, from, p, x: e.clientX, y: e.clientY, id: e.pointerId, moving: false }; |
| 478 | }); |
| 479 | document.addEventListener('pointermove', e => |
| 480 | { |
| 481 | if (!drag || e.pointerId !== drag.id) return; |
| 482 | 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); } |
| 483 | if (drag.moving) { e.preventDefault(); const img = $('.drag-ghost'); img.style.left = e.clientX + 'px'; img.style.top = e.clientY + 'px'; } |
| 484 | }, { passive: false }); |
| 485 | document.addEventListener('pointerup', e => |
| 486 | { |
| 487 | if (!drag || e.pointerId !== drag.id) return; const d = drag; drag = null; $('.drag-ghost')?.remove(); |
| 488 | 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)); } |
| 489 | }); |
| 490 | document.addEventListener('pointercancel', () => { drag = null; $('.drag-ghost')?.remove(); }); |
| 491 | refresh(); setInterval(() => { if (!document.hidden) refresh(); }, 2500); document.addEventListener('visibilitychange', () => { if (!document.hidden) refresh(); }); |
| 492 | |
| 493 | let replay = null, replayTimer = null, historyRequest = 0; |
| 494 | function stopReplay () { clearInterval(replayTimer); replayTimer = null; } |
| 495 | async function historyFetch (query) |
| 496 | { |
| 497 | const response = await fetch('api.php?action=' + query); |
| 498 | const data = await response.json(); |
| 499 | if (!response.ok) throw new Error(data.error || 'Unable to load saved games.'); |
| 500 | return data; |
| 501 | } |
| 502 | async function showHistory () |
| 503 | { |
| 504 | const request = ++historyRequest; |
| 505 | showModal('<h2 id="modal-title">Game history</h2><p>Loading saved games…</p>'); |
| 506 | try { |
| 507 | const games = await historyFetch('history'); |
| 508 | if (request !== historyRequest || !modal.open || $('#modal-title')?.textContent !== 'Game history') return; |
| 509 | $('#modal-content').innerHTML = `<h2 id="modal-title">Game history</h2><div class="history-list">${games.map(g => `<button class="secondary history-entry" data-replay-id="${g.id}"><strong>${esc(g.opponent)}</strong><span>${g.outcome === 'win' ? 'Won' : g.outcome === 'loss' ? 'Lost' : 'Draw'}</span><time datetime="${new Date(g.ended * 1000).toISOString()}">${esc(new Date(g.ended * 1000).toLocaleDateString())}</time></button>`).join('') || '<p>No saved games yet.</p>'}</div>`; |
| 510 | } catch (e) { toast(e.message); } |
| 511 | } |
| 512 | async function openReplay (id) |
| 513 | { |
| 514 | const source = $('#modal-content').firstElementChild; |
| 515 | const request = ++historyRequest; |
| 516 | try { |
| 517 | const game = await historyFetch('replay&id=' + id); |
| 518 | if (request !== historyRequest || !modal.open || source !== $('#modal-content').firstElementChild) return; |
| 519 | showReplay(game); |
| 520 | } catch (e) { toast(e.message); } |
| 521 | } |
| 522 | function showReplay (game) |
| 523 | { |
| 524 | const content = '<div id="replay-card"></div><div class="replay-controls"><button class="secondary" data-replay-control="start" aria-label="Jump to start" title="Jump to start">⏮</button><button class="secondary" data-replay-control="back" aria-label="Step back" title="Step back">⏪</button><button class="primary" data-replay-control="play" aria-label="Play">▶</button><button class="secondary" data-replay-control="next" aria-label="Step forward" title="Step forward">⏩</button><button class="secondary" data-replay-control="end" aria-label="Jump to end" title="Jump to end">⏭</button></div><p id="replay-progress" aria-live="polite"></p><div class="replay-bottom">' + (game.shared ? '<a class="text-button" href="./">Microchess ↗</a>' : '<button class="text-button" id="history-return">← Game history</button>') + '<button class="text-button" id="replay-share" aria-label="Copy game link" title="Copy game link">🔗</button></div>'; |
| 525 | if ($('#replay-page')) { stopReplay(); $('#modal-content').innerHTML = content; } |
| 526 | else { showModal(content); modal.classList.add('replay-modal'); } |
| 527 | replay = { ...game, index: 0 }; |
| 528 | renderReplay(); |
| 529 | } |
| 530 | async function copyReplayLink () |
| 531 | { |
| 532 | const url = new URL('./', location.href); url.searchParams.set('replay', replay.shareToken); |
| 533 | try { await navigator.clipboard.writeText(url.href); toast('Game link copied.'); } |
| 534 | catch { |
| 535 | // Keep a usable copy fallback when clipboard access is unavailable. |
| 536 | const input = document.createElement('input'); input.value = url.href; input.readOnly = true; input.setAttribute('aria-label', 'Game link'); |
| 537 | $('.replay-bottom').append(input); input.select(); toast('Select and copy the game link.'); |
| 538 | } |
| 539 | } |
| 540 | function renderReplay () |
| 541 | { |
| 542 | if (!replay || !$('#replay-card')) return; |
| 543 | const g = { ...replay, id: 'replay', replay: true, status: 'replay', yourTurn: false, legal: [], check: false, state: replay.positions[replay.index] }; |
| 544 | const whiteTip = !customColoursDisabled() && (replay.pieceSkinWhite || 'White') !== 'White' ? `Playing as ${replay.pieceSkinWhite} (White)` : 'Playing as White'; |
| 545 | const blackTip = !customColoursDisabled() && (replay.pieceSkinBlack || 'Black') !== 'Black' ? `Playing as ${replay.pieceSkinBlack} (Black)` : 'Playing as Black'; |
| 546 | $('#replay-card').innerHTML = `<article class="game-card" data-game="replay"><div class="card-header replay-players" id="modal-title"><span title="${esc(whiteTip)}"><img src="${pieceUrl('K', replay.pieceSkinWhite || 'White')}" alt="${esc(replay.pieceSkinWhite || 'White')}">${esc(replay.whiteName)}</span><span aria-hidden="true">–</span><span title="${esc(blackTip)}"><img src="${pieceUrl('k', replay.pieceSkinBlack || 'Black')}" alt="${esc(replay.pieceSkinBlack || 'Black')}">${esc(replay.blackName)}</span></div>${board(g)}</article>`; |
| 547 | $('#replay-progress').textContent = `${replay.index} / ${replay.positions.length - 1} · ${replay.shared ? replay.outcome : replay.outcome === 'win' ? 'Won' : replay.outcome === 'loss' ? 'Lost' : 'Draw'} · ${replay.reason}`; |
| 548 | const last = replay.positions.length - 1; |
| 549 | $('[data-replay-control="play"]').textContent = replayTimer ? '⏸' : '▶'; |
| 550 | $('[data-replay-control="play"]').setAttribute('aria-label', replayTimer ? 'Pause' : 'Play'); |
| 551 | $('[data-replay-control="play"]').disabled = last < 1; |
| 552 | $('[data-replay-control="start"]').disabled = $('[data-replay-control="back"]').disabled = replay.index === 0; |
| 553 | $('[data-replay-control="next"]').disabled = $('[data-replay-control="end"]').disabled = replay.index === last; |
| 554 | } |
| 555 | $('#modal-content').addEventListener('click', e => { |
| 556 | const b = e.target.closest('button'); if (!b) return; |
| 557 | if (b.dataset.replayId) openReplay(b.dataset.replayId); |
| 558 | if (b.id === 'history-return') showHistory(); |
| 559 | if (b.id === 'replay-share') copyReplayLink(); |
| 560 | const control = b.dataset.replayControl; |
| 561 | if (!control || !replay) return; |
| 562 | if (control === 'play') { |
| 563 | if (replayTimer) stopReplay(); |
| 564 | else { |
| 565 | if (replay.index === replay.positions.length - 1) replay.index = 0; |
| 566 | replayTimer = setInterval(() => { |
| 567 | replay.index++; |
| 568 | if (replay.index >= replay.positions.length - 1) stopReplay(); |
| 569 | renderReplay(); |
| 570 | }, 500); |
| 571 | } |
| 572 | } else { |
| 573 | stopReplay(); |
| 574 | const last = replay.positions.length - 1; |
| 575 | replay.index = control === 'start' ? 0 : control === 'end' ? last : Math.max(0, Math.min(last, replay.index + (control === 'back' ? -1 : 1))); |
| 576 | } |
| 577 | renderReplay(); |
| 578 | }); |
| 579 | const savedAnimations = new Set(); |
| 580 | function animateSavedGames () |
| 581 | { |
| 582 | for (const g of state.games) { |
| 583 | if (!g.replayId) continue; |
| 584 | const key = `microchess-saved:${state.user.id}:${g.replayId}`; |
| 585 | let seen = savedAnimations.has(key); |
| 586 | try { seen ||= localStorage.getItem(key) === '1'; } catch {} |
| 587 | const tile = $(`#your-games [data-game="${g.id}"]`), target = $('#history-button'); |
| 588 | if (seen || !tile || !target || !target.getBoundingClientRect().width) continue; |
| 589 | savedAnimations.add(key); |
| 590 | try { localStorage.setItem(key, '1'); } catch {} |
| 591 | if (matchMedia('(prefers-reduced-motion: reduce)').matches) continue; |
| 592 | const start = tile.getBoundingClientRect(), end = target.getBoundingClientRect(); |
| 593 | const icon = document.createElement('span'); icon.className = 'saved-hourglass'; icon.textContent = '⌛'; icon.setAttribute('aria-hidden', 'true'); |
| 594 | icon.style.left = `${start.left + start.width / 2 - 12}px`; icon.style.top = `${start.top + 45}px`; document.body.append(icon); |
| 595 | 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)' }); |
| 596 | flight.onfinish = () => { icon.remove(); $('#history-button')?.animate([{ transform: 'translateY(0)' }, { transform: 'translateY(-9px)' }, { transform: 'translateY(0)' }], { duration: 360, easing: 'ease-out' }); }; |
| 597 | } |
| 598 | } |
| 599 | |
| 600 | if (new URLSearchParams(location.search).has('replay')) { |
| 601 | const token = new URLSearchParams(location.search).get('replay'); |
| 602 | fetch('api.php?action=shared_replay&token=' + encodeURIComponent(token), { credentials: 'omit' }).then(async response => { |
| 603 | const data = await response.json(); |
| 604 | if (!response.ok) throw new Error(data.error || 'Unable to load saved games.'); |
| 605 | showReplay(data); |
| 606 | }).catch(e => { |
| 607 | $('#modal-content').innerHTML = `<h1>Game unavailable</h1><p>${esc(e.message)}</p>`; |
| 608 | }); |
| 609 | } |
projects-timfalken-com microchess