BlueGit

projects-timfalken-com microchess

Files

microchess / web / assets / app.js

app.js

tweaks
timfa Tim Falken · pushed by timfa · 2 months ago
005905a2 History
app.js 31.0 KiB Download Raw
1'use strict';
2const $ = (s, root = document) => root.querySelector(s);
3const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
4const names = { p: 'Pawn', r: 'Rook', n: 'Knight', b: 'Bishop', q: 'Queen', k: 'King' };
5const materialValues = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 };
6const pieceUrl = p => `assets/pieces/${p.toLowerCase()}${p === p.toUpperCase() ? 'l' : 'd'}t.svg`;
7const initials = name => esc(name.slice(0, 2).toUpperCase());
8const avatarUrl = id => `assets/avatars/${encodeURIComponent(id)}.png`;
9function avatarMarkup (name, id, editable = false)
10{
11 const content = id ? `<img src="${avatarUrl(id)}" alt="" draggable="false">` : initials(name);
12 return editable ? `<button id="avatar-button" class="avatar" aria-label="Choose your avatar" title="Choose your avatar">${content}</button>` : `<span class="avatar">${content}</span>`;
13}
14let avatarOptions = null, avatarGroup = 'all', avatarColor = 'all';
15async function chooseAvatar ()
16{
17 if (!state) return;
18 showModal('<h2 id="modal-title">Choose your avatar</h2><p>Loading the pieces…</p>');
19 modal.classList.add('avatar-picker');
20 try
21 {
22 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(); }
23 if (!modal.open || !modal.classList.contains('avatar-picker')) return;
24 avatarGroup = 'all'; avatarColor = 'all';
25 $('#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 from Wikimedia Commons by C. Burnett and Iago Casabiell González. <a href="assets/avatars/CREDITS.md" target="_blank" rel="noopener">Sources &amp; licenses ↗</a></p>`;
26 renderAvatarChoices();
27 } catch (e) { toast(e.message); if (modal.classList.contains('avatar-picker')) closeModal(); }
28}
29function renderAvatarChoices ()
30{
31 const options = avatarOptions.filter(a => (avatarGroup === 'all' || a.group === avatarGroup) && (avatarColor === 'all' || a.color === avatarColor));
32 $('#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>';
33 $('#avatar-option-count').textContent = `${options.length} pieces`;
34 document.querySelectorAll('[data-avatar-group]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.avatarGroup === avatarGroup)));
35}
36let state, selected = null, promotion = null, busy = false, drag = null, lastRender = '', toastTimer, inviteShown = false;
37const moveHolds = new Map();
38const moveFeedback = new Map();
39let moveHoldTimer;
40let inviteToken = new URLSearchParams(location.search).get('invite');
41const modal = $('#modal');
42function toast (message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 5000); }
43function showModal (html) { modal.classList.remove('avatar-picker'); $('#modal-content').innerHTML = html; if (!modal.open) modal.showModal(); }
44function closeModal () { modal.close(); }
45$('#modal-close').onclick = closeModal;
46modal.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(); } });
47function dismissInvite () { inviteToken = null; history.replaceState(null, '', location.pathname); }
48modal.addEventListener('close', () => { if (inviteShown) dismissInvite(); });
49const mobileLayout = matchMedia('(max-width: 760px)');
50function showSidebar (open)
51{
52 const sidebar = $('#sidebar'); if (!sidebar) return;
53 sidebar.classList.toggle('open', open);
54 sidebar.inert = mobileLayout.matches && !open;
55 $('#sidebar-backdrop').hidden = !open;
56 $('#friends-toggle').setAttribute('aria-expanded', String(open));
57 $('#main').inert = mobileLayout.matches && open;
58 document.body.classList.toggle('sidebar-open', mobileLayout.matches && open);
59 if (open) $('#friends-close').focus();
60 else if (mobileLayout.matches) $('#friends-toggle').focus();
61}
62mobileLayout.addEventListener('change', () => showSidebar(false));
63if ($('#sidebar')) $('#sidebar').inert = mobileLayout.matches;
64$('#friends-toggle').onclick = () => showSidebar(!$('#sidebar').classList.contains('open'));
65if ($('#friends-close')) $('#friends-close').onclick = () => showSidebar(false);
66if ($('#sidebar-backdrop')) $('#sidebar-backdrop').onclick = () => showSidebar(false);
67document.addEventListener('keydown', e => { if (e.key === 'Escape') { showSidebar(false); selected = null; promotion = null; claimIntended = null; renderGames(); } });
68async function api (data)
69{
70 const response = await fetch('api.php', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': state.csrf }, body: JSON.stringify(data) });
71 const result = await response.json(); if (!response.ok) throw new Error(result.error || 'Request failed.'); return result;
72}
73async function action (data, success)
74{
75 if (busy) return; busy = true;
76 try
77 {
78 const result = await api(data);
79 if (data.action === 'move')
80 {
81 moveHolds.set(data.game, { user: state.user.id, version: data.version, until: null });
82 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 });
83 }
84 selected = null; promotion = null; if (success) await success(result); await refresh(true);
85 }
86 catch (e) { toast(e.message); await refresh(true); }
87 finally { busy = false; }
88}
89async function refresh (force = false)
90{
91 if (!$('#your-games') || (busy && !force) || drag) return;
92 try
93 {
94 const response = await fetch('api.php' + (inviteToken ? '?invite=' + encodeURIComponent(inviteToken) : ''));
95 const data = await response.json();
96 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' + (inviteToken ? '?invite=' + encodeURIComponent(inviteToken) : '') + '">Sign in</a>'); return; }
97 if (!response.ok) throw new Error(data.error || 'Unable to load games.');
98 state = data;
99 if (selected) { const g = state.games.find(g => g.id === selected.game); if (!g?.yourTurn || g.version !== selected.version) { selected = null; promotion = null; } }
100 const signature = JSON.stringify(data);
101 if (signature !== lastRender) { lastRender = signature; renderGames(); renderFriends(); }
102 if (data.invite && !inviteShown)
103 {
104 inviteShown = true; const i = data.invite;
105 if (i.error) showModal(`<h2>Invitation</h2><p>${esc(i.error)}</p><button class="primary" data-modal-action="close">Got it</button>`);
106 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>`);
107 }
108 } catch (e) { toast(e.message || 'Connection lost. We’ll try again shortly.'); }
109}
110function 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>`; }
111function renderGames ()
112{
113 if (!state) return;
114 clearTimeout(moveHoldTimer);
115 let relocating = false;
116 const now = performance.now();
117 for (const [id, hold] of moveHolds)
118 {
119 const g = state.games.find(g => g.id === id);
120 if (hold.user !== state.user.id || !g || g.status !== 'active' || (g.version > hold.version && g.yourTurn))
121 {
122 moveHolds.delete(id); continue;
123 }
124 // Start the pause when the confirmed board position is first displayed.
125 if (hold.until === null && g.version > hold.version) hold.until = now + 3000;
126 if (hold.until !== null && hold.until <= now && !drag) { moveHolds.delete(id); relocating = true; }
127 }
128 const deadlines = [...moveHolds.values()].filter(h => h.until !== null).map(h => h.until);
129 if (deadlines.length) moveHoldTimer = setTimeout(renderGames, Math.max(drag ? 100 : 1, Math.min(...deadlines) - now));
130 const selector = '.game-card, .waiting-heading, #main > footer';
131 const key = el => el.dataset.game || el.tagName;
132 const animate = !matchMedia('(prefers-reduced-motion: reduce)').matches &&
133 (relocating || [...document.querySelectorAll(selector)].some(el => el.getAnimations().length));
134 const before = new Map(animate ? [...document.querySelectorAll(selector)].map(el => [key(el), el.getBoundingClientRect()]) : []);
135 const yours = state.games.filter(g => g.yourTurn || g.status === 'ended' || g.status === 'pending' && g.incoming || moveHolds.has(g.id));
136 const waiting = state.games.filter(g => !yours.includes(g));
137 $('#your-count').textContent = yours.length; $('#waiting-count').textContent = waiting.length;
138 // Continue from the visible fill even when polling/selection recreates the cards mid-animation.
139 const materialBefore = new Map([...document.querySelectorAll('.material-bar')].map(el =>
140 {
141 const fill = $('.material-white', el), animation = fill.getAnimations()[0];
142 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 }];
143 }));
144 $('#your-games').innerHTML = yours.map(card).join('') || empty(true);
145 $('#waiting-games').innerHTML = waiting.map(card).join('') || empty(false);
146 const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
147 for (const el of document.querySelectorAll('.material-bar'))
148 {
149 const fill = $('.material-white', el), share = Number(el.dataset.share), old = materialBefore.get(el.closest('[data-game]').dataset.game);
150 fill.style.transform = `scaleX(${share})`;
151 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' });
152 }
153 renderMoveFeedback(now, reduced);
154 if (animate)
155 {
156 for (const el of document.querySelectorAll(selector))
157 {
158 const old = before.get(key(el));
159 el.getAnimations().forEach(animation => animation.cancel());
160 if (!old) continue;
161 const rect = el.getBoundingClientRect(), dx = old.left - rect.left, dy = old.top - rect.top;
162 if (Math.abs(dx) < 1 && Math.abs(dy) < 1) continue;
163 el.animate([
164 { transform: `translate(${dx}px, ${dy}px)`, zIndex: 2 },
165 { transform: 'translate(0, 0)', zIndex: 2 }
166 ], { duration: 650, easing: 'cubic-bezier(.22, 1, .36, 1)' });
167 }
168 }
169}
170function card (g)
171{
172 let content = '';
173 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>`;
174 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>`;
175 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>`;
176 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>${esc(g.opponent)}</strong>${g.status !== 'pending' ? materialBar(g) : ''}</div>${g.status !== 'pending' ? `<span class="color-tag"><span class="color-disc ${g.color === 'b' ? 'black' : ''}"></span>${g.color === 'w' ? 'White' : 'Black'}</span>` : ''}${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>`;
177}
178function materialBar (g)
179{
180 const totals = { w: 0, b: 0 };
181 for (const p of g.state.board) if (p !== '.') totals[p === p.toUpperCase() ? 'w' : 'b'] += materialValues[p.toLowerCase()];
182 const total = totals.w + totals.b, share = total ? totals.w / total : .5;
183 const label = `White: ${totals.w} material points. Black: ${totals.b} material points. You play ${g.color === 'w' ? 'White' : 'Black'}.`;
184 return `<div class="material-bar" data-share="${share}" role="meter" aria-label="Material balance, White on the left and Black on the right" 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"></span></div>`;
185}
186function renderMoveFeedback (now, reduced)
187{
188 for (const [id, feedback] of moveFeedback)
189 {
190 const g = state.games.find(g => g.id === id);
191 if (feedback.user !== state.user.id || !g || g.state.ply > feedback.ply) { moveFeedback.delete(id); continue; }
192 if (g.state.ply !== feedback.ply) continue;
193 if (feedback.start === null)
194 {
195 feedback.start = now;
196 setTimeout(() =>
197 {
198 if (moveFeedback.get(id) !== feedback) return;
199 moveFeedback.delete(id);
200 document.querySelector(`[data-game="${id}"] .move-feedback`)?.remove();
201 }, 1800);
202 }
203 const elapsed = now - feedback.start;
204 if (elapsed >= 1800) { moveFeedback.delete(id); continue; }
205 const el = document.querySelector(`[data-game="${id}"]`); if (!el) continue;
206 const overlay = document.createElement('div');
207 overlay.className = `move-feedback ${feedback.quality}`;
208 const label = { good: 'Looks good', poor: 'Watch out' }[feedback.quality];
209 el.append(overlay);
210 if (reduced) { overlay.style.opacity = '1'; continue; }
211 const frames = [{ opacity: 0, offset: 0 }, { opacity: 1, offset: .15 }, { opacity: .25, offset: .4 }, { opacity: 1, offset: .65 }, { opacity: 0, offset: 1 }];
212 const animation = overlay.animate(frames, { duration: 1800, easing: 'ease-in-out' });
213 animation.currentTime = elapsed;
214 }
215}
216function board (g)
217{
218 const indices = Array.from({ length: 20 }, (_, i) => g.color === 'w' ? i : 19 - i);
219 const active = selected?.game === g.id ? selected.from : null;
220 const legal = g.legal.filter(m => m.from === active).map(m => m.to);
221 let html = '<div class="board-wrap"><div class="board" role="group" aria-label="Microchess board">';
222 indices.forEach((i, view) =>
223 {
224 const p = g.state.board[i], square = String.fromCharCode(97 + i % 4) + (5 - Math.floor(i / 4));
225 const last = g.state.last && (i === g.state.last.from || i === g.state.last.to);
226 const checked = g.check && p.toLowerCase() === 'k' && (p === p.toUpperCase() ? 'w' : 'b') === g.state.turn;
227 const label = `${square}${p !== '.' ? ' ' + (p === p.toUpperCase() ? 'white ' : 'black ') + names[p.toLowerCase()] : ''}${legal.includes(i) ? ', legal destination' : ''}`;
228 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)}" 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>`;
229 });
230 html += '</div>';
231 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)}" alt="">${names[p]}</button>`).join('')}</div><button class="text-button" data-cancel-promotion>Cancel</button></div>`;
232 return html + '</div>';
233}
234function renderFriends ()
235{
236 $('#friend-count').textContent = state.friends.length; $('#sidebar-count').textContent = state.friends.length;
237 $('#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.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>';
238 $('#account-summary').innerHTML = `${avatarMarkup(state.user.name, state.user.avatar, true)}<span>${esc(state.user.name)}<small>${state.local ? 'Local test account' : 'Ready for your next move'}</small></span>`;
239}
240function 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; }
241function chooseSquare (g, i)
242{
243 if (!g.yourTurn || busy || promotion) return;
244 if (selected?.game === g.id && g.legal.some(m => m.from === selected.from && m.to === i)) { attemptMove(g, selected.from, i); return; }
245 const p = g.state.board[i];
246 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 }; }
247 else selected = null;
248 renderGames();
249}
250let claimIntended = null;
251function attemptMove (g, from, to, promote)
252{
253 const moves = g.legal.filter(m => m.from === from && m.to === to); if (!moves.length) return;
254 if (moves[0].promotion && !promote) { promotion = { game: g.id, from, to }; renderGames(); return; }
255 const kind = claimIntended === g.id ? 'claim_draw' : 'move'; claimIntended = null;
256 action({ action: kind, game: g.id, version: g.version, from, to, promotion: promote ?? null });
257}
258async 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>`); }); }
259if ($('#match-link')) $('#match-link').onclick = () => createLink('match');
260if ($('#friend-link')) $('#friend-link').onclick = () => createLink('friend');
261$('#settings-button').onclick = () => { if (!state) return; showModal(`<h2>Your account</h2><p>Signed in as ${esc(state.user.name)}.</p><div class="settings-actions">${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>`); };
262if ($('#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>`);
263document.addEventListener('click', e =>
264{
265 const el = e.target.closest('button'); if (!el) return;
266 const gameEl = el.closest('[data-game]'); const g = gameEl && state?.games.find(g => g.id === Number(gameEl.dataset.game));
267 if (el.id === 'avatar-button') chooseAvatar();
268 if (el.dataset.createLink) createLink(el.dataset.createLink);
269 if (el.hasAttribute('data-square') && g) { if (suppressClick) { suppressClick = false; return; } chooseSquare(g, Number(el.dataset.square)); }
270 if (el.dataset.gameAction && g) { if (el.dataset.gameAction === 'stop-confirm') { showModal(`<h2 id="modal-title">Spel stoppen?</h2><p>De laatste zet was ${g.inactiveDays} dagen geleden. Wil je het spel stoppen?</p><div class="actions"><button class="danger" data-stop-game="${g.id}" data-version="${g.version}">Spel stoppen</button><button class="secondary" data-modal-action="close">Annuleren</button></div>`); } else if (el.dataset.gameAction === 'options') options(g); else action({ action: el.dataset.gameAction, game: g.id, version: g.version }); }
271 if (el.dataset.promotion && g && promotion) attemptMove(g, promotion.from, promotion.to, el.dataset.promotion);
272 if (el.hasAttribute('data-cancel-promotion')) { promotion = null; claimIntended = null; renderGames(); }
273 if (el.dataset.friend) { const f = state.friends.find(f => f.id === el.dataset.friend); 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"><button class="primary" data-friend-action="challenge">Challenge to a game ↗</button><button class="text-button" data-friend-action="remove">Remove friend…</button></div>`); $('#modal-content').dataset.friend = f.id; }
274});
275$('#modal-content').addEventListener('click', async e =>
276{
277 const b = e.target.closest('button'); if (!b) return;
278 if (b.dataset.stopGame) { await action({ action: 'stop_inactive', game: Number(b.dataset.stopGame), version: Number(b.dataset.version) }, () => closeModal()); return; }
279 if (b.dataset.avatarGroup) { avatarGroup = b.dataset.avatarGroup; renderAvatarChoices(); return; }
280 if (b.hasAttribute('data-avatar-choice')) { await action({ action: 'set_avatar', avatar: b.dataset.avatarChoice || null }, () => { closeModal(); toast('Avatar updated.'); }); return; }
281 if (b.dataset.modalAction === 'close') closeModal();
282 if (b.dataset.modalAction === 'accept-invite') await action({ action: 'accept_link', token: inviteToken }, () => { closeModal(); toast('Invitation accepted.'); });
283 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.'); } }
284 if (b.dataset.modalAction === 'switch') await action({ action: 'switch_user', user: state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1' }, () => { lastRender = ''; closeModal(); });
285 if (b.dataset.modalAction === 'logout') await action({ action: 'logout' }, () => location.reload());
286 if (b.dataset.friendAction)
287 {
288 const id = $('#modal-content').dataset.friend;
289 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>'); }
290 else await action({ action: b.dataset.friendAction === 'challenge' ? 'challenge' : 'remove_friend', friend: id }, () => { closeModal(); toast(b.dataset.friendAction === 'challenge' ? 'Challenge sent.' : 'Friend removed.'); });
291 }
292 if (b.dataset.option)
293 {
294 const g = state.games.find(g => g.id === Number($('#modal-content').dataset.game)); if (!g) return;
295 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; }
296 if (b.dataset.option === 'claim-intended') { claimIntended = g.id; closeModal(); toast('Select your intended move to claim a draw.'); return; }
297 await action({ action: b.dataset.option, game: g.id, version: g.version }, () => closeModal());
298 }
299});
300$('#modal-content').addEventListener('change', e => { if (e.target.id === 'avatar-color') { avatarColor = e.target.value; renderAvatarChoices(); } });
301let suppressClick = false;
302document.addEventListener('pointerdown', e =>
303{
304 const sq = e.target.closest('[data-square]'); if (!sq || e.button !== 0 || busy || promotion) return;
305 const g = state?.games.find(g => g.id === Number(sq.closest('[data-game]').dataset.game)); if (!g?.yourTurn) return;
306 const from = Number(sq.dataset.square), p = g.state.board[from]; if (p === '.' || (p === p.toUpperCase() ? 'w' : 'b') !== g.color) return;
307 drag = { game: g.id, from, p, x: e.clientX, y: e.clientY, id: e.pointerId, moving: false };
308});
309document.addEventListener('pointermove', e =>
310{
311 if (!drag || e.pointerId !== drag.id) return;
312 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); }
313 if (drag.moving) { e.preventDefault(); const img = $('.drag-ghost'); img.style.left = e.clientX + 'px'; img.style.top = e.clientY + 'px'; }
314}, { passive: false });
315document.addEventListener('pointerup', e =>
316{
317 if (!drag || e.pointerId !== drag.id) return; const d = drag; drag = null; $('.drag-ghost')?.remove();
318 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)); }
319});
320document.addEventListener('pointercancel', () => { drag = null; $('.drag-ghost')?.remove(); });
321refresh(); setInterval(() => { if (!document.hidden) refresh(); }, 2500); document.addEventListener('visibilitychange', () => { if (!document.hidden) refresh(); });