BlueGit

projects-timfalken-com microchess

Keep final boards visible and allow stopping inactive games

timfa Tim Falken · pushed by timfa

Authored 2026-09-08 · 2 months ago

Hash
503ead58a6c2f9731dcd1b87381d5fffb672f980
Parent
cc5af529
7 files changed +90 −9
web/README.md +5 −1
@@ -70,7 +70,7 @@ Rematches need both players' agreement and swap colors, keeping the tile ID. Exi
70 70
71 71 ## Avatars
72 72
73 Click your avatar at the bottom of the friends sidebar to open the piece picker. The local collection contains 29 colored standard and fairy chess avatars, with color/family filters and an option to restore your initials. Selection is saved in SQLite and appears in friend lists, opponent tile headers and your data export. The `user_avatars` table is created automatically, preserving existing accounts and game data.
73 Click your avatar at the bottom of the friends sidebar to open the piece picker. The local collection contains 29 colored standard and fairy chess avatars, with color/family filters and an option to choose randomly. Accounts without an avatar receive a random piece automatically. Selection is saved in SQLite and appears in friend lists, opponent tile headers and your data export. The `user_avatars` table is created automatically, preserving existing accounts and game data.
74 74
75 75 Avatars use locally stored PNG previews from Wikimedia Commons; available original SVGs are included alongside them. Author, original file and license links are recorded in [avatar credits](assets/avatars/CREDITS.md) and `assets/avatars/catalog.json`. There are no runtime requests to Wikimedia.
76 76
@@ -100,3 +100,7 @@ These cover click, mouse drag, touch drag, promotion, rematch, friendships, desk
100 100 ## Piece credits
101 101
102 102 Unmodified `Chess_{piece}{l|d}t45.svg` images by **Cburnett**, downloaded from [Wikimedia Commons](https://commons.wikimedia.org/wiki/Category:SVG_chess_pieces), used under [Creative Commons Attribution-ShareAlike 3.0](https://creativecommons.org/licenses/by-sa/3.0/). See [asset credits](assets/pieces/CREDITS.md) for individual source links. The rules dialog includes visible attribution. The Microchess starting position follows [Green Chess](https://greenchess.net/rules.php?v=microchess).
103
104 ## Inactive games and final positions
105
106 Ended games retain the final board and move highlights, with a transparent result bar that becomes readable on hover or keyboard focus. Touch devices show readable controls immediately. After seven days without game activity, either player can confirm removal of both tiles. Existing result history is retained; stopping an unfinished game awards no result. Activity tracking begins at deployment for existing games because earlier move timestamps were not stored.
@@ -70,7 +70,7 @@ Rematches need both players' agreement and swap colors, keeping the tile ID. Exi
70
70
71## Avatars
71## Avatars
72
72
73Click your avatar at the bottom of the friends sidebar to open the piece picker. The local collection contains 29 colored standard and fairy chess avatars, with color/family filters and an option to restore your initials. Selection is saved in SQLite and appears in friend lists, opponent tile headers and your data export. The `user_avatars` table is created automatically, preserving existing accounts and game data.
73Click your avatar at the bottom of the friends sidebar to open the piece picker. The local collection contains 29 colored standard and fairy chess avatars, with color/family filters and an option to choose randomly. Accounts without an avatar receive a random piece automatically. Selection is saved in SQLite and appears in friend lists, opponent tile headers and your data export. The `user_avatars` table is created automatically, preserving existing accounts and game data.
74
74
75Avatars use locally stored PNG previews from Wikimedia Commons; available original SVGs are included alongside them. Author, original file and license links are recorded in [avatar credits](assets/avatars/CREDITS.md) and `assets/avatars/catalog.json`. There are no runtime requests to Wikimedia.
75Avatars use locally stored PNG previews from Wikimedia Commons; available original SVGs are included alongside them. Author, original file and license links are recorded in [avatar credits](assets/avatars/CREDITS.md) and `assets/avatars/catalog.json`. There are no runtime requests to Wikimedia.
76
76
@@ -100,3 +100,7 @@ These cover click, mouse drag, touch drag, promotion, rematch, friendships, desk
100## Piece credits
100## Piece credits
101
101
102Unmodified `Chess_{piece}{l|d}t45.svg` images by **Cburnett**, downloaded from [Wikimedia Commons](https://commons.wikimedia.org/wiki/Category:SVG_chess_pieces), used under [Creative Commons Attribution-ShareAlike 3.0](https://creativecommons.org/licenses/by-sa/3.0/). See [asset credits](assets/pieces/CREDITS.md) for individual source links. The rules dialog includes visible attribution. The Microchess starting position follows [Green Chess](https://greenchess.net/rules.php?v=microchess).
102Unmodified `Chess_{piece}{l|d}t45.svg` images by **Cburnett**, downloaded from [Wikimedia Commons](https://commons.wikimedia.org/wiki/Category:SVG_chess_pieces), used under [Creative Commons Attribution-ShareAlike 3.0](https://creativecommons.org/licenses/by-sa/3.0/). See [asset credits](assets/pieces/CREDITS.md) for individual source links. The rules dialog includes visible attribution. The Microchess starting position follows [Green Chess](https://greenchess.net/rules.php?v=microchess).
103
104## Inactive games and final positions
105
106Ended games retain the final board and move highlights, with a transparent result bar that becomes readable on hover or keyboard focus. Touch devices show readable controls immediately. After seven days without game activity, either player can confirm removal of both tiles. Existing result history is retained; stopping an unfinished game awards no result. Activity tracking begins at deployment for existing games because earlier move timestamps were not stored.
web/api.php +8 −2
@@ -54,7 +54,10 @@ try {
54 54 $out=['ok'=>true];
55 55 if ($action==='set_avatar') {
56 56 $avatar=$in['avatar']??null;
57 if ($avatar===null) query('DELETE FROM user_avatars WHERE user_id=?',[$u]);
57 if ($avatar===null) {
58 $avatars=avatarCatalog();
59 query('INSERT INTO user_avatars(user_id,avatar) VALUES(?,?) ON CONFLICT(user_id) DO UPDATE SET avatar=excluded.avatar',[$u,$avatars[random_int(0,count($avatars)-1)]['id']]);
60 }
58 61 else {
59 62 if (!is_string($avatar)||!in_array($avatar,array_column(avatarCatalog(),'id'),true)) throw new DomainException('Choose an avatar from the available pieces.');
60 63 query('INSERT INTO user_avatars(user_id,avatar) VALUES(?,?) ON CONFLICT(user_id) DO UPDATE SET avatar=excluded.avatar',[$u,$avatar]);
@@ -85,7 +88,10 @@ try {
85 88 $side=$g['a']===$u?'a':'b';$opSide=$side==='a'?'b':'a';$other=$g[$opSide];
86 89 if ($g['exit_'.$side]) throw new DomainException('You have left this game.');
87 90 if (!isset($in['version']) || $in['version']!==(int)$g['version']) throw new DomainException('The game has changed. Please try again.');
88 if (in_array($action,['accept','reject'],true)) {
91 if ($action==='stop_inactive') {
92 if (($g['activity_at']??time())>time()-7*86400) throw new DomainException('This game has been active within the last week.');
93 query("UPDATE games SET exit_a=1,exit_b=1,rematch_a=0,rematch_b=0,status=CASE WHEN status='ended' THEN status ELSE 'stopped' END,version=version+1 WHERE id=?",[$g['id']]);
94 } elseif (in_array($action,['accept','reject'],true)) {
89 95 if ($g['status']!=='pending' || $g['b']!==$u) throw new DomainException('This invitation is no longer available.');
90 96 if ($action==='reject') query('DELETE FROM games WHERE id=?',[$g['id']]);
91 97 else query("UPDATE games SET status='active',white=?,state=?,version=version+1 WHERE id=?",[random_int(0,1)?$g['a']:$g['b'],json_encode(Chess::initial()),$g['id']]);
@@ -54,7 +54,10 @@ try {
54 $out=['ok'=>true];
54 $out=['ok'=>true];
55 if ($action==='set_avatar') {
55 if ($action==='set_avatar') {
56 $avatar=$in['avatar']??null;
56 $avatar=$in['avatar']??null;
57 if ($avatar===null) query('DELETE FROM user_avatars WHERE user_id=?',[$u]);
57 if ($avatar===null) {
58 $avatars=avatarCatalog();
59 query('INSERT INTO user_avatars(user_id,avatar) VALUES(?,?) ON CONFLICT(user_id) DO UPDATE SET avatar=excluded.avatar',[$u,$avatars[random_int(0,count($avatars)-1)]['id']]);
60 }
58 else {
61 else {
59 if (!is_string($avatar)||!in_array($avatar,array_column(avatarCatalog(),'id'),true)) throw new DomainException('Choose an avatar from the available pieces.');
62 if (!is_string($avatar)||!in_array($avatar,array_column(avatarCatalog(),'id'),true)) throw new DomainException('Choose an avatar from the available pieces.');
60 query('INSERT INTO user_avatars(user_id,avatar) VALUES(?,?) ON CONFLICT(user_id) DO UPDATE SET avatar=excluded.avatar',[$u,$avatar]);
63 query('INSERT INTO user_avatars(user_id,avatar) VALUES(?,?) ON CONFLICT(user_id) DO UPDATE SET avatar=excluded.avatar',[$u,$avatar]);
@@ -85,7 +88,10 @@ try {
85 $side=$g['a']===$u?'a':'b';$opSide=$side==='a'?'b':'a';$other=$g[$opSide];
88 $side=$g['a']===$u?'a':'b';$opSide=$side==='a'?'b':'a';$other=$g[$opSide];
86 if ($g['exit_'.$side]) throw new DomainException('You have left this game.');
89 if ($g['exit_'.$side]) throw new DomainException('You have left this game.');
87 if (!isset($in['version']) || $in['version']!==(int)$g['version']) throw new DomainException('The game has changed. Please try again.');
90 if (!isset($in['version']) || $in['version']!==(int)$g['version']) throw new DomainException('The game has changed. Please try again.');
88 if (in_array($action,['accept','reject'],true)) {
91 if ($action==='stop_inactive') {
92 if (($g['activity_at']??time())>time()-7*86400) throw new DomainException('This game has been active within the last week.');
93 query("UPDATE games SET exit_a=1,exit_b=1,rematch_a=0,rematch_b=0,status=CASE WHEN status='ended' THEN status ELSE 'stopped' END,version=version+1 WHERE id=?",[$g['id']]);
94 } elseif (in_array($action,['accept','reject'],true)) {
89 if ($g['status']!=='pending' || $g['b']!==$u) throw new DomainException('This invitation is no longer available.');
95 if ($g['status']!=='pending' || $g['b']!==$u) throw new DomainException('This invitation is no longer available.');
90 if ($action==='reject') query('DELETE FROM games WHERE id=?',[$g['id']]);
96 if ($action==='reject') query('DELETE FROM games WHERE id=?',[$g['id']]);
91 else query("UPDATE games SET status='active',white=?,state=?,version=version+1 WHERE id=?",[random_int(0,1)?$g['a']:$g['b'],json_encode(Chess::initial()),$g['id']]);
97 else query("UPDATE games SET status='active',white=?,state=?,version=version+1 WHERE id=?",[random_int(0,1)?$g['a']:$g['b'],json_encode(Chess::initial()),$g['id']]);
web/assets/app.css +4 −0
@@ -7,3 +7,7 @@
7 7 @media(max-width:760px){body.sidebar-open{overflow:hidden}}
8 8
9 9 .avatar img{width:90%;height:90%;object-fit:contain}#avatar-button{padding:0;color:inherit;outline-offset:4px;flex-shrink:0}#avatar-button:hover{background:#dce6cb;box-shadow:0 0 0 3px #dce6cb}dialog.avatar-picker{width:min(700px,calc(100% - 28px));max-height:calc(100dvh - 32px);overflow-y:auto}.avatar-filters{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin:20px 0}.avatar-tabs{display:flex;gap:5px}.avatar-tabs button{font-size:12px;padding:8px 12px}.avatar-tabs button[aria-pressed=true]{background:var(--green);color:white}#avatar-color{font:inherit;font-size:12px;color:var(--ink);background:var(--paper);border:1px solid var(--line);border-radius:7px;padding:8px;max-width:100%}.avatar-choices{display:grid;grid-template-columns:repeat(auto-fill,minmax(88px,1fr));gap:10px;max-height:390px;overflow-y:auto;padding:4px}.avatar-choice{display:flex;align-items:center;flex-direction:column;justify-content:center;gap:7px;min-height:108px;padding:9px 5px;background:#eff1e7;border:2px solid transparent;font-size:10px;line-height:1.3;font-weight:500}.avatar-choice img{width:54px;height:54px;object-fit:contain}.avatar-choice[aria-pressed=true]{border-color:var(--green);background:#dde8cc}.avatar-picker-footer{display:flex;justify-content:space-between;align-items:center;gap:15px;margin-top:18px}dialog .avatar-credits{font-size:10px;margin:16px 0 0;line-height:1.6}.avatar-no-results{grid-column:1/-1;padding:25px 10px;text-align:center}#avatar-color:focus-visible{outline:3px solid #c19042;outline-offset:3px}@media(max-width:760px){dialog.avatar-picker{padding:30px 20px 22px}.avatar-choices{grid-template-columns:repeat(3,minmax(0,1fr));max-height:42dvh}.avatar-tabs button{padding:8px 10px;font-size:11px}}
10
11 .ended-board{position:relative}.ended-board .end-content{position:absolute;left:15px;right:15px;top:50%;transform:translateY(-50%);min-height:0;aspect-ratio:auto;padding:12px 8px;display:flex;flex-direction:row;justify-content:space-between;gap:8px;text-align:left;background:rgb(255 254 251 / 12%);opacity:.22;transition:opacity .18s,background .18s}.end-content:hover,.end-content:focus-within{background:rgb(255 254 251 / 94%);opacity:1}.end-status{min-width:0}.end-status h3{font-size:13px;line-height:1.3}.end-status small{display:block;font-size:10px}.end-content .actions{flex-wrap:nowrap;gap:4px}.end-content button{font-size:10px;padding:8px 6px}.stop-inactive{margin-left:auto;background:#b73535;color:white;font-size:22px;line-height:1;padding:3px 7px;flex-shrink:0}.card-header:has(.stop-inactive) .color-tag{margin-left:auto}.card-header:has(.stop-inactive){gap:6px}
12 @media(hover:none){.ended-board .end-content{opacity:1;background:rgb(255 254 251 / 82%)}}
13 @media(min-width:761px){#sidebar{position:sticky;top:0;align-self:start;height:calc(100dvh - 88px);overflow-y:auto;padding-top:24px;padding-bottom:20px}#sidebar>*{flex-shrink:0}#friend-list{flex:1 1 auto;min-height:60px;overflow-y:auto}.sidebar-note{padding:18px 0}.sidebar-note>span{font-size:30px}}
@@ -7,3 +7,7 @@
7@media(max-width:760px){body.sidebar-open{overflow:hidden}}
7@media(max-width:760px){body.sidebar-open{overflow:hidden}}
8
8
9.avatar img{width:90%;height:90%;object-fit:contain}#avatar-button{padding:0;color:inherit;outline-offset:4px;flex-shrink:0}#avatar-button:hover{background:#dce6cb;box-shadow:0 0 0 3px #dce6cb}dialog.avatar-picker{width:min(700px,calc(100% - 28px));max-height:calc(100dvh - 32px);overflow-y:auto}.avatar-filters{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin:20px 0}.avatar-tabs{display:flex;gap:5px}.avatar-tabs button{font-size:12px;padding:8px 12px}.avatar-tabs button[aria-pressed=true]{background:var(--green);color:white}#avatar-color{font:inherit;font-size:12px;color:var(--ink);background:var(--paper);border:1px solid var(--line);border-radius:7px;padding:8px;max-width:100%}.avatar-choices{display:grid;grid-template-columns:repeat(auto-fill,minmax(88px,1fr));gap:10px;max-height:390px;overflow-y:auto;padding:4px}.avatar-choice{display:flex;align-items:center;flex-direction:column;justify-content:center;gap:7px;min-height:108px;padding:9px 5px;background:#eff1e7;border:2px solid transparent;font-size:10px;line-height:1.3;font-weight:500}.avatar-choice img{width:54px;height:54px;object-fit:contain}.avatar-choice[aria-pressed=true]{border-color:var(--green);background:#dde8cc}.avatar-picker-footer{display:flex;justify-content:space-between;align-items:center;gap:15px;margin-top:18px}dialog .avatar-credits{font-size:10px;margin:16px 0 0;line-height:1.6}.avatar-no-results{grid-column:1/-1;padding:25px 10px;text-align:center}#avatar-color:focus-visible{outline:3px solid #c19042;outline-offset:3px}@media(max-width:760px){dialog.avatar-picker{padding:30px 20px 22px}.avatar-choices{grid-template-columns:repeat(3,minmax(0,1fr));max-height:42dvh}.avatar-tabs button{padding:8px 10px;font-size:11px}}
9.avatar img{width:90%;height:90%;object-fit:contain}#avatar-button{padding:0;color:inherit;outline-offset:4px;flex-shrink:0}#avatar-button:hover{background:#dce6cb;box-shadow:0 0 0 3px #dce6cb}dialog.avatar-picker{width:min(700px,calc(100% - 28px));max-height:calc(100dvh - 32px);overflow-y:auto}.avatar-filters{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin:20px 0}.avatar-tabs{display:flex;gap:5px}.avatar-tabs button{font-size:12px;padding:8px 12px}.avatar-tabs button[aria-pressed=true]{background:var(--green);color:white}#avatar-color{font:inherit;font-size:12px;color:var(--ink);background:var(--paper);border:1px solid var(--line);border-radius:7px;padding:8px;max-width:100%}.avatar-choices{display:grid;grid-template-columns:repeat(auto-fill,minmax(88px,1fr));gap:10px;max-height:390px;overflow-y:auto;padding:4px}.avatar-choice{display:flex;align-items:center;flex-direction:column;justify-content:center;gap:7px;min-height:108px;padding:9px 5px;background:#eff1e7;border:2px solid transparent;font-size:10px;line-height:1.3;font-weight:500}.avatar-choice img{width:54px;height:54px;object-fit:contain}.avatar-choice[aria-pressed=true]{border-color:var(--green);background:#dde8cc}.avatar-picker-footer{display:flex;justify-content:space-between;align-items:center;gap:15px;margin-top:18px}dialog .avatar-credits{font-size:10px;margin:16px 0 0;line-height:1.6}.avatar-no-results{grid-column:1/-1;padding:25px 10px;text-align:center}#avatar-color:focus-visible{outline:3px solid #c19042;outline-offset:3px}@media(max-width:760px){dialog.avatar-picker{padding:30px 20px 22px}.avatar-choices{grid-template-columns:repeat(3,minmax(0,1fr));max-height:42dvh}.avatar-tabs button{padding:8px 10px;font-size:11px}}
10
11.ended-board{position:relative}.ended-board .end-content{position:absolute;left:15px;right:15px;top:50%;transform:translateY(-50%);min-height:0;aspect-ratio:auto;padding:12px 8px;display:flex;flex-direction:row;justify-content:space-between;gap:8px;text-align:left;background:rgb(255 254 251 / 12%);opacity:.22;transition:opacity .18s,background .18s}.end-content:hover,.end-content:focus-within{background:rgb(255 254 251 / 94%);opacity:1}.end-status{min-width:0}.end-status h3{font-size:13px;line-height:1.3}.end-status small{display:block;font-size:10px}.end-content .actions{flex-wrap:nowrap;gap:4px}.end-content button{font-size:10px;padding:8px 6px}.stop-inactive{margin-left:auto;background:#b73535;color:white;font-size:22px;line-height:1;padding:3px 7px;flex-shrink:0}.card-header:has(.stop-inactive) .color-tag{margin-left:auto}.card-header:has(.stop-inactive){gap:6px}
12@media(hover:none){.ended-board .end-content{opacity:1;background:rgb(255 254 251 / 82%)}}
13@media(min-width:761px){#sidebar{position:sticky;top:0;align-self:start;height:calc(100dvh - 88px);overflow-y:auto;padding-top:24px;padding-bottom:20px}#sidebar>*{flex-shrink:0}#friend-list{flex:1 1 auto;min-height:60px;overflow-y:auto}.sidebar-note{padding:18px 0}.sidebar-note>span{font-size:30px}}
web/assets/app.js +5 −4
@@ -18,7 +18,7 @@ async function chooseAvatar(){
18 18 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();}
19 19 if(!modal.open||!modal.classList.contains('avatar-picker'))return;
20 20 avatarGroup='all';avatarColor='all';
21 $('#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="">Use my initials</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>`;
21 $('#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>`;
22 22 renderAvatarChoices();
23 23 }catch(e){toast(e.message);if(modal.classList.contains('avatar-picker'))closeModal();}
24 24 }
@@ -133,9 +133,9 @@ function renderGames() {
133 133 function card(g){
134 134 let content='';
135 135 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">The next move is theirs.</span>'}</div>`;
136 else if(g.status==='ended')content=`<div class="end-content"><span class="big-icon">${g.winner?'♔':'½'}</span><div><span class="eyebrow">${esc(g.reason)}</span><h3>${g.winner?esc(g.winner)+' wins!':'A game well matched.'}</h3></div><p>${g.winner?'Every ending is another opening.':'This one ends in a draw.'}</p>${g.opponentRematch&&g.canRematch?`<p class="rematch-note">${esc(g.opponent)} wants a rematch.</p>`:''}<div class="actions">${g.canRematch?`<button class="primary" data-game-action="rematch" ${g.rematch?'disabled':''}>${g.rematch?'Rematch requested':'Rematch'}</button>`:''}<button class="secondary" data-game-action="exit">Exit</button></div>${g.rematch&&g.canRematch?'<small class="inline-note">Waiting for your opponent.</small>':''}</div>`;
136 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>`;
137 137 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>`;
138 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)}<strong>${esc(g.opponent)}</strong>${g.status!=='pending'?`<span class="color-tag"><span class="color-disc ${g.color==='b'?'black':''}"></span>${g.color==='w'?'White':'Black'}</span>`:''}</div>${content}</article>`;
138 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)}<strong>${esc(g.opponent)}</strong>${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>`;
139 139 }
140 140 function board(g){
141 141 const indices=Array.from({length:20},(_,i)=>g.color==='w'?i:19-i);
@@ -185,13 +185,14 @@ document.addEventListener('click',e=>{
185 185 if(el.id==='avatar-button')chooseAvatar();
186 186 if(el.dataset.createLink)createLink(el.dataset.createLink);
187 187 if(el.hasAttribute('data-square')&&g){if(suppressClick){suppressClick=false;return;}chooseSquare(g,Number(el.dataset.square));}
188 if(el.dataset.gameAction&&g){if(el.dataset.gameAction==='options')options(g);else action({action:el.dataset.gameAction,game:g.id,version:g.version});}
188 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});}
189 189 if(el.dataset.promotion&&g&&promotion)attemptMove(g,promotion.from,promotion.to,el.dataset.promotion);
190 190 if(el.hasAttribute('data-cancel-promotion')){promotion=null;claimIntended=null;renderGames();}
191 191 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;}
192 192 });
193 193 $('#modal-content').addEventListener('click',async e=>{
194 194 const b=e.target.closest('button');if(!b)return;
195 if(b.dataset.stopGame){await action({action:'stop_inactive',game:Number(b.dataset.stopGame),version:Number(b.dataset.version)},()=>closeModal());return;}
195 196 if(b.dataset.avatarGroup){avatarGroup=b.dataset.avatarGroup;renderAvatarChoices();return;}
196 197 if(b.hasAttribute('data-avatar-choice')){await action({action:'set_avatar',avatar:b.dataset.avatarChoice||null},()=>{closeModal();toast('Avatar updated.');});return;}
197 198 if(b.dataset.modalAction==='close')closeModal();
@@ -18,7 +18,7 @@ async function chooseAvatar(){
18 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();}
18 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();}
19 if(!modal.open||!modal.classList.contains('avatar-picker'))return;
19 if(!modal.open||!modal.classList.contains('avatar-picker'))return;
20 avatarGroup='all';avatarColor='all';
20 avatarGroup='all';avatarColor='all';
21 $('#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="">Use my initials</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>`;
21 $('#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>`;
22 renderAvatarChoices();
22 renderAvatarChoices();
23 }catch(e){toast(e.message);if(modal.classList.contains('avatar-picker'))closeModal();}
23 }catch(e){toast(e.message);if(modal.classList.contains('avatar-picker'))closeModal();}
24}
24}
@@ -133,9 +133,9 @@ function renderGames() {
133function card(g){
133function card(g){
134 let content='';
134 let content='';
135 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">The next move is theirs.</span>'}</div>`;
135 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">The next move is theirs.</span>'}</div>`;
136 else if(g.status==='ended')content=`<div class="end-content"><span class="big-icon">${g.winner?'♔':'½'}</span><div><span class="eyebrow">${esc(g.reason)}</span><h3>${g.winner?esc(g.winner)+' wins!':'A game well matched.'}</h3></div><p>${g.winner?'Every ending is another opening.':'This one ends in a draw.'}</p>${g.opponentRematch&&g.canRematch?`<p class="rematch-note">${esc(g.opponent)} wants a rematch.</p>`:''}<div class="actions">${g.canRematch?`<button class="primary" data-game-action="rematch" ${g.rematch?'disabled':''}>${g.rematch?'Rematch requested':'Rematch'}</button>`:''}<button class="secondary" data-game-action="exit">Exit</button></div>${g.rematch&&g.canRematch?'<small class="inline-note">Waiting for your opponent.</small>':''}</div>`;
136 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>`;
137 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>`;
137 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>`;
138 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)}<strong>${esc(g.opponent)}</strong>${g.status!=='pending'?`<span class="color-tag"><span class="color-disc ${g.color==='b'?'black':''}"></span>${g.color==='w'?'White':'Black'}</span>`:''}</div>${content}</article>`;
138 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)}<strong>${esc(g.opponent)}</strong>${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>`;
139}
139}
140function board(g){
140function board(g){
141 const indices=Array.from({length:20},(_,i)=>g.color==='w'?i:19-i);
141 const indices=Array.from({length:20},(_,i)=>g.color==='w'?i:19-i);
@@ -185,13 +185,14 @@ document.addEventListener('click',e=>{
185 if(el.id==='avatar-button')chooseAvatar();
185 if(el.id==='avatar-button')chooseAvatar();
186 if(el.dataset.createLink)createLink(el.dataset.createLink);
186 if(el.dataset.createLink)createLink(el.dataset.createLink);
187 if(el.hasAttribute('data-square')&&g){if(suppressClick){suppressClick=false;return;}chooseSquare(g,Number(el.dataset.square));}
187 if(el.hasAttribute('data-square')&&g){if(suppressClick){suppressClick=false;return;}chooseSquare(g,Number(el.dataset.square));}
188 if(el.dataset.gameAction&&g){if(el.dataset.gameAction==='options')options(g);else action({action:el.dataset.gameAction,game:g.id,version:g.version});}
188 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});}
189 if(el.dataset.promotion&&g&&promotion)attemptMove(g,promotion.from,promotion.to,el.dataset.promotion);
189 if(el.dataset.promotion&&g&&promotion)attemptMove(g,promotion.from,promotion.to,el.dataset.promotion);
190 if(el.hasAttribute('data-cancel-promotion')){promotion=null;claimIntended=null;renderGames();}
190 if(el.hasAttribute('data-cancel-promotion')){promotion=null;claimIntended=null;renderGames();}
191 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;}
191 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;}
192});
192});
193$('#modal-content').addEventListener('click',async e=>{
193$('#modal-content').addEventListener('click',async e=>{
194 const b=e.target.closest('button');if(!b)return;
194 const b=e.target.closest('button');if(!b)return;
195 if(b.dataset.stopGame){await action({action:'stop_inactive',game:Number(b.dataset.stopGame),version:Number(b.dataset.version)},()=>closeModal());return;}
195 if(b.dataset.avatarGroup){avatarGroup=b.dataset.avatarGroup;renderAvatarChoices();return;}
196 if(b.dataset.avatarGroup){avatarGroup=b.dataset.avatarGroup;renderAvatarChoices();return;}
196 if(b.hasAttribute('data-avatar-choice')){await action({action:'set_avatar',avatar:b.dataset.avatarChoice||null},()=>{closeModal();toast('Avatar updated.');});return;}
197 if(b.hasAttribute('data-avatar-choice')){await action({action:'set_avatar',avatar:b.dataset.avatarChoice||null},()=>{closeModal();toast('Avatar updated.');});return;}
197 if(b.dataset.modalAction==='close')closeModal();
198 if(b.dataset.modalAction==='close')closeModal();
web/lib/bootstrap.php +23 −0
@@ -22,6 +22,25 @@ function db(): PDO {
22 22 CREATE TABLE IF NOT EXISTS games (id INTEGER PRIMARY KEY AUTOINCREMENT, a TEXT NOT NULL REFERENCES users(id), b TEXT NOT NULL REFERENCES users(id), status TEXT NOT NULL, white TEXT, state TEXT, winner TEXT, reason TEXT, exit_a INTEGER DEFAULT 0, exit_b INTEGER DEFAULT 0, rematch_a INTEGER DEFAULT 0, rematch_b INTEGER DEFAULT 0, draw_offer TEXT, version INTEGER DEFAULT 0, created INTEGER NOT NULL);
23 23 CREATE TABLE IF NOT EXISTS results (id INTEGER PRIMARY KEY AUTOINCREMENT, game_id INTEGER NOT NULL REFERENCES games(id), a TEXT NOT NULL, b TEXT NOT NULL, winner TEXT, reason TEXT NOT NULL, state TEXT NOT NULL, ended INTEGER NOT NULL);
24 24 CREATE INDEX IF NOT EXISTS games_a ON games(a); CREATE INDEX IF NOT EXISTS games_b ON games(b);');
25 $columns=$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1);
26 if (!in_array('activity_at',$columns,true)) {
27 $db->exec('BEGIN IMMEDIATE');
28 try {
29 if (!in_array('activity_at',$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1),true)) {
30 $db->exec('ALTER TABLE games ADD COLUMN activity_at INTEGER');
31 $db->exec('UPDATE games SET activity_at=unixepoch() WHERE activity_at IS NULL');
32 }
33 $db->exec('COMMIT');
34 } catch (Throwable $e) { $db->exec('ROLLBACK');throw $e; }
35 }
36 $db->exec('CREATE TRIGGER IF NOT EXISTS games_activity_insert AFTER INSERT ON games BEGIN UPDATE games SET activity_at=unixepoch() WHERE id=NEW.id; END;
37 CREATE TRIGGER IF NOT EXISTS games_activity_update AFTER UPDATE OF version ON games BEGIN UPDATE games SET activity_at=unixepoch() WHERE id=NEW.id; END;');
38 // Assign existing accounts once as well as newly created accounts.
39 foreach ($db->query('SELECT id FROM users WHERE id NOT IN (SELECT user_id FROM user_avatars)')->fetchAll(PDO::FETCH_COLUMN) as $id) {
40 $avatars=avatarCatalog();
41 $q=$db->prepare('INSERT OR IGNORE INTO user_avatars(user_id,avatar) VALUES(?,?)');
42 $q->execute([$id,$avatars[random_int(0,count($avatars)-1)]['id']]);
43 }
25 44 return $db;
26 45 }
27 46 function query(string $sql,array $args=[]): PDOStatement { $s=db()->prepare($sql);$s->execute($args);return $s; }
@@ -86,6 +105,8 @@ function authRequest(string $path,?array $form=null,?string $token=null): array
86 105 }
87 106 function loginUser(string $id,string $name): void {
88 107 query('INSERT INTO users VALUES(?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name',[$id,$name]);
108 $avatars=avatarCatalog();
109 query('INSERT OR IGNORE INTO user_avatars(user_id,avatar) VALUES(?,?)',[$id,$avatars[random_int(0,count($avatars)-1)]['id']]);
89 110 session_regenerate_id(true); $_SESSION['user']=$id; $_SESSION['csrf']=bin2hex(random_bytes(24));
90 111 }
91 112 // Generate the editable configuration on the first page request, including localhost.
@@ -121,6 +142,8 @@ function gameView(array $g,string $u): array {
121 142 $s=$g['state']?json_decode($g['state'],true):null;
122 143 $color=$g['white']===$u?'w':'b';
123 144 return ['id'=>(int)$g['id'],'opponent'=>$opponent['name'],'opponentAvatar'=>$opponent['avatar'], 'status'=>$g['status'],'incoming'=>$g['b']===$u,'color'=>$color,
145 'inactiveDays'=>max(0,(int)floor((time()-($g['activity_at']??time()))/86400)),
146 'outcome'=>$g['winner']===null?'draw':($g['winner']===$u?'win':'loss'),
124 147 'state'=>$s,'yourTurn'=>$g['status']==='active' && $s['turn']===$color,'legal'=>$g['status']==='active' && $s['turn']===$color?Chess::legal($s):[],
125 148 'check'=>$s?Chess::check($s):false,'winner'=>$g['winner']?query('SELECT name FROM users WHERE id=?',[$g['winner']])->fetchColumn():null,'reason'=>$g['reason'],
126 149 'canRematch'=>!$g['exit_'.$opSide],'rematch'=>!!$g['rematch_'.$side],'opponentRematch'=>!!$g['rematch_'.$opSide], 'drawOffer'=>$g['draw_offer']?($g['draw_offer']===$u?'you':'opponent'):null,
@@ -22,6 +22,25 @@ function db(): PDO {
22 CREATE TABLE IF NOT EXISTS games (id INTEGER PRIMARY KEY AUTOINCREMENT, a TEXT NOT NULL REFERENCES users(id), b TEXT NOT NULL REFERENCES users(id), status TEXT NOT NULL, white TEXT, state TEXT, winner TEXT, reason TEXT, exit_a INTEGER DEFAULT 0, exit_b INTEGER DEFAULT 0, rematch_a INTEGER DEFAULT 0, rematch_b INTEGER DEFAULT 0, draw_offer TEXT, version INTEGER DEFAULT 0, created INTEGER NOT NULL);
22 CREATE TABLE IF NOT EXISTS games (id INTEGER PRIMARY KEY AUTOINCREMENT, a TEXT NOT NULL REFERENCES users(id), b TEXT NOT NULL REFERENCES users(id), status TEXT NOT NULL, white TEXT, state TEXT, winner TEXT, reason TEXT, exit_a INTEGER DEFAULT 0, exit_b INTEGER DEFAULT 0, rematch_a INTEGER DEFAULT 0, rematch_b INTEGER DEFAULT 0, draw_offer TEXT, version INTEGER DEFAULT 0, created INTEGER NOT NULL);
23 CREATE TABLE IF NOT EXISTS results (id INTEGER PRIMARY KEY AUTOINCREMENT, game_id INTEGER NOT NULL REFERENCES games(id), a TEXT NOT NULL, b TEXT NOT NULL, winner TEXT, reason TEXT NOT NULL, state TEXT NOT NULL, ended INTEGER NOT NULL);
23 CREATE TABLE IF NOT EXISTS results (id INTEGER PRIMARY KEY AUTOINCREMENT, game_id INTEGER NOT NULL REFERENCES games(id), a TEXT NOT NULL, b TEXT NOT NULL, winner TEXT, reason TEXT NOT NULL, state TEXT NOT NULL, ended INTEGER NOT NULL);
24 CREATE INDEX IF NOT EXISTS games_a ON games(a); CREATE INDEX IF NOT EXISTS games_b ON games(b);');
24 CREATE INDEX IF NOT EXISTS games_a ON games(a); CREATE INDEX IF NOT EXISTS games_b ON games(b);');
25 $columns=$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1);
26 if (!in_array('activity_at',$columns,true)) {
27 $db->exec('BEGIN IMMEDIATE');
28 try {
29 if (!in_array('activity_at',$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1),true)) {
30 $db->exec('ALTER TABLE games ADD COLUMN activity_at INTEGER');
31 $db->exec('UPDATE games SET activity_at=unixepoch() WHERE activity_at IS NULL');
32 }
33 $db->exec('COMMIT');
34 } catch (Throwable $e) { $db->exec('ROLLBACK');throw $e; }
35 }
36 $db->exec('CREATE TRIGGER IF NOT EXISTS games_activity_insert AFTER INSERT ON games BEGIN UPDATE games SET activity_at=unixepoch() WHERE id=NEW.id; END;
37 CREATE TRIGGER IF NOT EXISTS games_activity_update AFTER UPDATE OF version ON games BEGIN UPDATE games SET activity_at=unixepoch() WHERE id=NEW.id; END;');
38 // Assign existing accounts once as well as newly created accounts.
39 foreach ($db->query('SELECT id FROM users WHERE id NOT IN (SELECT user_id FROM user_avatars)')->fetchAll(PDO::FETCH_COLUMN) as $id) {
40 $avatars=avatarCatalog();
41 $q=$db->prepare('INSERT OR IGNORE INTO user_avatars(user_id,avatar) VALUES(?,?)');
42 $q->execute([$id,$avatars[random_int(0,count($avatars)-1)]['id']]);
43 }
25 return $db;
44 return $db;
26}
45}
27function query(string $sql,array $args=[]): PDOStatement { $s=db()->prepare($sql);$s->execute($args);return $s; }
46function query(string $sql,array $args=[]): PDOStatement { $s=db()->prepare($sql);$s->execute($args);return $s; }
@@ -86,6 +105,8 @@ function authRequest(string $path,?array $form=null,?string $token=null): array
86}
105}
87function loginUser(string $id,string $name): void {
106function loginUser(string $id,string $name): void {
88 query('INSERT INTO users VALUES(?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name',[$id,$name]);
107 query('INSERT INTO users VALUES(?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name',[$id,$name]);
108 $avatars=avatarCatalog();
109 query('INSERT OR IGNORE INTO user_avatars(user_id,avatar) VALUES(?,?)',[$id,$avatars[random_int(0,count($avatars)-1)]['id']]);
89 session_regenerate_id(true); $_SESSION['user']=$id; $_SESSION['csrf']=bin2hex(random_bytes(24));
110 session_regenerate_id(true); $_SESSION['user']=$id; $_SESSION['csrf']=bin2hex(random_bytes(24));
90}
111}
91// Generate the editable configuration on the first page request, including localhost.
112// Generate the editable configuration on the first page request, including localhost.
@@ -121,6 +142,8 @@ function gameView(array $g,string $u): array {
121 $s=$g['state']?json_decode($g['state'],true):null;
142 $s=$g['state']?json_decode($g['state'],true):null;
122 $color=$g['white']===$u?'w':'b';
143 $color=$g['white']===$u?'w':'b';
123 return ['id'=>(int)$g['id'],'opponent'=>$opponent['name'],'opponentAvatar'=>$opponent['avatar'], 'status'=>$g['status'],'incoming'=>$g['b']===$u,'color'=>$color,
144 return ['id'=>(int)$g['id'],'opponent'=>$opponent['name'],'opponentAvatar'=>$opponent['avatar'], 'status'=>$g['status'],'incoming'=>$g['b']===$u,'color'=>$color,
145 'inactiveDays'=>max(0,(int)floor((time()-($g['activity_at']??time()))/86400)),
146 'outcome'=>$g['winner']===null?'draw':($g['winner']===$u?'win':'loss'),
124 'state'=>$s,'yourTurn'=>$g['status']==='active' && $s['turn']===$color,'legal'=>$g['status']==='active' && $s['turn']===$color?Chess::legal($s):[],
147 'state'=>$s,'yourTurn'=>$g['status']==='active' && $s['turn']===$color,'legal'=>$g['status']==='active' && $s['turn']===$color?Chess::legal($s):[],
125 'check'=>$s?Chess::check($s):false,'winner'=>$g['winner']?query('SELECT name FROM users WHERE id=?',[$g['winner']])->fetchColumn():null,'reason'=>$g['reason'],
148 'check'=>$s?Chess::check($s):false,'winner'=>$g['winner']?query('SELECT name FROM users WHERE id=?',[$g['winner']])->fetchColumn():null,'reason'=>$g['reason'],
126 'canRematch'=>!$g['exit_'.$opSide],'rematch'=>!!$g['rematch_'.$side],'opponentRematch'=>!!$g['rematch_'.$opSide], 'drawOffer'=>$g['draw_offer']?($g['draw_offer']===$u?'you':'opponent'):null,
149 'canRematch'=>!$g['exit_'.$opSide],'rematch'=>!!$g['rematch_'.$side],'opponentRematch'=>!!$g['rematch_'.$opSide], 'drawOffer'=>$g['draw_offer']?($g['draw_offer']===$u?'you':'opponent'):null,
web/tests/browser.mjs +26 −0
@@ -78,6 +78,16 @@ try{
78 78 await white.locator('[data-promotion="n"]').click();
79 79 await white.getByRole('heading',{name:'A game well matched.'}).waitFor();
80 80 assert.equal((await state(white)).games[0].state.board[1],'N','Underpromotion saved');
81 for(const page of [white,black]){
82 await page.locator('.end-content').waitFor();
83 assert.equal(await page.locator('.ended-board .square').count(),20,'Final board remains visible for both players');
84 assert.equal(await page.locator('.ended-board .square.last').count(),2,'Final move stays highlighted');
85 await page.mouse.move(0,0);
86 await page.waitForTimeout(250);
87 assert(Number(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity))<.3,'Result starts transparent');
88 await page.locator('.end-content').hover();await page.waitForTimeout(250);
89 assert.equal(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity),'1','Hover reveals result controls');
90 }
81 91 await white.getByRole('button',{name:'Rematch',exact:true}).click();
82 92 await black.getByText(/wants a rematch/).waitFor();
83 93 await black.getByRole('button',{name:'Rematch',exact:true}).click();
@@ -88,6 +98,21 @@ try{
88 98 await a.reload();await a.locator('.game-card').nth(3).waitFor();
89 99 await a.screenshot({path:path.join(web,'tests/artifacts/desktop.png'),fullPage:true});
90 100 assert(await a.locator('.square img').evaluateAll(imgs=>imgs.every(i=>i.complete&&i.naturalWidth>0)),'All SVG pieces load');
101 await a.setViewportSize({width:1440,height:640});
102 await a.evaluate(()=>scrollTo(0,document.body.scrollHeight));
103 const sidebar=await a.locator('#sidebar').boundingBox();
104 assert(sidebar.y>=0&&sidebar.y+sidebar.height<=640,'Desktop sidebar fits viewport while scrolling');
105 assert.equal(await a.locator('#sidebar').evaluate(e=>getComputedStyle(e).position),'sticky');
106 const staleId=(await state(a)).games[0].id;
107 execFileSync('php',['-r',`$db=new PDO('sqlite:'.$argv[1]);$db->exec('UPDATE games SET activity_at=unixepoch()-8*86400 WHERE id='.(int)$argv[2]);`,path.join(root,'data/microchess.sqlite'),String(staleId)]);
108 await a.locator(`[data-game="${staleId}"] .stop-inactive`).click();
109 await a.getByText('De laatste zet was 8 dagen geleden. Wil je het spel stoppen?').waitFor();
110 await a.getByRole('button',{name:'Annuleren',exact:true}).click();
111 assert((await state(a)).games.some(g=>g.id===staleId),'Cancel retains game');
112 await a.locator(`[data-game="${staleId}"] .stop-inactive`).click();
113 await a.getByRole('button',{name:'Spel stoppen',exact:true}).click();
114 await a.locator(`[data-game="${staleId}"]`).waitFor({state:'detached'});
115 await b.locator(`[data-game="${staleId}"]`).waitFor({state:'detached'});
91 116 await a.setViewportSize({width:390,height:844});
92 117 assert(await a.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),'No mobile horizontal overflow');
93 118 assert.equal(await a.locator('#your-games').evaluate(e=>getComputedStyle(e).gridTemplateColumns.split(' ').length),1,'One tile column');
@@ -96,6 +121,7 @@ try{
96 121 await a.locator('[data-avatar-group="fairy"]').click();
97 122 await a.locator('#avatar-color').selectOption('Purple');
98 123 await a.locator('[data-avatar-choice="purple-elephant"]').waitFor();
124 await a.locator('.avatar-choice img').evaluateAll(imgs=>Promise.all(imgs.map(i=>i.decode())));
99 125 assert(await a.locator('.avatar-choice img').evaluateAll(imgs=>imgs.every(i=>i.complete&&i.naturalWidth>0)),'Fairy avatars load');
100 126 await a.screenshot({path:path.join(web,'tests/artifacts/avatar-picker-mobile.png')});
101 127 await a.locator('[data-avatar-choice="purple-elephant"]').click();
@@ -78,6 +78,16 @@ try{
78 await white.locator('[data-promotion="n"]').click();
78 await white.locator('[data-promotion="n"]').click();
79 await white.getByRole('heading',{name:'A game well matched.'}).waitFor();
79 await white.getByRole('heading',{name:'A game well matched.'}).waitFor();
80 assert.equal((await state(white)).games[0].state.board[1],'N','Underpromotion saved');
80 assert.equal((await state(white)).games[0].state.board[1],'N','Underpromotion saved');
81 for(const page of [white,black]){
82 await page.locator('.end-content').waitFor();
83 assert.equal(await page.locator('.ended-board .square').count(),20,'Final board remains visible for both players');
84 assert.equal(await page.locator('.ended-board .square.last').count(),2,'Final move stays highlighted');
85 await page.mouse.move(0,0);
86 await page.waitForTimeout(250);
87 assert(Number(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity))<.3,'Result starts transparent');
88 await page.locator('.end-content').hover();await page.waitForTimeout(250);
89 assert.equal(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity),'1','Hover reveals result controls');
90 }
81 await white.getByRole('button',{name:'Rematch',exact:true}).click();
91 await white.getByRole('button',{name:'Rematch',exact:true}).click();
82 await black.getByText(/wants a rematch/).waitFor();
92 await black.getByText(/wants a rematch/).waitFor();
83 await black.getByRole('button',{name:'Rematch',exact:true}).click();
93 await black.getByRole('button',{name:'Rematch',exact:true}).click();
@@ -88,6 +98,21 @@ try{
88 await a.reload();await a.locator('.game-card').nth(3).waitFor();
98 await a.reload();await a.locator('.game-card').nth(3).waitFor();
89 await a.screenshot({path:path.join(web,'tests/artifacts/desktop.png'),fullPage:true});
99 await a.screenshot({path:path.join(web,'tests/artifacts/desktop.png'),fullPage:true});
90 assert(await a.locator('.square img').evaluateAll(imgs=>imgs.every(i=>i.complete&&i.naturalWidth>0)),'All SVG pieces load');
100 assert(await a.locator('.square img').evaluateAll(imgs=>imgs.every(i=>i.complete&&i.naturalWidth>0)),'All SVG pieces load');
101 await a.setViewportSize({width:1440,height:640});
102 await a.evaluate(()=>scrollTo(0,document.body.scrollHeight));
103 const sidebar=await a.locator('#sidebar').boundingBox();
104 assert(sidebar.y>=0&&sidebar.y+sidebar.height<=640,'Desktop sidebar fits viewport while scrolling');
105 assert.equal(await a.locator('#sidebar').evaluate(e=>getComputedStyle(e).position),'sticky');
106 const staleId=(await state(a)).games[0].id;
107 execFileSync('php',['-r',`$db=new PDO('sqlite:'.$argv[1]);$db->exec('UPDATE games SET activity_at=unixepoch()-8*86400 WHERE id='.(int)$argv[2]);`,path.join(root,'data/microchess.sqlite'),String(staleId)]);
108 await a.locator(`[data-game="${staleId}"] .stop-inactive`).click();
109 await a.getByText('De laatste zet was 8 dagen geleden. Wil je het spel stoppen?').waitFor();
110 await a.getByRole('button',{name:'Annuleren',exact:true}).click();
111 assert((await state(a)).games.some(g=>g.id===staleId),'Cancel retains game');
112 await a.locator(`[data-game="${staleId}"] .stop-inactive`).click();
113 await a.getByRole('button',{name:'Spel stoppen',exact:true}).click();
114 await a.locator(`[data-game="${staleId}"]`).waitFor({state:'detached'});
115 await b.locator(`[data-game="${staleId}"]`).waitFor({state:'detached'});
91 await a.setViewportSize({width:390,height:844});
116 await a.setViewportSize({width:390,height:844});
92 assert(await a.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),'No mobile horizontal overflow');
117 assert(await a.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),'No mobile horizontal overflow');
93 assert.equal(await a.locator('#your-games').evaluate(e=>getComputedStyle(e).gridTemplateColumns.split(' ').length),1,'One tile column');
118 assert.equal(await a.locator('#your-games').evaluate(e=>getComputedStyle(e).gridTemplateColumns.split(' ').length),1,'One tile column');
@@ -96,6 +121,7 @@ try{
96 await a.locator('[data-avatar-group="fairy"]').click();
121 await a.locator('[data-avatar-group="fairy"]').click();
97 await a.locator('#avatar-color').selectOption('Purple');
122 await a.locator('#avatar-color').selectOption('Purple');
98 await a.locator('[data-avatar-choice="purple-elephant"]').waitFor();
123 await a.locator('[data-avatar-choice="purple-elephant"]').waitFor();
124 await a.locator('.avatar-choice img').evaluateAll(imgs=>Promise.all(imgs.map(i=>i.decode())));
99 assert(await a.locator('.avatar-choice img').evaluateAll(imgs=>imgs.every(i=>i.complete&&i.naturalWidth>0)),'Fairy avatars load');
125 assert(await a.locator('.avatar-choice img').evaluateAll(imgs=>imgs.every(i=>i.complete&&i.naturalWidth>0)),'Fairy avatars load');
100 await a.screenshot({path:path.join(web,'tests/artifacts/avatar-picker-mobile.png')});
126 await a.screenshot({path:path.join(web,'tests/artifacts/avatar-picker-mobile.png')});
101 await a.locator('[data-avatar-choice="purple-elephant"]').click();
127 await a.locator('[data-avatar-choice="purple-elephant"]').click();
web/tests/integration.py +19 −2
@@ -85,16 +85,18 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
85 85 check(json.loads(loaded)=={'base_url':'https://example.test','client_id':'fixture-client','client_secret':'fixture-secret'},'Empty fields use environment; configured fields take precedence')
86 86 b.state(); b.post('switch_user', user='test_user_2'); b.state()
87 87 check(b.state()['user']['name'] == 'test_user_2', 'Independent sessions')
88 initial_avatar=b.state()['user']['avatar']
89 check(initial_avatar in {v['id'] for v in json.loads((root/'assets/avatars/catalog.json').read_text())},'Random default avatar')
88 90 a.post('set_avatar',avatar='blue-knight')
89 91 check(a.state()['user']['avatar']=='blue-knight','Avatar persists across requests')
90 check(b.state()['user']['avatar'] is None,'Avatar change affects only the signed-in user')
92 check(b.state()['user']['avatar']==initial_avatar,'Avatar change affects only the signed-in user')
91 93 a.post('set_avatar',avatar='../../data/config.php',expected=409)
92 94 a.post('set_avatar',avatar='not-a-piece',expected=409)
93 95 a.post('set_avatar',avatar=['blue-knight'],expected=409)
94 96 b.post('set_avatar',avatar='purple-elephant')
95 97 check(b.state()['user']['avatar']=='purple-elephant','Fairy avatar can be selected')
96 98 b.post('set_avatar',avatar=None)
97 check(b.state()['user']['avatar'] is None,'Reset avatar to initials')
99 check(b.state()['user']['avatar'] is not None,'Random avatar reset')
98 100 a.post('switch_user', user='admin', expected=409)
99 101 old = a.csrf; a.csrf = 'wrong'; a.post('create_link', kind='match', expected=403); a.csrf = old
100 102 token = a.post('create_link', kind='friend')['url'].split('=')[1]
@@ -187,6 +189,21 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
187 189 check(False,'No production autologin')
188 190 except urllib.error.HTTPError as e:
189 191 check(e.code==401,'No production autologin')
192 # Inactivity is enforced on the server, with stale confirmation protection.
193 token=a.post('create_link',kind='match')['url'].split('=')[1]
194 inactive_id=b.post('accept_link',token=token)['game']
195 a.game_action('stop_inactive',inactive_id,expected=409)
196 con.execute('UPDATE games SET activity_at=? WHERE id=?',(int(time.time())-8*86400,inactive_id));con.commit()
197 old=a.game(inactive_id)
198 check(old['inactiveDays']==8,'Eight inactive days shown')
199 turn=a if old['yourTurn'] else b
200 turn.game_action('move',inactive_id,**turn.game(inactive_id)['legal'][0])
201 a.post('stop_inactive',game=inactive_id,version=old['version'],expected=409)
202 check(a.game(inactive_id)['inactiveDays']==0,'Move resets inactivity')
203 con.execute('UPDATE games SET activity_at=? WHERE id=?',(int(time.time())-7*86400,inactive_id));con.commit()
204 a.game_action('stop_inactive',inactive_id)
205 check(all(g['id']!=inactive_id for c in [a,b] for g in c.state()['games']),'Stop removes both tiles')
206 check(len(a.get('/api.php?action=export')['results'])==3,'Stopped game adds no result')
190 207 con.close()
191 208 print(f'API: {checks} assertions passed.')
192 209 finally:
@@ -85,16 +85,18 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
85 check(json.loads(loaded)=={'base_url':'https://example.test','client_id':'fixture-client','client_secret':'fixture-secret'},'Empty fields use environment; configured fields take precedence')
85 check(json.loads(loaded)=={'base_url':'https://example.test','client_id':'fixture-client','client_secret':'fixture-secret'},'Empty fields use environment; configured fields take precedence')
86 b.state(); b.post('switch_user', user='test_user_2'); b.state()
86 b.state(); b.post('switch_user', user='test_user_2'); b.state()
87 check(b.state()['user']['name'] == 'test_user_2', 'Independent sessions')
87 check(b.state()['user']['name'] == 'test_user_2', 'Independent sessions')
88 initial_avatar=b.state()['user']['avatar']
89 check(initial_avatar in {v['id'] for v in json.loads((root/'assets/avatars/catalog.json').read_text())},'Random default avatar')
88 a.post('set_avatar',avatar='blue-knight')
90 a.post('set_avatar',avatar='blue-knight')
89 check(a.state()['user']['avatar']=='blue-knight','Avatar persists across requests')
91 check(a.state()['user']['avatar']=='blue-knight','Avatar persists across requests')
90 check(b.state()['user']['avatar'] is None,'Avatar change affects only the signed-in user')
92 check(b.state()['user']['avatar']==initial_avatar,'Avatar change affects only the signed-in user')
91 a.post('set_avatar',avatar='../../data/config.php',expected=409)
93 a.post('set_avatar',avatar='../../data/config.php',expected=409)
92 a.post('set_avatar',avatar='not-a-piece',expected=409)
94 a.post('set_avatar',avatar='not-a-piece',expected=409)
93 a.post('set_avatar',avatar=['blue-knight'],expected=409)
95 a.post('set_avatar',avatar=['blue-knight'],expected=409)
94 b.post('set_avatar',avatar='purple-elephant')
96 b.post('set_avatar',avatar='purple-elephant')
95 check(b.state()['user']['avatar']=='purple-elephant','Fairy avatar can be selected')
97 check(b.state()['user']['avatar']=='purple-elephant','Fairy avatar can be selected')
96 b.post('set_avatar',avatar=None)
98 b.post('set_avatar',avatar=None)
97 check(b.state()['user']['avatar'] is None,'Reset avatar to initials')
99 check(b.state()['user']['avatar'] is not None,'Random avatar reset')
98 a.post('switch_user', user='admin', expected=409)
100 a.post('switch_user', user='admin', expected=409)
99 old = a.csrf; a.csrf = 'wrong'; a.post('create_link', kind='match', expected=403); a.csrf = old
101 old = a.csrf; a.csrf = 'wrong'; a.post('create_link', kind='match', expected=403); a.csrf = old
100 token = a.post('create_link', kind='friend')['url'].split('=')[1]
102 token = a.post('create_link', kind='friend')['url'].split('=')[1]
@@ -187,6 +189,21 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
187 check(False,'No production autologin')
189 check(False,'No production autologin')
188 except urllib.error.HTTPError as e:
190 except urllib.error.HTTPError as e:
189 check(e.code==401,'No production autologin')
191 check(e.code==401,'No production autologin')
192 # Inactivity is enforced on the server, with stale confirmation protection.
193 token=a.post('create_link',kind='match')['url'].split('=')[1]
194 inactive_id=b.post('accept_link',token=token)['game']
195 a.game_action('stop_inactive',inactive_id,expected=409)
196 con.execute('UPDATE games SET activity_at=? WHERE id=?',(int(time.time())-8*86400,inactive_id));con.commit()
197 old=a.game(inactive_id)
198 check(old['inactiveDays']==8,'Eight inactive days shown')
199 turn=a if old['yourTurn'] else b
200 turn.game_action('move',inactive_id,**turn.game(inactive_id)['legal'][0])
201 a.post('stop_inactive',game=inactive_id,version=old['version'],expected=409)
202 check(a.game(inactive_id)['inactiveDays']==0,'Move resets inactivity')
203 con.execute('UPDATE games SET activity_at=? WHERE id=?',(int(time.time())-7*86400,inactive_id));con.commit()
204 a.game_action('stop_inactive',inactive_id)
205 check(all(g['id']!=inactive_id for c in [a,b] for g in c.state()['games']),'Stop removes both tiles')
206 check(len(a.get('/api.php?action=export')['results'])==3,'Stopped game adds no result')
190 con.close()
207 con.close()
191 print(f'API: {checks} assertions passed.')
208 print(f'API: {checks} assertions passed.')
192 finally:
209 finally: