BlueGit

projects-timfalken-com microchess

Store disable-custom-colours on the account, not localStorage.

Persists with user_piece_colors and syncs via set_disable_custom_colours
so the preference follows the signed-in account.

timfa Tim Falken · pushed by timfa

Authored 2026-09-13 · 2 months ago

Hash
6451d4366078e2463e652ca87dce9e2bbe2f469b
Parent
f96fcb20
5 files changed +29 −14
web/README.md +1 −1
@@ -80,7 +80,7 @@ The integration tests exercise rating updates, rematches, duplicate results, con
80 80
81 81 ## Avatars
82 82
83 Click your avatar at the bottom of the friends sidebar to open the piece picker. The local collection contains 103 selected avatars: 67 fairy pieces and 36 colored standard pieces (including White and Black). Removed files are excluded from the catalog; PNG and SVG versions of the same piece appear as one choice. The picker has 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. Click your name under the avatar to choose default or custom piece colours (White/Black/Red/Blue/Green/Yellow); resolved skins are stored per game for live play and replays. Account settings can disable custom colours locally (default on). The `user_avatars` table is created automatically, preserving existing accounts and game data.
83 Click your avatar at the bottom of the friends sidebar to open the piece picker. The local collection contains 103 selected avatars: 67 fairy pieces and 36 colored standard pieces (including White and Black). Removed files are excluded from the catalog; PNG and SVG versions of the same piece appear as one choice. The picker has 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. Click your name under the avatar to choose default or custom piece colours (White/Black/Red/Blue/Green/Yellow); resolved skins are stored per game for live play and replays. Account settings store a “Disable custom colours” preference on your account (default off, so custom colours show). The `user_avatars` table is created automatically, preserving existing accounts and game data.
84 84
85 85 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.
86 86
@@ -80,7 +80,7 @@ The integration tests exercise rating updates, rematches, duplicate results, con
80
80
81## Avatars
81## Avatars
82
82
83Click your avatar at the bottom of the friends sidebar to open the piece picker. The local collection contains 103 selected avatars: 67 fairy pieces and 36 colored standard pieces (including White and Black). Removed files are excluded from the catalog; PNG and SVG versions of the same piece appear as one choice. The picker has 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. Click your name under the avatar to choose default or custom piece colours (White/Black/Red/Blue/Green/Yellow); resolved skins are stored per game for live play and replays. Account settings can disable custom colours locally (default on). The `user_avatars` table is created automatically, preserving existing accounts and game data.
83Click your avatar at the bottom of the friends sidebar to open the piece picker. The local collection contains 103 selected avatars: 67 fairy pieces and 36 colored standard pieces (including White and Black). Removed files are excluded from the catalog; PNG and SVG versions of the same piece appear as one choice. The picker has 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. Click your name under the avatar to choose default or custom piece colours (White/Black/Red/Blue/Green/Yellow); resolved skins are stored per game for live play and replays. Account settings store a “Disable custom colours” preference on your account (default off, so custom colours show). The `user_avatars` table is created automatically, preserving existing accounts and game data.
84
84
85Avatars 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.
85Avatars 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.
86
86
web/api.php +2 −0
@@ -145,6 +145,8 @@ try {
145 145 $alternative=$in['alternativeColor']??'';
146 146 if (!is_string($mode)||!is_string($preferred)||!is_string($alternative)) throw new DomainException('Invalid colour preference.');
147 147 savePieceColorPrefs($u,$mode,$preferred,$alternative);
148 } elseif ($action==='set_disable_custom_colours') {
149 saveDisableCustomColours($u,!empty($in['disabled']));
148 150 } elseif ($action==='create_link') {
149 151 $kind=$in['kind']??''; if (!in_array($kind,['friend','match'],true)) throw new DomainException('Invalid invitation type.');
150 152 $token=bin2hex(random_bytes(24));
@@ -145,6 +145,8 @@ try {
145 $alternative=$in['alternativeColor']??'';
145 $alternative=$in['alternativeColor']??'';
146 if (!is_string($mode)||!is_string($preferred)||!is_string($alternative)) throw new DomainException('Invalid colour preference.');
146 if (!is_string($mode)||!is_string($preferred)||!is_string($alternative)) throw new DomainException('Invalid colour preference.');
147 savePieceColorPrefs($u,$mode,$preferred,$alternative);
147 savePieceColorPrefs($u,$mode,$preferred,$alternative);
148 } elseif ($action==='set_disable_custom_colours') {
149 saveDisableCustomColours($u,!empty($in['disabled']));
148 } elseif ($action==='create_link') {
150 } elseif ($action==='create_link') {
149 $kind=$in['kind']??''; if (!in_array($kind,['friend','match'],true)) throw new DomainException('Invalid invitation type.');
151 $kind=$in['kind']??''; if (!in_array($kind,['friend','match'],true)) throw new DomainException('Invalid invitation type.');
150 $token=bin2hex(random_bytes(24));
152 $token=bin2hex(random_bytes(24));
web/assets/app.js +3 −8
@@ -6,15 +6,10 @@ const materialValues = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 };
6 6 const PIECE_COLOR_ORDER = ['White', 'Black', 'Red', 'Blue', 'Green', 'Yellow'];
7 7 const CUSTOM_PIECE_SKINS = new Set(['Red', 'Blue', 'Green', 'Yellow']);
8 8 const pieceFileNames = { k: 'king', q: 'queen', r: 'rook', b: 'bishop', n: 'knight', p: 'pawn' };
9 const DISABLE_CUSTOM_COLOURS_KEY = 'microchess-disable-custom-colours';
10 9 function customColoursDisabled ()
11 10 {
12 // Default off → custom colours visible unless the player opted out.
13 try { return localStorage.getItem(DISABLE_CUSTOM_COLOURS_KEY) === '1'; } catch { return false; }
14 }
15 function setCustomColoursDisabled (disabled)
16 {
17 try { localStorage.setItem(DISABLE_CUSTOM_COLOURS_KEY, disabled ? '1' : '0'); } catch {}
11 // Account preference (default off → custom colours visible).
12 return !!(state?.user?.disableCustomColours);
18 13 }
19 14 const classicPieceUrl = p => `assets/pieces/${p.toLowerCase()}${p === p.toUpperCase() ? 'l' : 'd'}t.svg`;
20 15 const pieceUrl = (p, skin) =>
@@ -393,7 +388,7 @@ function renderMatchmaking ()
393 388 async function createLink (kind) { await action({ action: 'create_link', kind }, r => { showModal(`<span class="eyebrow">${kind === 'friend' ? 'GOOD COMPANY' : 'GAME ON'}</span><h2>${kind === 'friend' ? 'Invite a friend.' : 'Send a little challenge.'}</h2><p>Share this link. ${kind === 'friend' ? 'You’ll become friends when the other person clicks accept.' : 'The first person to accept starts a game with you.'} It expires in one month.</p><input aria-label="Invitation link" id="share-url" readonly value="${esc(r.url)}"><div class="actions"><button class="primary" data-modal-action="copy">Copy link ↗</button></div>${kind === 'match' ? '<div id="matchmaking-actions" class="settings-actions"></div>' : ''}`); renderMatchmaking(); }); }
394 389 if ($('#match-link')) $('#match-link').onclick = () => createLink('match');
395 390 if ($('#friend-link')) $('#friend-link').onclick = () => createLink('friend');
396 if ($('#settings-button')) $('#settings-button').onclick = () => { if (!state) return; showModal(`<h2>Your account</h2><p>Signed in as ${esc(state.user.name)}.</p><p>${state.user.rating} Elo</p><label class="settings-check"><input type="checkbox" id="disable-custom-colours" ${customColoursDisabled() ? 'checked' : ''}> Disable custom colours</label><div id="notification-settings"></div><div class="settings-actions"><button class="secondary" data-install-app>Add to home screen</button><p id="install-help" hidden></p>${state.local ? `<button class="secondary" data-modal-action="switch">Switch to ${state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1'}</button>` : ''}<a class="button secondary" href="api.php?action=export" download>Export my data (JSON)</a><button class="secondary" data-modal-action="logout">Sign out</button></div>`); $('#disable-custom-colours').onchange = e => { setCustomColoursDisabled(e.target.checked); renderGames(); }; window.microchessPwa?.settings(); };
391 if ($('#settings-button')) $('#settings-button').onclick = () => { if (!state) return; showModal(`<h2>Your account</h2><p>Signed in as ${esc(state.user.name)}.</p><p>${state.user.rating} Elo</p><label class="settings-check"><input type="checkbox" id="disable-custom-colours" ${customColoursDisabled() ? 'checked' : ''}> Disable custom colours</label><div id="notification-settings"></div><div class="settings-actions"><button class="secondary" data-install-app>Add to home screen</button><p id="install-help" hidden></p>${state.local ? `<button class="secondary" data-modal-action="switch">Switch to ${state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1'}</button>` : ''}<a class="button secondary" href="api.php?action=export" download>Export my data (JSON)</a><button class="secondary" data-modal-action="logout">Sign out</button></div>`); $('#disable-custom-colours').onchange = e => { action({ action: 'set_disable_custom_colours', disabled: e.target.checked }, () => toast(e.target.checked ? 'Custom colours hidden.' : 'Custom colours shown.')); }; window.microchessPwa?.settings(); };
397 392 if ($('#rules-button')) $('#rules-button').onclick = () => showModal(`<span class="eyebrow">MICROCHESS</span><h2>Small board. Real chess.</h2><p>The usual rules of chess, on a 4 × 5 board.</p><ul class="rules-list"><li>Each side starts with a king, rook, bishop, knight and one pawn. White moves first.</li><li>Pawns move one square forward, capture diagonally and never move two squares. There is no castling or en passant.</li><li>Reach the last rank to promote to a queen, rook, bishop or knight.</li><li>Protect your king. Checkmate wins; stalemate and dead positions draw.</li><li>Claim a draw after three repetitions or 50 moves by each side without a pawn move or capture. You may also claim with an intended move, via the game menu. Five repetitions or 75 moves draw automatically.</li><li>Click a piece to see legal destinations, then click a dot. Or drag it to a destination.</li><li>The bar below your opponent’s name compares remaining material: White on the left, Black on the right. Pawn 1, knight/bishop 3, rook 5, queen 9; kings are not counted.</li><li>After your move, a blue pulse marks a clear estimated gain; red marks a likely material loss or mating threat. This quick tactical check can miss deeper ideas. Quiet or uncertain moves get no pulse.</li></ul><p class="inline-note">Pieces by Cburnett, from <a href="https://commons.wikimedia.org/wiki/Category:SVG_chess_pieces" target="_blank" rel="noreferrer">Wikimedia Commons</a>, <a href="https://creativecommons.org/licenses/by-sa/3.0/" target="_blank" rel="noreferrer">CC BY-SA 3.0</a>. Unmodified SVGs.</p>`);
398 393 document.addEventListener('click', e =>
399 394 {
@@ -6,15 +6,10 @@ const materialValues = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 };
6const PIECE_COLOR_ORDER = ['White', 'Black', 'Red', 'Blue', 'Green', 'Yellow'];
6const PIECE_COLOR_ORDER = ['White', 'Black', 'Red', 'Blue', 'Green', 'Yellow'];
7const CUSTOM_PIECE_SKINS = new Set(['Red', 'Blue', 'Green', 'Yellow']);
7const CUSTOM_PIECE_SKINS = new Set(['Red', 'Blue', 'Green', 'Yellow']);
8const pieceFileNames = { k: 'king', q: 'queen', r: 'rook', b: 'bishop', n: 'knight', p: 'pawn' };
8const pieceFileNames = { k: 'king', q: 'queen', r: 'rook', b: 'bishop', n: 'knight', p: 'pawn' };
9const DISABLE_CUSTOM_COLOURS_KEY = 'microchess-disable-custom-colours';
10function customColoursDisabled ()
9function customColoursDisabled ()
11{
10{
12 // Default off → custom colours visible unless the player opted out.
11 // Account preference (default off → custom colours visible).
13 try { return localStorage.getItem(DISABLE_CUSTOM_COLOURS_KEY) === '1'; } catch { return false; }
12 return !!(state?.user?.disableCustomColours);
14}
15function setCustomColoursDisabled (disabled)
16{
17 try { localStorage.setItem(DISABLE_CUSTOM_COLOURS_KEY, disabled ? '1' : '0'); } catch {}
18}
13}
19const classicPieceUrl = p => `assets/pieces/${p.toLowerCase()}${p === p.toUpperCase() ? 'l' : 'd'}t.svg`;
14const classicPieceUrl = p => `assets/pieces/${p.toLowerCase()}${p === p.toUpperCase() ? 'l' : 'd'}t.svg`;
20const pieceUrl = (p, skin) =>
15const pieceUrl = (p, skin) =>
@@ -393,7 +388,7 @@ function renderMatchmaking ()
393async function createLink (kind) { await action({ action: 'create_link', kind }, r => { showModal(`<span class="eyebrow">${kind === 'friend' ? 'GOOD COMPANY' : 'GAME ON'}</span><h2>${kind === 'friend' ? 'Invite a friend.' : 'Send a little challenge.'}</h2><p>Share this link. ${kind === 'friend' ? 'You’ll become friends when the other person clicks accept.' : 'The first person to accept starts a game with you.'} It expires in one month.</p><input aria-label="Invitation link" id="share-url" readonly value="${esc(r.url)}"><div class="actions"><button class="primary" data-modal-action="copy">Copy link ↗</button></div>${kind === 'match' ? '<div id="matchmaking-actions" class="settings-actions"></div>' : ''}`); renderMatchmaking(); }); }
388async function createLink (kind) { await action({ action: 'create_link', kind }, r => { showModal(`<span class="eyebrow">${kind === 'friend' ? 'GOOD COMPANY' : 'GAME ON'}</span><h2>${kind === 'friend' ? 'Invite a friend.' : 'Send a little challenge.'}</h2><p>Share this link. ${kind === 'friend' ? 'You’ll become friends when the other person clicks accept.' : 'The first person to accept starts a game with you.'} It expires in one month.</p><input aria-label="Invitation link" id="share-url" readonly value="${esc(r.url)}"><div class="actions"><button class="primary" data-modal-action="copy">Copy link ↗</button></div>${kind === 'match' ? '<div id="matchmaking-actions" class="settings-actions"></div>' : ''}`); renderMatchmaking(); }); }
394if ($('#match-link')) $('#match-link').onclick = () => createLink('match');
389if ($('#match-link')) $('#match-link').onclick = () => createLink('match');
395if ($('#friend-link')) $('#friend-link').onclick = () => createLink('friend');
390if ($('#friend-link')) $('#friend-link').onclick = () => createLink('friend');
396if ($('#settings-button')) $('#settings-button').onclick = () => { if (!state) return; showModal(`<h2>Your account</h2><p>Signed in as ${esc(state.user.name)}.</p><p>${state.user.rating} Elo</p><label class="settings-check"><input type="checkbox" id="disable-custom-colours" ${customColoursDisabled() ? 'checked' : ''}> Disable custom colours</label><div id="notification-settings"></div><div class="settings-actions"><button class="secondary" data-install-app>Add to home screen</button><p id="install-help" hidden></p>${state.local ? `<button class="secondary" data-modal-action="switch">Switch to ${state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1'}</button>` : ''}<a class="button secondary" href="api.php?action=export" download>Export my data (JSON)</a><button class="secondary" data-modal-action="logout">Sign out</button></div>`); $('#disable-custom-colours').onchange = e => { setCustomColoursDisabled(e.target.checked); renderGames(); }; window.microchessPwa?.settings(); };
391if ($('#settings-button')) $('#settings-button').onclick = () => { if (!state) return; showModal(`<h2>Your account</h2><p>Signed in as ${esc(state.user.name)}.</p><p>${state.user.rating} Elo</p><label class="settings-check"><input type="checkbox" id="disable-custom-colours" ${customColoursDisabled() ? 'checked' : ''}> Disable custom colours</label><div id="notification-settings"></div><div class="settings-actions"><button class="secondary" data-install-app>Add to home screen</button><p id="install-help" hidden></p>${state.local ? `<button class="secondary" data-modal-action="switch">Switch to ${state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1'}</button>` : ''}<a class="button secondary" href="api.php?action=export" download>Export my data (JSON)</a><button class="secondary" data-modal-action="logout">Sign out</button></div>`); $('#disable-custom-colours').onchange = e => { action({ action: 'set_disable_custom_colours', disabled: e.target.checked }, () => toast(e.target.checked ? 'Custom colours hidden.' : 'Custom colours shown.')); }; window.microchessPwa?.settings(); };
397if ($('#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>`);
392if ($('#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>`);
398document.addEventListener('click', e =>
393document.addEventListener('click', e =>
399{
394{
web/lib/PieceColors.php +16 −4
@@ -5,12 +5,12 @@ const PIECE_COLORS = ['White', 'Black', 'Red', 'Blue', 'Green', 'Yellow'];
5 5
6 6 function defaultPieceColorPrefs(): array
7 7 {
8 return ['color_mode' => 'default', 'preferred_color' => 'White', 'alternative_color' => 'Black'];
8 return ['color_mode' => 'default', 'preferred_color' => 'White', 'alternative_color' => 'Black', 'disable_custom_colours' => 0];
9 9 }
10 10
11 11 function pieceColorPrefs(string $userId): array
12 12 {
13 $row = query('SELECT color_mode, preferred_color, alternative_color FROM user_piece_colors WHERE user_id=?', [$userId])->fetch();
13 $row = query('SELECT color_mode, preferred_color, alternative_color, COALESCE(disable_custom_colours, 0) AS disable_custom_colours FROM user_piece_colors WHERE user_id=?', [$userId])->fetch();
14 14 return $row ?: defaultPieceColorPrefs();
15 15 }
16 16
@@ -30,10 +30,22 @@ function validatePieceColors(string $mode, string $preferred, string $alternativ
30 30 function savePieceColorPrefs(string $userId, string $mode, string $preferred, string $alternative): void
31 31 {
32 32 validatePieceColors($mode, $preferred, $alternative);
33 $existing = query('SELECT disable_custom_colours FROM user_piece_colors WHERE user_id=?', [$userId])->fetchColumn();
34 $disable = $existing === false ? 0 : (int)$existing;
33 35 query(
34 'INSERT INTO user_piece_colors(user_id,color_mode,preferred_color,alternative_color) VALUES(?,?,?,?)
36 'INSERT INTO user_piece_colors(user_id,color_mode,preferred_color,alternative_color,disable_custom_colours) VALUES(?,?,?,?,?)
35 37 ON CONFLICT(user_id) DO UPDATE SET color_mode=excluded.color_mode, preferred_color=excluded.preferred_color, alternative_color=excluded.alternative_color',
36 [$userId, $mode, $preferred, $alternative]
38 [$userId, $mode, $preferred, $alternative, $disable]
39 );
40 }
41
42 function saveDisableCustomColours(string $userId, bool $disabled): void
43 {
44 $row = pieceColorPrefs($userId);
45 query(
46 'INSERT INTO user_piece_colors(user_id,color_mode,preferred_color,alternative_color,disable_custom_colours) VALUES(?,?,?,?,?)
47 ON CONFLICT(user_id) DO UPDATE SET disable_custom_colours=excluded.disable_custom_colours',
48 [$userId, $row['color_mode'], $row['preferred_color'], $row['alternative_color'], $disabled ? 1 : 0]
37 49 );
38 50 }
39 51
@@ -5,12 +5,12 @@ const PIECE_COLORS = ['White', 'Black', 'Red', 'Blue', 'Green', 'Yellow'];
5
5
6function defaultPieceColorPrefs(): array
6function defaultPieceColorPrefs(): array
7{
7{
8 return ['color_mode' => 'default', 'preferred_color' => 'White', 'alternative_color' => 'Black'];
8 return ['color_mode' => 'default', 'preferred_color' => 'White', 'alternative_color' => 'Black', 'disable_custom_colours' => 0];
9}
9}
10
10
11function pieceColorPrefs(string $userId): array
11function pieceColorPrefs(string $userId): array
12{
12{
13 $row = query('SELECT color_mode, preferred_color, alternative_color FROM user_piece_colors WHERE user_id=?', [$userId])->fetch();
13 $row = query('SELECT color_mode, preferred_color, alternative_color, COALESCE(disable_custom_colours, 0) AS disable_custom_colours FROM user_piece_colors WHERE user_id=?', [$userId])->fetch();
14 return $row ?: defaultPieceColorPrefs();
14 return $row ?: defaultPieceColorPrefs();
15}
15}
16
16
@@ -30,10 +30,22 @@ function validatePieceColors(string $mode, string $preferred, string $alternativ
30function savePieceColorPrefs(string $userId, string $mode, string $preferred, string $alternative): void
30function savePieceColorPrefs(string $userId, string $mode, string $preferred, string $alternative): void
31{
31{
32 validatePieceColors($mode, $preferred, $alternative);
32 validatePieceColors($mode, $preferred, $alternative);
33 $existing = query('SELECT disable_custom_colours FROM user_piece_colors WHERE user_id=?', [$userId])->fetchColumn();
34 $disable = $existing === false ? 0 : (int)$existing;
33 query(
35 query(
34 'INSERT INTO user_piece_colors(user_id,color_mode,preferred_color,alternative_color) VALUES(?,?,?,?)
36 'INSERT INTO user_piece_colors(user_id,color_mode,preferred_color,alternative_color,disable_custom_colours) VALUES(?,?,?,?,?)
35 ON CONFLICT(user_id) DO UPDATE SET color_mode=excluded.color_mode, preferred_color=excluded.preferred_color, alternative_color=excluded.alternative_color',
37 ON CONFLICT(user_id) DO UPDATE SET color_mode=excluded.color_mode, preferred_color=excluded.preferred_color, alternative_color=excluded.alternative_color',
36 [$userId, $mode, $preferred, $alternative]
38 [$userId, $mode, $preferred, $alternative, $disable]
39 );
40}
41
42function saveDisableCustomColours(string $userId, bool $disabled): void
43{
44 $row = pieceColorPrefs($userId);
45 query(
46 'INSERT INTO user_piece_colors(user_id,color_mode,preferred_color,alternative_color,disable_custom_colours) VALUES(?,?,?,?,?)
47 ON CONFLICT(user_id) DO UPDATE SET disable_custom_colours=excluded.disable_custom_colours',
48 [$userId, $row['color_mode'], $row['preferred_color'], $row['alternative_color'], $disabled ? 1 : 0]
37 );
49 );
38}
50}
39
51
web/lib/bootstrap.php +7 −1
@@ -70,10 +70,15 @@ function db(): PDO {
70 70 color_mode TEXT NOT NULL DEFAULT \'default\' CHECK(color_mode IN (\'default\',\'custom\')),
71 71 preferred_color TEXT NOT NULL DEFAULT \'White\',
72 72 alternative_color TEXT NOT NULL DEFAULT \'Black\',
73 disable_custom_colours INTEGER NOT NULL DEFAULT 0,
73 74 CHECK(preferred_color IN (\'White\',\'Black\',\'Red\',\'Blue\',\'Green\',\'Yellow\')),
74 75 CHECK(alternative_color IN (\'White\',\'Black\',\'Red\',\'Blue\',\'Green\',\'Yellow\')),
75 76 CHECK(preferred_color <> alternative_color)
76 77 );');
78 $pieceColorCols=$db->query('PRAGMA table_info(user_piece_colors)')->fetchAll(PDO::FETCH_COLUMN,1);
79 if (!in_array('disable_custom_colours',$pieceColorCols,true)) {
80 $db->exec('ALTER TABLE user_piece_colors ADD COLUMN disable_custom_colours INTEGER NOT NULL DEFAULT 0');
81 }
77 82 $gameCols=$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1);
78 83 if (!in_array('piece_skin_white',$gameCols,true)) {
79 84 $db->exec('BEGIN IMMEDIATE');
@@ -127,7 +132,8 @@ function activityTriggers(PDO $db): void {
127 132 }
128 133 function query(string $sql,array $args=[]): PDOStatement { $s=db()->prepare($sql);$s->execute($args);return $s; }
129 134 function profile(string $id): array {
130 $p=query('SELECT u.*,a.avatar,COALESCE(r.rating,1200) AS rating,COALESCE(r.played,0) AS ratedGames,COALESCE(c.color_mode,\'default\') AS colorMode,COALESCE(c.preferred_color,\'White\') AS preferredColor,COALESCE(c.alternative_color,\'Black\') AS alternativeColor FROM users u LEFT JOIN user_avatars a ON a.user_id=u.id LEFT JOIN ratings r ON r.user_id=u.id LEFT JOIN user_piece_colors c ON c.user_id=u.id WHERE u.id=?',[$id])->fetch();
135 $p=query('SELECT u.*,a.avatar,COALESCE(r.rating,1200) AS rating,COALESCE(r.played,0) AS ratedGames,COALESCE(c.color_mode,\'default\') AS colorMode,COALESCE(c.preferred_color,\'White\') AS preferredColor,COALESCE(c.alternative_color,\'Black\') AS alternativeColor,COALESCE(c.disable_custom_colours,0) AS disableCustomColours FROM users u LEFT JOIN user_avatars a ON a.user_id=u.id LEFT JOIN ratings r ON r.user_id=u.id LEFT JOIN user_piece_colors c ON c.user_id=u.id WHERE u.id=?',[$id])->fetch();
136 if ($p) { $p['disableCustomColours'] = !empty($p['disableCustomColours']); }
131 137 return $p;
132 138 }
133 139 function avatarCatalog(): array {
@@ -70,10 +70,15 @@ function db(): PDO {
70 color_mode TEXT NOT NULL DEFAULT \'default\' CHECK(color_mode IN (\'default\',\'custom\')),
70 color_mode TEXT NOT NULL DEFAULT \'default\' CHECK(color_mode IN (\'default\',\'custom\')),
71 preferred_color TEXT NOT NULL DEFAULT \'White\',
71 preferred_color TEXT NOT NULL DEFAULT \'White\',
72 alternative_color TEXT NOT NULL DEFAULT \'Black\',
72 alternative_color TEXT NOT NULL DEFAULT \'Black\',
73 disable_custom_colours INTEGER NOT NULL DEFAULT 0,
73 CHECK(preferred_color IN (\'White\',\'Black\',\'Red\',\'Blue\',\'Green\',\'Yellow\')),
74 CHECK(preferred_color IN (\'White\',\'Black\',\'Red\',\'Blue\',\'Green\',\'Yellow\')),
74 CHECK(alternative_color IN (\'White\',\'Black\',\'Red\',\'Blue\',\'Green\',\'Yellow\')),
75 CHECK(alternative_color IN (\'White\',\'Black\',\'Red\',\'Blue\',\'Green\',\'Yellow\')),
75 CHECK(preferred_color <> alternative_color)
76 CHECK(preferred_color <> alternative_color)
76 );');
77 );');
78 $pieceColorCols=$db->query('PRAGMA table_info(user_piece_colors)')->fetchAll(PDO::FETCH_COLUMN,1);
79 if (!in_array('disable_custom_colours',$pieceColorCols,true)) {
80 $db->exec('ALTER TABLE user_piece_colors ADD COLUMN disable_custom_colours INTEGER NOT NULL DEFAULT 0');
81 }
77 $gameCols=$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1);
82 $gameCols=$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1);
78 if (!in_array('piece_skin_white',$gameCols,true)) {
83 if (!in_array('piece_skin_white',$gameCols,true)) {
79 $db->exec('BEGIN IMMEDIATE');
84 $db->exec('BEGIN IMMEDIATE');
@@ -127,7 +132,8 @@ function activityTriggers(PDO $db): void {
127}
132}
128function query(string $sql,array $args=[]): PDOStatement { $s=db()->prepare($sql);$s->execute($args);return $s; }
133function query(string $sql,array $args=[]): PDOStatement { $s=db()->prepare($sql);$s->execute($args);return $s; }
129function profile(string $id): array {
134function profile(string $id): array {
130 $p=query('SELECT u.*,a.avatar,COALESCE(r.rating,1200) AS rating,COALESCE(r.played,0) AS ratedGames,COALESCE(c.color_mode,\'default\') AS colorMode,COALESCE(c.preferred_color,\'White\') AS preferredColor,COALESCE(c.alternative_color,\'Black\') AS alternativeColor FROM users u LEFT JOIN user_avatars a ON a.user_id=u.id LEFT JOIN ratings r ON r.user_id=u.id LEFT JOIN user_piece_colors c ON c.user_id=u.id WHERE u.id=?',[$id])->fetch();
135 $p=query('SELECT u.*,a.avatar,COALESCE(r.rating,1200) AS rating,COALESCE(r.played,0) AS ratedGames,COALESCE(c.color_mode,\'default\') AS colorMode,COALESCE(c.preferred_color,\'White\') AS preferredColor,COALESCE(c.alternative_color,\'Black\') AS alternativeColor,COALESCE(c.disable_custom_colours,0) AS disableCustomColours FROM users u LEFT JOIN user_avatars a ON a.user_id=u.id LEFT JOIN ratings r ON r.user_id=u.id LEFT JOIN user_piece_colors c ON c.user_id=u.id WHERE u.id=?',[$id])->fetch();
136 if ($p) { $p['disableCustomColours'] = !empty($p['disableCustomColours']); }
131 return $p;
137 return $p;
132}
138}
133function avatarCatalog(): array {
139function avatarCatalog(): array {