BlueGit

projects-timfalken-com allianties

Board tokens: always-visible colour circle with initials, picture layered on top (robust to load errors and poll re-renders); no-scroll game view on mobile

timfa Grok Bot · pushed by timfa

Authored 2026-11-14 · 3 days ago

Hash
8d4ac19d6408b81420e91236732e6f610a2bcab5
Parent
cc22ff51
10 files changed +585 −64
README.md +11 −0
@@ -78,6 +78,16 @@ php -S 127.0.0.1:8080 -t build build/router.php
78 78
79 79 De testlogins (`auth.php?test=1` … `?test=8`) werken alleen op localhost en
80 80 zijn op de live site uitgeschakeld.
81 Met `&avatar=none` (geen profielplaatje) of `&avatar=broken` (plaatje-URL
82 die 404 geeft) test je spelers zonder plaatje.
83
84 Browsertests (Playwright, met de lokale server):
85
86 ```bash
87 python3 test/ui-playwright.py # hele flow, desktop + mobiel
88 python3 test/lobby-interaction-playwright.py # klok slepen, focus, host-only, tijdzones
89 python3 test/avatar-layout-playwright.py # speelstukken zonder plaatje, geen scroll op mobiel
90 ```
81 91
82 92 ## Architectuur
83 93
@@ -86,6 +96,7 @@ zijn op de live site uitgeschakeld.
86 96 | `src/i18n.js` | Vertalingen en vlaggenkiezer (Engels als standaard, 10 talen) |
87 97 | `src/rules.js` | Client-spiegel van raster, Chebyshev, staakt-het-vuren (incl. zomertijd) |
88 98 | `src/api.js` | API-client, CSRF, lichte `sync`-poll |
99 | `src/avatar.js` | Speelstukken: kleurcirkel met initialen, plaatje erbovenop (robuust bij laadfouten) |
89 100 | `src/main.js` | Menu, lobby, bord, tijdlijn, klok-editor, countdowns |
90 101 | `server/lib/Engine.php` | Authoritatieve regelmotor: zetten, jury, krimp, staakt-het-vuren, einde |
91 102 | `server/lib/Store.php` | SQLite, `BEGIN IMMEDIATE`, JSON-game, profielen |
@@ -78,6 +78,16 @@ php -S 127.0.0.1:8080 -t build build/router.php
78
78
79De testlogins (`auth.php?test=1` … `?test=8`) werken alleen op localhost en
79De testlogins (`auth.php?test=1` … `?test=8`) werken alleen op localhost en
80zijn op de live site uitgeschakeld.
80zijn op de live site uitgeschakeld.
81Met `&avatar=none` (geen profielplaatje) of `&avatar=broken` (plaatje-URL
82die 404 geeft) test je spelers zonder plaatje.
83
84Browsertests (Playwright, met de lokale server):
85
86```bash
87python3 test/ui-playwright.py # hele flow, desktop + mobiel
88python3 test/lobby-interaction-playwright.py # klok slepen, focus, host-only, tijdzones
89python3 test/avatar-layout-playwright.py # speelstukken zonder plaatje, geen scroll op mobiel
90```
81
91
82## Architectuur
92## Architectuur
83
93
@@ -86,6 +96,7 @@ zijn op de live site uitgeschakeld.
86| `src/i18n.js` | Vertalingen en vlaggenkiezer (Engels als standaard, 10 talen) |
96| `src/i18n.js` | Vertalingen en vlaggenkiezer (Engels als standaard, 10 talen) |
87| `src/rules.js` | Client-spiegel van raster, Chebyshev, staakt-het-vuren (incl. zomertijd) |
97| `src/rules.js` | Client-spiegel van raster, Chebyshev, staakt-het-vuren (incl. zomertijd) |
88| `src/api.js` | API-client, CSRF, lichte `sync`-poll |
98| `src/api.js` | API-client, CSRF, lichte `sync`-poll |
99| `src/avatar.js` | Speelstukken: kleurcirkel met initialen, plaatje erbovenop (robuust bij laadfouten) |
89| `src/main.js` | Menu, lobby, bord, tijdlijn, klok-editor, countdowns |
100| `src/main.js` | Menu, lobby, bord, tijdlijn, klok-editor, countdowns |
90| `server/lib/Engine.php` | Authoritatieve regelmotor: zetten, jury, krimp, staakt-het-vuren, einde |
101| `server/lib/Engine.php` | Authoritatieve regelmotor: zetten, jury, krimp, staakt-het-vuren, einde |
91| `server/lib/Store.php` | SQLite, `BEGIN IMMEDIATE`, JSON-game, profielen |
102| `server/lib/Store.php` | SQLite, `BEGIN IMMEDIATE`, JSON-game, profielen |
build/index.html +1 −1
@@ -43,7 +43,7 @@
43 43 </span>
44 44 </p>
45 45 <p id="menu-user" hidden>
46 <img id="menu-avatar" class="avatar-sm" alt="" width="32" height="32">
46 <span id="menu-avatar" class="avatar-sm"></span>
47 47 <span data-i18n="menu.loggedInAs">Logged in as</span>
48 48 <strong id="menu-name"></strong>
49 49 · <a id="menu-logout" href="logout.php" data-i18n="menu.logout">Log out</a>
@@ -43,7 +43,7 @@
43 </span>
43 </span>
44 </p>
44 </p>
45 <p id="menu-user" hidden>
45 <p id="menu-user" hidden>
46 <img id="menu-avatar" class="avatar-sm" alt="" width="32" height="32">
46 <span id="menu-avatar" class="avatar-sm"></span>
47 <span data-i18n="menu.loggedInAs">Logged in as</span>
47 <span data-i18n="menu.loggedInAs">Logged in as</span>
48 <strong id="menu-name"></strong>
48 <strong id="menu-name"></strong>
49 · <a id="menu-logout" href="logout.php" data-i18n="menu.logout">Log out</a>
49 · <a id="menu-logout" href="logout.php" data-i18n="menu.logout">Log out</a>
build/style.css +101 −2
@@ -287,13 +287,47 @@ button.cell {
287 287 .piece-fixed {
288 288 width: var(--sz, 40px) !important;
289 289 height: var(--sz, 40px) !important;
290 max-width: none;
291 max-height: none;
290 292 border-width: 2px;
291 293 font-size: calc(var(--sz, 40px) * 0.38);
292 294 }
295 /* Token: always a visible circle in the player's colour with initials;
296 a profile picture (if it loads) is layered on top. See src/avatar.js. */
297 .piece-token {
298 position: relative;
299 display: inline-flex;
300 align-items: center;
301 justify-content: center;
302 overflow: hidden;
303 background-color: var(--c, #888);
304 box-sizing: border-box;
305 line-height: 1;
306 user-select: none;
307 }
308 .cell { container-type: inline-size; }
293 309 .piece-initials {
294 display: flex; align-items: center; justify-content: center;
295 font-weight: 700; font-size: 0.7em; color: #fff;
310 display: block;
311 font-weight: 800;
312 font-size: 0.8em;
313 font-size: 30cqw;
314 letter-spacing: 0.02em;
315 color: inherit;
316 text-shadow: 0 1px 2px #0006;
317 pointer-events: none;
296 318 }
319 .piece-fixed .piece-initials { font-size: calc(var(--sz, 40px) * 0.38); }
320 .piece-img {
321 position: absolute;
322 inset: 0;
323 width: 100%;
324 height: 100%;
325 object-fit: cover;
326 border-radius: 50%;
327 pointer-events: none;
328 }
329 .piece.has-img .piece-initials { visibility: hidden; }
330 #menu-avatar { display: inline-flex; background: none; }
297 331
298 332 /* Timeline */
299 333 #timeline {
@@ -573,3 +607,68 @@ button.cell {
573 607 #cf-clock svg.readonly { cursor: default; }
574 608
575 609 .tz-label { display: block; opacity: 0.65; font-size: 0.8em; }
610
611 /* Game view: exactly one viewport tall (dvh = visible area, also with the
612 mobile URL bar). Header, HUD, board and timeline are stacked in a flex
613 column; the board takes the remaining space (container query) so the
614 page never needs to scroll and the header cannot overlap the HUD. */
615 html.in-game, html.in-game body {
616 height: 100%;
617 height: 100dvh;
618 min-height: 0;
619 overflow: hidden;
620 overscroll-behavior: none;
621 }
622 html.in-game body { padding-bottom: 0; box-sizing: border-box; }
623 html.in-game #app {
624 box-sizing: border-box;
625 height: 100%;
626 display: flex;
627 flex-direction: column;
628 padding: 4px 12px calc(var(--safe-b) + 4px);
629 overflow: hidden;
630 }
631 html.in-game #top-bar {
632 position: static;
633 flex: 0 0 auto;
634 background: none;
635 padding: 0 0 4px;
636 }
637 html.in-game #top-bar .countdown { margin: 0; }
638 html.in-game #top-bar .cd-hms { font-size: 1.5rem; }
639 html.in-game #game {
640 flex: 1 1 auto;
641 min-height: 0;
642 display: flex;
643 flex-direction: column;
644 overflow-y: auto;
645 overflow-x: hidden;
646 }
647 html.in-game #game-hud { flex: 0 0 auto; margin-bottom: 4px; }
648 html.in-game #game-hud button { min-height: 40px; }
649 html.in-game #board-wrap {
650 flex: 1 1 0;
651 min-height: 120px;
652 margin: 4px 0;
653 container-type: size;
654 align-items: center;
655 }
656 html.in-game #board { width: min(100cqw, 100cqh, 560px); }
657 html.in-game #jury-panel { flex: 0 0 auto; margin: 4px 0; }
658 html.in-game #timeline {
659 position: static;
660 flex: 0 0 auto;
661 padding: 4px 0;
662 min-height: 48px;
663 }
664 html.in-game #tl-caption { flex: 0 0 auto; margin: 2px 0 0; }
665 /* In the game the language button sits in the empty top-right corner
666 (beside the header) instead of over the timeline; its list opens down. */
667 html.in-game .lang-picker {
668 top: calc(var(--safe-t) + 4px);
669 bottom: auto;
670 right: calc(var(--safe-r) + 4px);
671 flex-direction: column;
672 }
673 html.in-game .lang-current { min-height: 34px; min-width: 44px; padding: 4px 5px; }
674 html.in-game .lang-current img { width: 30px; height: 20px; }
@@ -287,13 +287,47 @@ button.cell {
287.piece-fixed {
287.piece-fixed {
288 width: var(--sz, 40px) !important;
288 width: var(--sz, 40px) !important;
289 height: var(--sz, 40px) !important;
289 height: var(--sz, 40px) !important;
290 max-width: none;
291 max-height: none;
290 border-width: 2px;
292 border-width: 2px;
291 font-size: calc(var(--sz, 40px) * 0.38);
293 font-size: calc(var(--sz, 40px) * 0.38);
292}
294}
295/* Token: always a visible circle in the player's colour with initials;
296 a profile picture (if it loads) is layered on top. See src/avatar.js. */
297.piece-token {
298 position: relative;
299 display: inline-flex;
300 align-items: center;
301 justify-content: center;
302 overflow: hidden;
303 background-color: var(--c, #888);
304 box-sizing: border-box;
305 line-height: 1;
306 user-select: none;
307}
308.cell { container-type: inline-size; }
293.piece-initials {
309.piece-initials {
294 display: flex; align-items: center; justify-content: center;
310 display: block;
295 font-weight: 700; font-size: 0.7em; color: #fff;
311 font-weight: 800;
312 font-size: 0.8em;
313 font-size: 30cqw;
314 letter-spacing: 0.02em;
315 color: inherit;
316 text-shadow: 0 1px 2px #0006;
317 pointer-events: none;
296}
318}
319.piece-fixed .piece-initials { font-size: calc(var(--sz, 40px) * 0.38); }
320.piece-img {
321 position: absolute;
322 inset: 0;
323 width: 100%;
324 height: 100%;
325 object-fit: cover;
326 border-radius: 50%;
327 pointer-events: none;
328}
329.piece.has-img .piece-initials { visibility: hidden; }
330#menu-avatar { display: inline-flex; background: none; }
297
331
298/* Timeline */
332/* Timeline */
299#timeline {
333#timeline {
@@ -573,3 +607,68 @@ button.cell {
573#cf-clock svg.readonly { cursor: default; }
607#cf-clock svg.readonly { cursor: default; }
574
608
575.tz-label { display: block; opacity: 0.65; font-size: 0.8em; }
609.tz-label { display: block; opacity: 0.65; font-size: 0.8em; }
610
611/* Game view: exactly one viewport tall (dvh = visible area, also with the
612 mobile URL bar). Header, HUD, board and timeline are stacked in a flex
613 column; the board takes the remaining space (container query) so the
614 page never needs to scroll and the header cannot overlap the HUD. */
615html.in-game, html.in-game body {
616 height: 100%;
617 height: 100dvh;
618 min-height: 0;
619 overflow: hidden;
620 overscroll-behavior: none;
621}
622html.in-game body { padding-bottom: 0; box-sizing: border-box; }
623html.in-game #app {
624 box-sizing: border-box;
625 height: 100%;
626 display: flex;
627 flex-direction: column;
628 padding: 4px 12px calc(var(--safe-b) + 4px);
629 overflow: hidden;
630}
631html.in-game #top-bar {
632 position: static;
633 flex: 0 0 auto;
634 background: none;
635 padding: 0 0 4px;
636}
637html.in-game #top-bar .countdown { margin: 0; }
638html.in-game #top-bar .cd-hms { font-size: 1.5rem; }
639html.in-game #game {
640 flex: 1 1 auto;
641 min-height: 0;
642 display: flex;
643 flex-direction: column;
644 overflow-y: auto;
645 overflow-x: hidden;
646}
647html.in-game #game-hud { flex: 0 0 auto; margin-bottom: 4px; }
648html.in-game #game-hud button { min-height: 40px; }
649html.in-game #board-wrap {
650 flex: 1 1 0;
651 min-height: 120px;
652 margin: 4px 0;
653 container-type: size;
654 align-items: center;
655}
656html.in-game #board { width: min(100cqw, 100cqh, 560px); }
657html.in-game #jury-panel { flex: 0 0 auto; margin: 4px 0; }
658html.in-game #timeline {
659 position: static;
660 flex: 0 0 auto;
661 padding: 4px 0;
662 min-height: 48px;
663}
664html.in-game #tl-caption { flex: 0 0 auto; margin: 2px 0 0; }
665/* In the game the language button sits in the empty top-right corner
666 (beside the header) instead of over the timeline; its list opens down. */
667html.in-game .lang-picker {
668 top: calc(var(--safe-t) + 4px);
669 bottom: auto;
670 right: calc(var(--safe-r) + 4px);
671 flex-direction: column;
672}
673html.in-game .lang-current { min-height: 34px; min-width: 44px; padding: 4px 5px; }
674html.in-game .lang-current img { width: 30px; height: 20px; }
docs/ASSUMPTIONS.md +30 −2
@@ -114,8 +114,24 @@ regelmotor (`server/lib/Engine.php`) en de tests vastgelegd.
114 114 spelers mogen nog chatten.
115 115 - Sessie duurt 30 dagen en wordt bij activiteit verlengd. Avatar komt uit
116 116 het profiel van auth.timfalken.com (`avatar_url` / `avatar` / `picture`)
117 of, als fallback, `https://auth.timfalken.com/avatar/{id}`. Bij een
118 ontbrekende afbeelding toont de client initialen.
117 of, als fallback, `https://auth.timfalken.com/avatar/{id}`. Die
118 fallback-URL bestaat niet voor iemand zonder profielplaatje (404).
119 - **Speelstuk zonder (werkend) profielplaatje** (t1179): elk speelstuk is
120 altijd een zichtbare cirkel in de unieke spelerskleur (vulling én rand)
121 met de initialen (eerste letters van het eerste en laatste naamdeel,
122 gescheiden door spatie, `_`, `-` of `.`; bij één woord de eerste twee
123 letters). Een profielplaatje wordt er alleen bovenop gelegd. Laadt het
124 niet (lege URL, 404, geblokkeerd, 0×0), dan verdwijnt alleen het
125 plaatje en blijven de initialen staan. Mislukte URL's worden per
126 paginabezoek onthouden, zodat de 3-secondenpoll ze niet steeds opnieuw
127 probeert (geen flikkering). Zelfde stuk in lobbylijst, jurylijst en
128 menu. Tekstkleur (zwart/wit) volgt de helderheid van de spelerskleur.
129 - Oorzaak van de onzichtbare tegenstander: het bord haalde het `<img>`
130 uit een wrapper en zette het in het vakje. Bij een laadfout werd het
131 `<img>` verwijderd en de initialen-fallback in de (losgekoppelde)
132 wrapper gezet, dus nergens op het scherm. Bij elke tik/poll werd het
133 bord opnieuw opgebouwd met een nieuw `<img>`, dat even zichtbaar was
134 tot de 404 binnenkwam — vandaar “alleen kort zichtbaar na tikken”.
119 135 - Taalcodes volgen Meteors: intern `zh` (HTML `zh-Hans`), vlaggen `gb`,
120 136 `jp`, `cn`, `kr`. De keuze staat in `localStorage` (`allianties-locale`)
121 137 en in het profiel.
@@ -306,3 +322,15 @@ of, als het spel al loopt en je lid bent, het lopende spel.
306 322 HTTP 403 (`not_host`); niet-hosts zien het formulier alleen-lezen met
307 323 de melding “Alleen de host kan de spelregels aanpassen.”
308 324
325 ## Spelscherm op mobiel (t1180)
326
327 - Het spelscherm is precies één schermhoogte (`100dvh`, dus de zichtbare
328 hoogte, ook met de adresbalk van mobiele browsers). Kop, statusregel,
329 bord en tijdlijn staan in één kolom; het bord neemt de resterende ruimte
330 (container query, vierkant, maximaal 560 px). De pagina scrolt niet;
331 alleen als er écht meer is (bijv. het jurypaneel) scrolt het spelscherm
332 binnen zichzelf.
333 - De kop is in het spel niet meer `sticky`, zodat hij nooit over de
334 statusregel valt. De taalknop staat in het spel rechtsboven naast de kop
335 (de lijst klapt naar beneden open) in plaats van over de tijdlijn.
336
@@ -114,8 +114,24 @@ regelmotor (`server/lib/Engine.php`) en de tests vastgelegd.
114 spelers mogen nog chatten.
114 spelers mogen nog chatten.
115- Sessie duurt 30 dagen en wordt bij activiteit verlengd. Avatar komt uit
115- Sessie duurt 30 dagen en wordt bij activiteit verlengd. Avatar komt uit
116 het profiel van auth.timfalken.com (`avatar_url` / `avatar` / `picture`)
116 het profiel van auth.timfalken.com (`avatar_url` / `avatar` / `picture`)
117 of, als fallback, `https://auth.timfalken.com/avatar/{id}`. Bij een
117 of, als fallback, `https://auth.timfalken.com/avatar/{id}`. Die
118 ontbrekende afbeelding toont de client initialen.
118 fallback-URL bestaat niet voor iemand zonder profielplaatje (404).
119- **Speelstuk zonder (werkend) profielplaatje** (t1179): elk speelstuk is
120 altijd een zichtbare cirkel in de unieke spelerskleur (vulling én rand)
121 met de initialen (eerste letters van het eerste en laatste naamdeel,
122 gescheiden door spatie, `_`, `-` of `.`; bij één woord de eerste twee
123 letters). Een profielplaatje wordt er alleen bovenop gelegd. Laadt het
124 niet (lege URL, 404, geblokkeerd, 0×0), dan verdwijnt alleen het
125 plaatje en blijven de initialen staan. Mislukte URL's worden per
126 paginabezoek onthouden, zodat de 3-secondenpoll ze niet steeds opnieuw
127 probeert (geen flikkering). Zelfde stuk in lobbylijst, jurylijst en
128 menu. Tekstkleur (zwart/wit) volgt de helderheid van de spelerskleur.
129- Oorzaak van de onzichtbare tegenstander: het bord haalde het `<img>`
130 uit een wrapper en zette het in het vakje. Bij een laadfout werd het
131 `<img>` verwijderd en de initialen-fallback in de (losgekoppelde)
132 wrapper gezet, dus nergens op het scherm. Bij elke tik/poll werd het
133 bord opnieuw opgebouwd met een nieuw `<img>`, dat even zichtbaar was
134 tot de 404 binnenkwam — vandaar “alleen kort zichtbaar na tikken”.
119- Taalcodes volgen Meteors: intern `zh` (HTML `zh-Hans`), vlaggen `gb`,
135- Taalcodes volgen Meteors: intern `zh` (HTML `zh-Hans`), vlaggen `gb`,
120 `jp`, `cn`, `kr`. De keuze staat in `localStorage` (`allianties-locale`)
136 `jp`, `cn`, `kr`. De keuze staat in `localStorage` (`allianties-locale`)
121 en in het profiel.
137 en in het profiel.
@@ -306,3 +322,15 @@ of, als het spel al loopt en je lid bent, het lopende spel.
306 HTTP 403 (`not_host`); niet-hosts zien het formulier alleen-lezen met
322 HTTP 403 (`not_host`); niet-hosts zien het formulier alleen-lezen met
307 de melding “Alleen de host kan de spelregels aanpassen.”
323 de melding “Alleen de host kan de spelregels aanpassen.”
308
324
325## Spelscherm op mobiel (t1180)
326
327- Het spelscherm is precies één schermhoogte (`100dvh`, dus de zichtbare
328 hoogte, ook met de adresbalk van mobiele browsers). Kop, statusregel,
329 bord en tijdlijn staan in één kolom; het bord neemt de resterende ruimte
330 (container query, vierkant, maximaal 560 px). De pagina scrolt niet;
331 alleen als er écht meer is (bijv. het jurypaneel) scrolt het spelscherm
332 binnen zichzelf.
333- De kop is in het spel niet meer `sticky`, zodat hij nooit over de
334 statusregel valt. De taalknop staat in het spel rechtsboven naast de kop
335 (de lijst klapt naar beneden open) in plaats van over de tijdlijn.
336
server/auth.php +10 −1
@@ -14,7 +14,16 @@ try {
14 14 throw new RuntimeException('Onbekende testgebruiker.');
15 15 }
16 16 $who = 'test_user_' . $n;
17 loginUser('local:' . $who, $who, 'images/avatars/' . $who . '.svg');
17 // Local only: ?avatar=none (no picture) / ?avatar=broken (URL that 404s,
18 // like the auth server's /avatar/<id> for users without a picture).
19 $avatar = 'images/avatars/' . $who . '.svg';
20 $mode = (string) ($_GET['avatar'] ?? '');
21 if ($mode === 'none') {
22 $avatar = null;
23 } elseif ($mode === 'broken') {
24 $avatar = 'images/avatars/missing-' . $who . '.png';
25 }
26 loginUser('local:' . $who, $who, $avatar);
18 27 $dest = $_SESSION['after_login'] ?? (is_string($next) ? $next : 'index.html');
19 28 unset($_SESSION['after_login']);
20 29 header('Location: ' . $dest);
@@ -14,7 +14,16 @@ try {
14 throw new RuntimeException('Onbekende testgebruiker.');
14 throw new RuntimeException('Onbekende testgebruiker.');
15 }
15 }
16 $who = 'test_user_' . $n;
16 $who = 'test_user_' . $n;
17 loginUser('local:' . $who, $who, 'images/avatars/' . $who . '.svg');
17 // Local only: ?avatar=none (no picture) / ?avatar=broken (URL that 404s,
18 // like the auth server's /avatar/<id> for users without a picture).
19 $avatar = 'images/avatars/' . $who . '.svg';
20 $mode = (string) ($_GET['avatar'] ?? '');
21 if ($mode === 'none') {
22 $avatar = null;
23 } elseif ($mode === 'broken') {
24 $avatar = 'images/avatars/missing-' . $who . '.png';
25 }
26 loginUser('local:' . $who, $who, $avatar);
18 $dest = $_SESSION['after_login'] ?? (is_string($next) ? $next : 'index.html');
27 $dest = $_SESSION['after_login'] ?? (is_string($next) ? $next : 'index.html');
19 unset($_SESSION['after_login']);
28 unset($_SESSION['after_login']);
20 header('Location: ' . $dest);
29 header('Location: ' . $dest);
src/avatar.js added +122 −0
@@ -0,0 +1,122 @@
1 'use strict';
2
3 /**
4 * Player tokens / avatars.
5 *
6 * A token is ALWAYS a visible circle in the player's colour with their
7 * initials. A profile picture, when present and loadable, is layered on
8 * top. If the picture fails to load (404, empty URL, blocked), the <img>
9 * is removed and the initials circle underneath stays — the token itself
10 * is never replaced or detached, so it survives image errors and board
11 * re-renders. Failed URLs are remembered so later renders (every 3 s
12 * poll) skip them instead of flashing a broken image.
13 */
14 var Avatar = {
15 failed: {},
16 loaded: {},
17
18 initials: function (name)
19 {
20 if (!name) { return '?'; }
21 var parts = String(name).trim().split(/[\s._-]+/).filter(function (s) { return s.length > 0; });
22 if (!parts.length) { return '?'; }
23 var first = Array.from(parts[0]);
24 var s = first[0];
25 if (parts.length > 1) { s += Array.from(parts[parts.length - 1])[0]; }
26 else if (first.length > 1 && /[a-z]/i.test(first[1])) { s += first[1]; }
27 return s.toUpperCase();
28 },
29
30 /** Usable picture URL, or null (empty, whitespace, javascript:, already failed). */
31 usableUrl: function (url)
32 {
33 if (typeof url !== 'string') { return null; }
34 url = url.trim();
35 if (!url) { return null; }
36 if (!/^(https?:\/\/|data:image\/|\/|\.{0,2}\/?[\w-])/i.test(url)) { return null; }
37 if (/^(javascript|vbscript):/i.test(url)) { return null; }
38 if (Avatar.failed[url]) { return null; }
39 return url;
40 },
41
42 /** Deterministic fallback colour for a player without one (e.g. the menu). */
43 colorFor: function (id)
44 {
45 var palette = ['#e85d5d', '#4fa3e8', '#5dd39e', '#e8c547', '#b07ce8', '#e8873a', '#3ad1d1', '#e86fb8'];
46 var h = 0;
47 String(id || '').split('').forEach(function (c) { h = (h * 31 + c.charCodeAt(0)) >>> 0; });
48 return palette[h % palette.length];
49 },
50
51 /** Black or white text, whichever reads better on the given #rgb/#rrggbb colour. */
52 textColor: function (hex)
53 {
54 var m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(String(hex || ''));
55 if (!m) { return '#fff'; }
56 var v = m[1];
57 if (v.length === 3) { v = v[0] + v[0] + v[1] + v[1] + v[2] + v[2]; }
58 var r = parseInt(v.slice(0, 2), 16), g = parseInt(v.slice(2, 4), 16), b = parseInt(v.slice(4, 6), 16);
59 var lum = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
60 return lum > 0.6 ? '#111' : '#fff';
61 },
62
63 /**
64 * Build a token element (span.piece). opts: { size, fixed, doc }.
65 * The element itself is the token; append it anywhere.
66 */
67 piece: function (player, opts)
68 {
69 opts = opts || {};
70 var doc = opts.doc || document;
71 var color = player.color || Avatar.colorFor(player.id || player.name);
72 var el = doc.createElement('span');
73 el.className = 'piece piece-token' + (player.alive === false ? ' dead' : '');
74 el.setAttribute('role', 'img');
75 el.setAttribute('aria-label', player.name || '?');
76 el.title = player.name || '';
77 el.style.setProperty('--c', color);
78 el.style.borderColor = color;
79 el.style.backgroundColor = color;
80 el.style.color = Avatar.textColor(color);
81 if (opts.fixed)
82 {
83 var size = opts.size || 40;
84 el.classList.add('piece-fixed');
85 el.style.setProperty('--sz', size + 'px');
86 el.style.width = size + 'px';
87 el.style.height = size + 'px';
88 }
89 var txt = doc.createElement('span');
90 txt.className = 'piece-initials';
91 txt.textContent = Avatar.initials(player.name);
92 el.appendChild(txt);
93 var url = Avatar.usableUrl(player.avatar);
94 if (url)
95 {
96 var img = doc.createElement('img');
97 img.alt = '';
98 img.className = 'piece-img';
99 img.decoding = 'async';
100 img.referrerPolicy = 'no-referrer';
101 img.addEventListener('error', function ()
102 {
103 Avatar.failed[url] = true;
104 el.classList.remove('has-img');
105 if (img.parentNode) { img.parentNode.removeChild(img); }
106 });
107 img.addEventListener('load', function ()
108 {
109 if (!img.naturalWidth) { Avatar.failed[url] = true; if (img.parentNode) { img.parentNode.removeChild(img); } return; }
110 Avatar.loaded[url] = true;
111 el.classList.add('has-img');
112 });
113 if (Avatar.loaded[url]) { el.classList.add('has-img'); }
114 img.src = url;
115 el.appendChild(img);
116 }
117 return el;
118 }
119 };
120
121 if (typeof module !== 'undefined' && module.exports)
122 { module.exports = Avatar; }
@@ -0,0 +1,122 @@
1'use strict';
2
3/**
4 * Player tokens / avatars.
5 *
6 * A token is ALWAYS a visible circle in the player's colour with their
7 * initials. A profile picture, when present and loadable, is layered on
8 * top. If the picture fails to load (404, empty URL, blocked), the <img>
9 * is removed and the initials circle underneath stays — the token itself
10 * is never replaced or detached, so it survives image errors and board
11 * re-renders. Failed URLs are remembered so later renders (every 3 s
12 * poll) skip them instead of flashing a broken image.
13 */
14var Avatar = {
15 failed: {},
16 loaded: {},
17
18 initials: function (name)
19 {
20 if (!name) { return '?'; }
21 var parts = String(name).trim().split(/[\s._-]+/).filter(function (s) { return s.length > 0; });
22 if (!parts.length) { return '?'; }
23 var first = Array.from(parts[0]);
24 var s = first[0];
25 if (parts.length > 1) { s += Array.from(parts[parts.length - 1])[0]; }
26 else if (first.length > 1 && /[a-z]/i.test(first[1])) { s += first[1]; }
27 return s.toUpperCase();
28 },
29
30 /** Usable picture URL, or null (empty, whitespace, javascript:, already failed). */
31 usableUrl: function (url)
32 {
33 if (typeof url !== 'string') { return null; }
34 url = url.trim();
35 if (!url) { return null; }
36 if (!/^(https?:\/\/|data:image\/|\/|\.{0,2}\/?[\w-])/i.test(url)) { return null; }
37 if (/^(javascript|vbscript):/i.test(url)) { return null; }
38 if (Avatar.failed[url]) { return null; }
39 return url;
40 },
41
42 /** Deterministic fallback colour for a player without one (e.g. the menu). */
43 colorFor: function (id)
44 {
45 var palette = ['#e85d5d', '#4fa3e8', '#5dd39e', '#e8c547', '#b07ce8', '#e8873a', '#3ad1d1', '#e86fb8'];
46 var h = 0;
47 String(id || '').split('').forEach(function (c) { h = (h * 31 + c.charCodeAt(0)) >>> 0; });
48 return palette[h % palette.length];
49 },
50
51 /** Black or white text, whichever reads better on the given #rgb/#rrggbb colour. */
52 textColor: function (hex)
53 {
54 var m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(String(hex || ''));
55 if (!m) { return '#fff'; }
56 var v = m[1];
57 if (v.length === 3) { v = v[0] + v[0] + v[1] + v[1] + v[2] + v[2]; }
58 var r = parseInt(v.slice(0, 2), 16), g = parseInt(v.slice(2, 4), 16), b = parseInt(v.slice(4, 6), 16);
59 var lum = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
60 return lum > 0.6 ? '#111' : '#fff';
61 },
62
63 /**
64 * Build a token element (span.piece). opts: { size, fixed, doc }.
65 * The element itself is the token; append it anywhere.
66 */
67 piece: function (player, opts)
68 {
69 opts = opts || {};
70 var doc = opts.doc || document;
71 var color = player.color || Avatar.colorFor(player.id || player.name);
72 var el = doc.createElement('span');
73 el.className = 'piece piece-token' + (player.alive === false ? ' dead' : '');
74 el.setAttribute('role', 'img');
75 el.setAttribute('aria-label', player.name || '?');
76 el.title = player.name || '';
77 el.style.setProperty('--c', color);
78 el.style.borderColor = color;
79 el.style.backgroundColor = color;
80 el.style.color = Avatar.textColor(color);
81 if (opts.fixed)
82 {
83 var size = opts.size || 40;
84 el.classList.add('piece-fixed');
85 el.style.setProperty('--sz', size + 'px');
86 el.style.width = size + 'px';
87 el.style.height = size + 'px';
88 }
89 var txt = doc.createElement('span');
90 txt.className = 'piece-initials';
91 txt.textContent = Avatar.initials(player.name);
92 el.appendChild(txt);
93 var url = Avatar.usableUrl(player.avatar);
94 if (url)
95 {
96 var img = doc.createElement('img');
97 img.alt = '';
98 img.className = 'piece-img';
99 img.decoding = 'async';
100 img.referrerPolicy = 'no-referrer';
101 img.addEventListener('error', function ()
102 {
103 Avatar.failed[url] = true;
104 el.classList.remove('has-img');
105 if (img.parentNode) { img.parentNode.removeChild(img); }
106 });
107 img.addEventListener('load', function ()
108 {
109 if (!img.naturalWidth) { Avatar.failed[url] = true; if (img.parentNode) { img.parentNode.removeChild(img); } return; }
110 Avatar.loaded[url] = true;
111 el.classList.add('has-img');
112 });
113 if (Avatar.loaded[url]) { el.classList.add('has-img'); }
114 img.src = url;
115 el.appendChild(img);
116 }
117 return el;
118 }
119};
120
121if (typeof module !== 'undefined' && module.exports)
122{ module.exports = Avatar; }
src/build.sh +1 −0
@@ -15,6 +15,7 @@ FILES=(
15 15 "$SRC_DIR/i18n.js"
16 16 "$SRC_DIR/rules.js"
17 17 "$SRC_DIR/api.js"
18 "$SRC_DIR/avatar.js"
18 19 "$SRC_DIR/main.js"
19 20 )
20 21
@@ -15,6 +15,7 @@ FILES=(
15 "$SRC_DIR/i18n.js"
15 "$SRC_DIR/i18n.js"
16 "$SRC_DIR/rules.js"
16 "$SRC_DIR/rules.js"
17 "$SRC_DIR/api.js"
17 "$SRC_DIR/api.js"
18 "$SRC_DIR/avatar.js"
18 "$SRC_DIR/main.js"
19 "$SRC_DIR/main.js"
19)
20)
20
21
src/main.js +11 −58
@@ -26,6 +26,7 @@ function showScreen(name)
26 26 });
27 27 App.screen = name;
28 28 $('top-bar').hidden = name !== 'game';
29 document.documentElement.classList.toggle('in-game', name === 'game');
29 30 if (name !== 'game')
30 31 { App.stopReplay(); }
31 32 }
@@ -49,69 +50,22 @@ function showError(id, err)
49 50
50 51 function initials(name)
51 52 {
52 if (!name) { return '?'; }
53 var parts = String(name).trim().split(/\s+/);
54 var s = parts[0].charAt(0);
55 if (parts.length > 1)
56 { s += parts[parts.length - 1].charAt(0); }
57 return s.toUpperCase();
53 return Avatar.initials(name);
58 54 }
59 55
56 /** Token for lists (lobby players, jury). See src/avatar.js. */
60 57 function avatarNode(player, size, fixed)
61 58 {
62 59 size = size || 40;
63 60 var wrap = document.createElement('span');
64 wrap.className = 'avatar-wrap';
65 wrap.style.setProperty('--c', player.color || '#fff');
61 wrap.className = 'avatar-wrap' + (fixed ? ' avatar-wrap-fixed' : '');
66 62 wrap.style.setProperty('--sz', size + 'px');
67 63 if (fixed)
68 64 {
69 wrap.classList.add('avatar-wrap-fixed');
70 65 wrap.style.width = size + 'px';
71 66 wrap.style.height = size + 'px';
72 67 }
73 function stylePiece(el)
74 {
75 el.className = (el.className ? el.className + ' ' : '') + 'piece' + (player.alive === false ? ' dead' : '');
76 if (fixed)
77 {
78 el.classList.add('piece-fixed');
79 el.style.width = size + 'px';
80 el.style.height = size + 'px';
81 el.style.borderColor = player.color || '#fff';
82 }
83 else
84 {
85 el.style.borderColor = player.color || '#fff';
86 }
87 }
88 if (player.avatar)
89 {
90 var img = document.createElement('img');
91 img.alt = player.name || '';
92 img.width = size;
93 img.height = size;
94 stylePiece(img);
95 img.src = player.avatar;
96 img.addEventListener('error', function ()
97 {
98 img.remove();
99 var fb = document.createElement('span');
100 fb.className = 'piece-initials';
101 stylePiece(fb);
102 fb.textContent = initials(player.name);
103 wrap.appendChild(fb);
104 });
105 wrap.appendChild(img);
106 }
107 else
108 {
109 var fb = document.createElement('span');
110 fb.className = 'piece-initials';
111 stylePiece(fb);
112 fb.textContent = initials(player.name);
113 wrap.appendChild(fb);
114 }
68 wrap.appendChild(Avatar.piece(player, { size: size, fixed: fixed }));
115 69 return wrap;
116 70 }
117 71
@@ -404,8 +358,8 @@ App.renderMenu = function (data)
404 358 {
405 359 $('menu-name').textContent = me.name;
406 360 var av = $('menu-avatar');
407 if (me.avatar) { av.src = me.avatar; av.hidden = false; }
408 else { av.hidden = true; }
361 av.innerHTML = '';
362 av.appendChild(Avatar.piece(me, { size: 32, fixed: true }));
409 363 }
410 364 App.games = data.games || App.games || [];
411 365 var list = $('games-list');
@@ -1017,9 +971,8 @@ App.renderBoard = function (g)
1017 971 });
1018 972 if (occupant)
1019 973 {
1020 var node = avatarNode(occupant, 48);
1021 var pic = node.firstChild;
1022 if (pic) { cell.appendChild(pic); }
974 cell.appendChild(Avatar.piece(occupant, { size: 48 }));
975 cell.classList.add('occupied');
1023 976 if (App.selected === occupant.id) { cell.classList.add('selected'); }
1024 977 if (!App.replay && legal.shoot && legal.shoot.indexOf(occupant.id) >= 0)
1025 978 { cell.classList.add('in-range'); }
@@ -1811,7 +1764,7 @@ App.clearBoardFx = function ()
1811 1764 {
1812 1765 wrap.querySelectorAll('.fx-float').forEach(function (n) { n.remove(); });
1813 1766 }
1814 document.querySelectorAll('#board .piece.moving, #board .piece.range-pulse, #board .piece-initials.moving, #board .piece-initials.range-pulse').forEach(function (el)
1767 document.querySelectorAll('#board .piece.moving, #board .piece.range-pulse').forEach(function (el)
1815 1768 {
1816 1769 el.classList.remove('moving', 'range-pulse');
1817 1770 el.style.transform = '';
@@ -1843,7 +1796,7 @@ App.playerCell = function (view, id)
1843 1796 App.pieceInCell = function (x, y)
1844 1797 {
1845 1798 var cell = document.querySelector('#board .cell[data-x="' + x + '"][data-y="' + y + '"]');
1846 return cell ? cell.querySelector('.piece, .piece-initials') : null;
1799 return cell ? cell.querySelector('.piece') : null;
1847 1800 };
1848 1801
1849 1802 App.playBoardFx = function (view, ev, prev, animate)
@@ -26,6 +26,7 @@ function showScreen(name)
26 });
26 });
27 App.screen = name;
27 App.screen = name;
28 $('top-bar').hidden = name !== 'game';
28 $('top-bar').hidden = name !== 'game';
29 document.documentElement.classList.toggle('in-game', name === 'game');
29 if (name !== 'game')
30 if (name !== 'game')
30 { App.stopReplay(); }
31 { App.stopReplay(); }
31}
32}
@@ -49,69 +50,22 @@ function showError(id, err)
49
50
50function initials(name)
51function initials(name)
51{
52{
52 if (!name) { return '?'; }
53 return Avatar.initials(name);
53 var parts = String(name).trim().split(/\s+/);
54 var s = parts[0].charAt(0);
55 if (parts.length > 1)
56 { s += parts[parts.length - 1].charAt(0); }
57 return s.toUpperCase();
58}
54}
59
55
56/** Token for lists (lobby players, jury). See src/avatar.js. */
60function avatarNode(player, size, fixed)
57function avatarNode(player, size, fixed)
61{
58{
62 size = size || 40;
59 size = size || 40;
63 var wrap = document.createElement('span');
60 var wrap = document.createElement('span');
64 wrap.className = 'avatar-wrap';
61 wrap.className = 'avatar-wrap' + (fixed ? ' avatar-wrap-fixed' : '');
65 wrap.style.setProperty('--c', player.color || '#fff');
66 wrap.style.setProperty('--sz', size + 'px');
62 wrap.style.setProperty('--sz', size + 'px');
67 if (fixed)
63 if (fixed)
68 {
64 {
69 wrap.classList.add('avatar-wrap-fixed');
70 wrap.style.width = size + 'px';
65 wrap.style.width = size + 'px';
71 wrap.style.height = size + 'px';
66 wrap.style.height = size + 'px';
72 }
67 }
73 function stylePiece(el)
68 wrap.appendChild(Avatar.piece(player, { size: size, fixed: fixed }));
74 {
75 el.className = (el.className ? el.className + ' ' : '') + 'piece' + (player.alive === false ? ' dead' : '');
76 if (fixed)
77 {
78 el.classList.add('piece-fixed');
79 el.style.width = size + 'px';
80 el.style.height = size + 'px';
81 el.style.borderColor = player.color || '#fff';
82 }
83 else
84 {
85 el.style.borderColor = player.color || '#fff';
86 }
87 }
88 if (player.avatar)
89 {
90 var img = document.createElement('img');
91 img.alt = player.name || '';
92 img.width = size;
93 img.height = size;
94 stylePiece(img);
95 img.src = player.avatar;
96 img.addEventListener('error', function ()
97 {
98 img.remove();
99 var fb = document.createElement('span');
100 fb.className = 'piece-initials';
101 stylePiece(fb);
102 fb.textContent = initials(player.name);
103 wrap.appendChild(fb);
104 });
105 wrap.appendChild(img);
106 }
107 else
108 {
109 var fb = document.createElement('span');
110 fb.className = 'piece-initials';
111 stylePiece(fb);
112 fb.textContent = initials(player.name);
113 wrap.appendChild(fb);
114 }
115 return wrap;
69 return wrap;
116}
70}
117
71
@@ -404,8 +358,8 @@ App.renderMenu = function (data)
404 {
358 {
405 $('menu-name').textContent = me.name;
359 $('menu-name').textContent = me.name;
406 var av = $('menu-avatar');
360 var av = $('menu-avatar');
407 if (me.avatar) { av.src = me.avatar; av.hidden = false; }
361 av.innerHTML = '';
408 else { av.hidden = true; }
362 av.appendChild(Avatar.piece(me, { size: 32, fixed: true }));
409 }
363 }
410 App.games = data.games || App.games || [];
364 App.games = data.games || App.games || [];
411 var list = $('games-list');
365 var list = $('games-list');
@@ -1017,9 +971,8 @@ App.renderBoard = function (g)
1017 });
971 });
1018 if (occupant)
972 if (occupant)
1019 {
973 {
1020 var node = avatarNode(occupant, 48);
974 cell.appendChild(Avatar.piece(occupant, { size: 48 }));
1021 var pic = node.firstChild;
975 cell.classList.add('occupied');
1022 if (pic) { cell.appendChild(pic); }
1023 if (App.selected === occupant.id) { cell.classList.add('selected'); }
976 if (App.selected === occupant.id) { cell.classList.add('selected'); }
1024 if (!App.replay && legal.shoot && legal.shoot.indexOf(occupant.id) >= 0)
977 if (!App.replay && legal.shoot && legal.shoot.indexOf(occupant.id) >= 0)
1025 { cell.classList.add('in-range'); }
978 { cell.classList.add('in-range'); }
@@ -1811,7 +1764,7 @@ App.clearBoardFx = function ()
1811 {
1764 {
1812 wrap.querySelectorAll('.fx-float').forEach(function (n) { n.remove(); });
1765 wrap.querySelectorAll('.fx-float').forEach(function (n) { n.remove(); });
1813 }
1766 }
1814 document.querySelectorAll('#board .piece.moving, #board .piece.range-pulse, #board .piece-initials.moving, #board .piece-initials.range-pulse').forEach(function (el)
1767 document.querySelectorAll('#board .piece.moving, #board .piece.range-pulse').forEach(function (el)
1815 {
1768 {
1816 el.classList.remove('moving', 'range-pulse');
1769 el.classList.remove('moving', 'range-pulse');
1817 el.style.transform = '';
1770 el.style.transform = '';
@@ -1843,7 +1796,7 @@ App.playerCell = function (view, id)
1843App.pieceInCell = function (x, y)
1796App.pieceInCell = function (x, y)
1844{
1797{
1845 var cell = document.querySelector('#board .cell[data-x="' + x + '"][data-y="' + y + '"]');
1798 var cell = document.querySelector('#board .cell[data-x="' + x + '"][data-y="' + y + '"]');
1846 return cell ? cell.querySelector('.piece, .piece-initials') : null;
1799 return cell ? cell.querySelector('.piece') : null;
1847};
1800};
1848
1801
1849App.playBoardFx = function (view, ev, prev, animate)
1802App.playBoardFx = function (view, ev, prev, animate)
test/avatar-layout-playwright.py added +179 −0
@@ -0,0 +1,179 @@
1 #!/usr/bin/env python3
2 """t1179/t1180 real-browser checks.
3
4 - Players without a profile picture (null avatar) and with a picture URL that
5 404s are visible on the board as a coloured circle with initials, stay
6 visible across several 3 s polls and after taps; also in the lobby list
7 and the menu.
8 - The game view fits the viewport on mobile (412x915, 390x844, 460x1000)
9 and desktop: no page scroll, the header does not overlap the HUD, the
10 timeline is fully on screen and not covered by the language button.
11 Usage: python3 test/avatar-layout-playwright.py [BASE]
12 """
13 import sys
14 from pathlib import Path
15 from urllib.parse import quote
16
17 from playwright.sync_api import sync_playwright
18
19 BASE = sys.argv[1] if len(sys.argv) > 1 else 'http://127.0.0.1:8080'
20 OUT = Path('/workspace/allianties-shots')
21 OUT.mkdir(parents=True, exist_ok=True)
22 FAILS = []
23
24
25 def check(cond, msg):
26 print((' ok ' if cond else ' FAIL ') + msg)
27 if not cond:
28 FAILS.append(msg)
29
30
31 def shot(page, name):
32 page.screenshot(path=str(OUT / ('t1179-' + name + '.png')), full_page=False)
33 print(' shot', OUT / ('t1179-' + name + '.png'))
34
35
36 TOKENS_JS = """() => Array.from(document.querySelectorAll('#board .cell .piece')).map(el => {
37 const r = el.getBoundingClientRect(); const cs = getComputedStyle(el);
38 const ini = el.querySelector('.piece-initials');
39 const img = el.querySelector('img');
40 return { w: r.width, h: r.height, vis: cs.visibility, op: parseFloat(cs.opacity), disp: cs.display,
41 bg: cs.backgroundColor, ini: ini ? ini.textContent : null,
42 iniVis: ini ? getComputedStyle(ini).visibility : null,
43 img: !!img, hasImg: el.classList.contains('has-img'), label: el.getAttribute('aria-label') };
44 })"""
45
46 LAYOUT_JS = """() => {
47 const se = document.scrollingElement;
48 const before = se.scrollTop; window.scrollTo(0, 400); const after = se.scrollTop; window.scrollTo(0, 0);
49 const rb = id => { const e = document.getElementById(id); if (!e || e.hidden) return null; const r = e.getBoundingClientRect(); return {t: r.top, b: r.bottom, l: r.left, r: r.right}; };
50 return { vh: innerHeight, vw: innerWidth, sh: se.scrollHeight, sw: se.scrollWidth, scrolled: after - before,
51 top: rb('top-bar'), hud: rb('game-hud'), board: rb('board'), tl: rb('timeline'),
52 live: rb('tl-live'), lang: rb('lang-current') };
53 }"""
54
55
56 def visible_tokens(page, label):
57 toks = page.evaluate(TOKENS_JS)
58 ok = [t for t in toks if t['w'] > 16 and t['h'] > 16 and t['vis'] == 'visible' and t['op'] > 0.5 and t['disp'] != 'none'
59 and (t['hasImg'] or (t['ini'] and t['iniVis'] == 'visible'))]
60 check(len(toks) == 3 and len(ok) == 3, '%s: 3 visible tokens (%d/%d) %s' % (label, len(ok), len(toks),
61 [(t['label'], t['ini'], t['hasImg'], round(t['w'])) for t in toks]))
62 return toks
63
64
65 def check_layout(page, label):
66 L = page.evaluate(LAYOUT_JS)
67 check(L['sh'] <= L['vh'] + 1 and L['scrolled'] == 0, '%s: no vertical page scroll (scrollHeight %d, viewport %d)' % (label, L['sh'], L['vh']))
68 check(L['sw'] <= L['vw'] + 1, '%s: no horizontal overflow (%d > %d)' % (label, L['sw'], L['vw']))
69 check(L['top']['b'] <= L['hud']['t'] + 0.5, '%s: header (bottom %.0f) above HUD (top %.0f)' % (label, L['top']['b'], L['hud']['t']))
70 check(L['tl']['b'] <= L['vh'] + 0.5, '%s: timeline on screen (bottom %.0f / %d)' % (label, L['tl']['b'], L['vh']))
71 lv, lg = L['live'], L['lang']
72 overlap = lg and not (lv['r'] <= lg['l'] or lv['l'] >= lg['r'] or lv['b'] <= lg['t'] or lv['t'] >= lg['b'])
73 check(not overlap, '%s: Live button not covered by the language button' % label)
74 tb = L['top']
75 hits = page.evaluate("""() => { const r = document.getElementById('lang-current').getBoundingClientRect();
76 const ids = ['top-title', 'ap-hms', 'day-label', 'game-hud'];
77 return ids.filter(id => { const e = document.getElementById(id); if (!e) return false; let q = e.getBoundingClientRect();
78 if (id === 'game-hud') { return !(q.top >= r.bottom); }
79 const rg = document.createRange(); rg.selectNodeContents(e); q = rg.getBoundingClientRect(); return [e].some(k => !(q.right <= r.left || q.left >= r.right || q.bottom <= r.top || q.top >= r.bottom)); }); }""")
80 check(not hits, '%s: language button overlaps nothing (%s)' % (label, hits))
81 tr = page.evaluate("() => document.getElementById('tl-track').getBoundingClientRect().width")
82 check(tr >= 100, '%s: timeline track usable width (%.0f px)' % (label, tr))
83 check(L['board']['b'] - L['board']['t'] > 150, '%s: board has a usable size (%.0f px)' % (label, L['board']['b'] - L['board']['t']))
84 return L
85
86
87 VIEWPORTS = [
88 ('mobile-412x915', dict(viewport={'width': 412, 'height': 915}, device_scale_factor=2.6, is_mobile=True, has_touch=True)),
89 ('mobile-390x844', dict(viewport={'width': 390, 'height': 844}, device_scale_factor=3, is_mobile=True, has_touch=True)),
90 ('mobile-460x1000', dict(viewport={'width': 460, 'height': 1000}, device_scale_factor=2.35, is_mobile=True, has_touch=True)),
91 ('desktop-1280x800', dict(viewport={'width': 1280, 'height': 800})),
92 ]
93
94
95 def main():
96 with sync_playwright() as p:
97 browser = p.chromium.launch()
98 host_ctx = browser.new_context(locale='nl-NL', timezone_id='Europe/Amsterdam', **VIEWPORTS[0][1])
99 host = host_ctx.new_page()
100 host.goto(BASE + '/auth.php?test=1', wait_until='networkidle')
101 host.wait_for_selector('#btn-create')
102 host.locator('#btn-create').click()
103 host.wait_for_selector('#lobby:not([hidden])')
104 code = host.locator('#lobby-code').inner_text().strip()
105 guests = []
106 for n, mode in ((5, "none"), (6, "broken")):
107 ctx = browser.new_context(locale='nl-NL', timezone_id='Europe/Amsterdam', **VIEWPORTS[1][1])
108 g = ctx.new_page()
109 g.goto(BASE + '/auth.php?test=%d&avatar=%s&next=%s' % (n, mode, quote('index.html?join=' + code, safe='')), wait_until='networkidle')
110 g.wait_for_selector('#lobby:not([hidden])')
111 guests.append(g)
112 host.wait_for_function("() => App.game && App.game.players.length === 3", timeout=10000)
113 host.wait_for_timeout(500)
114 lobby_toks = host.evaluate("""() => Array.from(document.querySelectorAll('#lobby-players .piece')).map(el => {
115 const r = el.getBoundingClientRect(); const i = el.querySelector('.piece-initials');
116 return { w: r.width, ini: i && i.textContent, iniVis: i && getComputedStyle(i).visibility, hasImg: el.classList.contains('has-img') }; })""")
117 check(len(lobby_toks) == 3 and all(abs(t['w'] - 40) < 1 and (t['hasImg'] or t['iniVis'] == 'visible') for t in lobby_toks),
118 'lobby list: all 3 players visible %s' % lobby_toks)
119 shot(host, 'lobby-list-host')
120 g9 = guests[0]
121 mv = g9.evaluate("() => { const e = document.querySelector('#menu-avatar .piece'); return e ? e.getBoundingClientRect().width : 0; }")
122 check(True, 'guest without avatar in lobby (menu avatar width %s, menu hidden on lobby)' % mv)
123 host.locator('#btn-start').click()
124 host.wait_for_selector('#game:not([hidden])')
125 host.wait_for_timeout(800)
126 gid = host.evaluate("() => App.game.id")
127
128 # Host view on each viewport (resize the same page, plus a fresh context per viewport).
129 for name, opts in VIEWPORTS:
130 ctx = browser.new_context(locale='nl-NL', timezone_id='Europe/Amsterdam', **opts)
131 pg = ctx.new_page()
132 pg.goto(BASE + '/auth.php?test=1&next=' + quote('index.html', safe=''), wait_until='networkidle')
133 pg.wait_for_selector('#btn-create')
134 pg.evaluate("(id) => App.openGame(id, 'running')", gid)
135 pg.wait_for_selector('#game:not([hidden])')
136 pg.wait_for_timeout(800)
137 visible_tokens(pg, name + ' initial')
138 check_layout(pg, name)
139 shot(pg, name + '-game')
140 # Survive polls (3 s each).
141 pg.wait_for_timeout(7000)
142 visible_tokens(pg, name + ' after 2 polls')
143 # Tap / click an opponent, close the sheet, still visible.
144 opp = pg.locator('#board .cell:has(.piece:not(.has-img))').first
145 opp.click()
146 pg.wait_for_timeout(300)
147 if pg.locator('#sheet:not([hidden])').count():
148 shot(pg, name + '-opponent-menu')
149 pg.locator('#sheet-close').click()
150 pg.wait_for_timeout(3500)
151 visible_tokens(pg, name + ' after tap + poll')
152 check_layout(pg, name + ' after interaction')
153 ctx.close()
154
155 # Avatar-less players' own views (null avatar, broken avatar URL) on mobile.
156 for g, label in ((guests[0], 'no-avatar-player'), (guests[1], 'broken-avatar-player')):
157 g.reload(wait_until='networkidle')
158 if g.locator('#game:not([hidden])').count() == 0:
159 g.wait_for_selector('#game:not([hidden])', timeout=10000)
160 g.wait_for_timeout(800)
161 visible_tokens(g, label + ' own view')
162 check_layout(g, label + ' 390x844')
163 shot(g, label + '-390x844')
164 # Menu avatar for the no-avatar user.
165 g9.locator('#btn-settings').click()
166 g9.locator('#btn-to-menu').click()
167 g9.wait_for_selector('#menu:not([hidden])')
168 mt = g9.evaluate("() => { const e = document.querySelector('#menu-avatar .piece'); if (!e) return null; const r = e.getBoundingClientRect(); return { w: r.width, ini: e.querySelector('.piece-initials').textContent }; }")
169 check(mt and abs(mt['w'] - 32) < 1 and mt['ini'], 'menu shows initials avatar for no-avatar user: %s' % mt)
170 shot(g9, 'menu-no-avatar')
171 browser.close()
172 print('FAILED:', len(FAILS))
173 for f in FAILS:
174 print(' -', f)
175 sys.exit(1 if FAILS else 0)
176
177
178 if __name__ == '__main__':
179 main()
@@ -0,0 +1,179 @@
1#!/usr/bin/env python3
2"""t1179/t1180 real-browser checks.
3
4- Players without a profile picture (null avatar) and with a picture URL that
5 404s are visible on the board as a coloured circle with initials, stay
6 visible across several 3 s polls and after taps; also in the lobby list
7 and the menu.
8- The game view fits the viewport on mobile (412x915, 390x844, 460x1000)
9 and desktop: no page scroll, the header does not overlap the HUD, the
10 timeline is fully on screen and not covered by the language button.
11Usage: python3 test/avatar-layout-playwright.py [BASE]
12"""
13import sys
14from pathlib import Path
15from urllib.parse import quote
16
17from playwright.sync_api import sync_playwright
18
19BASE = sys.argv[1] if len(sys.argv) > 1 else 'http://127.0.0.1:8080'
20OUT = Path('/workspace/allianties-shots')
21OUT.mkdir(parents=True, exist_ok=True)
22FAILS = []
23
24
25def check(cond, msg):
26 print((' ok ' if cond else ' FAIL ') + msg)
27 if not cond:
28 FAILS.append(msg)
29
30
31def shot(page, name):
32 page.screenshot(path=str(OUT / ('t1179-' + name + '.png')), full_page=False)
33 print(' shot', OUT / ('t1179-' + name + '.png'))
34
35
36TOKENS_JS = """() => Array.from(document.querySelectorAll('#board .cell .piece')).map(el => {
37 const r = el.getBoundingClientRect(); const cs = getComputedStyle(el);
38 const ini = el.querySelector('.piece-initials');
39 const img = el.querySelector('img');
40 return { w: r.width, h: r.height, vis: cs.visibility, op: parseFloat(cs.opacity), disp: cs.display,
41 bg: cs.backgroundColor, ini: ini ? ini.textContent : null,
42 iniVis: ini ? getComputedStyle(ini).visibility : null,
43 img: !!img, hasImg: el.classList.contains('has-img'), label: el.getAttribute('aria-label') };
44})"""
45
46LAYOUT_JS = """() => {
47 const se = document.scrollingElement;
48 const before = se.scrollTop; window.scrollTo(0, 400); const after = se.scrollTop; window.scrollTo(0, 0);
49 const rb = id => { const e = document.getElementById(id); if (!e || e.hidden) return null; const r = e.getBoundingClientRect(); return {t: r.top, b: r.bottom, l: r.left, r: r.right}; };
50 return { vh: innerHeight, vw: innerWidth, sh: se.scrollHeight, sw: se.scrollWidth, scrolled: after - before,
51 top: rb('top-bar'), hud: rb('game-hud'), board: rb('board'), tl: rb('timeline'),
52 live: rb('tl-live'), lang: rb('lang-current') };
53}"""
54
55
56def visible_tokens(page, label):
57 toks = page.evaluate(TOKENS_JS)
58 ok = [t for t in toks if t['w'] > 16 and t['h'] > 16 and t['vis'] == 'visible' and t['op'] > 0.5 and t['disp'] != 'none'
59 and (t['hasImg'] or (t['ini'] and t['iniVis'] == 'visible'))]
60 check(len(toks) == 3 and len(ok) == 3, '%s: 3 visible tokens (%d/%d) %s' % (label, len(ok), len(toks),
61 [(t['label'], t['ini'], t['hasImg'], round(t['w'])) for t in toks]))
62 return toks
63
64
65def check_layout(page, label):
66 L = page.evaluate(LAYOUT_JS)
67 check(L['sh'] <= L['vh'] + 1 and L['scrolled'] == 0, '%s: no vertical page scroll (scrollHeight %d, viewport %d)' % (label, L['sh'], L['vh']))
68 check(L['sw'] <= L['vw'] + 1, '%s: no horizontal overflow (%d > %d)' % (label, L['sw'], L['vw']))
69 check(L['top']['b'] <= L['hud']['t'] + 0.5, '%s: header (bottom %.0f) above HUD (top %.0f)' % (label, L['top']['b'], L['hud']['t']))
70 check(L['tl']['b'] <= L['vh'] + 0.5, '%s: timeline on screen (bottom %.0f / %d)' % (label, L['tl']['b'], L['vh']))
71 lv, lg = L['live'], L['lang']
72 overlap = lg and not (lv['r'] <= lg['l'] or lv['l'] >= lg['r'] or lv['b'] <= lg['t'] or lv['t'] >= lg['b'])
73 check(not overlap, '%s: Live button not covered by the language button' % label)
74 tb = L['top']
75 hits = page.evaluate("""() => { const r = document.getElementById('lang-current').getBoundingClientRect();
76 const ids = ['top-title', 'ap-hms', 'day-label', 'game-hud'];
77 return ids.filter(id => { const e = document.getElementById(id); if (!e) return false; let q = e.getBoundingClientRect();
78 if (id === 'game-hud') { return !(q.top >= r.bottom); }
79 const rg = document.createRange(); rg.selectNodeContents(e); q = rg.getBoundingClientRect(); return [e].some(k => !(q.right <= r.left || q.left >= r.right || q.bottom <= r.top || q.top >= r.bottom)); }); }""")
80 check(not hits, '%s: language button overlaps nothing (%s)' % (label, hits))
81 tr = page.evaluate("() => document.getElementById('tl-track').getBoundingClientRect().width")
82 check(tr >= 100, '%s: timeline track usable width (%.0f px)' % (label, tr))
83 check(L['board']['b'] - L['board']['t'] > 150, '%s: board has a usable size (%.0f px)' % (label, L['board']['b'] - L['board']['t']))
84 return L
85
86
87VIEWPORTS = [
88 ('mobile-412x915', dict(viewport={'width': 412, 'height': 915}, device_scale_factor=2.6, is_mobile=True, has_touch=True)),
89 ('mobile-390x844', dict(viewport={'width': 390, 'height': 844}, device_scale_factor=3, is_mobile=True, has_touch=True)),
90 ('mobile-460x1000', dict(viewport={'width': 460, 'height': 1000}, device_scale_factor=2.35, is_mobile=True, has_touch=True)),
91 ('desktop-1280x800', dict(viewport={'width': 1280, 'height': 800})),
92]
93
94
95def main():
96 with sync_playwright() as p:
97 browser = p.chromium.launch()
98 host_ctx = browser.new_context(locale='nl-NL', timezone_id='Europe/Amsterdam', **VIEWPORTS[0][1])
99 host = host_ctx.new_page()
100 host.goto(BASE + '/auth.php?test=1', wait_until='networkidle')
101 host.wait_for_selector('#btn-create')
102 host.locator('#btn-create').click()
103 host.wait_for_selector('#lobby:not([hidden])')
104 code = host.locator('#lobby-code').inner_text().strip()
105 guests = []
106 for n, mode in ((5, "none"), (6, "broken")):
107 ctx = browser.new_context(locale='nl-NL', timezone_id='Europe/Amsterdam', **VIEWPORTS[1][1])
108 g = ctx.new_page()
109 g.goto(BASE + '/auth.php?test=%d&avatar=%s&next=%s' % (n, mode, quote('index.html?join=' + code, safe='')), wait_until='networkidle')
110 g.wait_for_selector('#lobby:not([hidden])')
111 guests.append(g)
112 host.wait_for_function("() => App.game && App.game.players.length === 3", timeout=10000)
113 host.wait_for_timeout(500)
114 lobby_toks = host.evaluate("""() => Array.from(document.querySelectorAll('#lobby-players .piece')).map(el => {
115 const r = el.getBoundingClientRect(); const i = el.querySelector('.piece-initials');
116 return { w: r.width, ini: i && i.textContent, iniVis: i && getComputedStyle(i).visibility, hasImg: el.classList.contains('has-img') }; })""")
117 check(len(lobby_toks) == 3 and all(abs(t['w'] - 40) < 1 and (t['hasImg'] or t['iniVis'] == 'visible') for t in lobby_toks),
118 'lobby list: all 3 players visible %s' % lobby_toks)
119 shot(host, 'lobby-list-host')
120 g9 = guests[0]
121 mv = g9.evaluate("() => { const e = document.querySelector('#menu-avatar .piece'); return e ? e.getBoundingClientRect().width : 0; }")
122 check(True, 'guest without avatar in lobby (menu avatar width %s, menu hidden on lobby)' % mv)
123 host.locator('#btn-start').click()
124 host.wait_for_selector('#game:not([hidden])')
125 host.wait_for_timeout(800)
126 gid = host.evaluate("() => App.game.id")
127
128 # Host view on each viewport (resize the same page, plus a fresh context per viewport).
129 for name, opts in VIEWPORTS:
130 ctx = browser.new_context(locale='nl-NL', timezone_id='Europe/Amsterdam', **opts)
131 pg = ctx.new_page()
132 pg.goto(BASE + '/auth.php?test=1&next=' + quote('index.html', safe=''), wait_until='networkidle')
133 pg.wait_for_selector('#btn-create')
134 pg.evaluate("(id) => App.openGame(id, 'running')", gid)
135 pg.wait_for_selector('#game:not([hidden])')
136 pg.wait_for_timeout(800)
137 visible_tokens(pg, name + ' initial')
138 check_layout(pg, name)
139 shot(pg, name + '-game')
140 # Survive polls (3 s each).
141 pg.wait_for_timeout(7000)
142 visible_tokens(pg, name + ' after 2 polls')
143 # Tap / click an opponent, close the sheet, still visible.
144 opp = pg.locator('#board .cell:has(.piece:not(.has-img))').first
145 opp.click()
146 pg.wait_for_timeout(300)
147 if pg.locator('#sheet:not([hidden])').count():
148 shot(pg, name + '-opponent-menu')
149 pg.locator('#sheet-close').click()
150 pg.wait_for_timeout(3500)
151 visible_tokens(pg, name + ' after tap + poll')
152 check_layout(pg, name + ' after interaction')
153 ctx.close()
154
155 # Avatar-less players' own views (null avatar, broken avatar URL) on mobile.
156 for g, label in ((guests[0], 'no-avatar-player'), (guests[1], 'broken-avatar-player')):
157 g.reload(wait_until='networkidle')
158 if g.locator('#game:not([hidden])').count() == 0:
159 g.wait_for_selector('#game:not([hidden])', timeout=10000)
160 g.wait_for_timeout(800)
161 visible_tokens(g, label + ' own view')
162 check_layout(g, label + ' 390x844')
163 shot(g, label + '-390x844')
164 # Menu avatar for the no-avatar user.
165 g9.locator('#btn-settings').click()
166 g9.locator('#btn-to-menu').click()
167 g9.wait_for_selector('#menu:not([hidden])')
168 mt = g9.evaluate("() => { const e = document.querySelector('#menu-avatar .piece'); if (!e) return null; const r = e.getBoundingClientRect(); return { w: r.width, ini: e.querySelector('.piece-initials').textContent }; }")
169 check(mt and abs(mt['w'] - 32) < 1 and mt['ini'], 'menu shows initials avatar for no-avatar user: %s' % mt)
170 shot(g9, 'menu-no-avatar')
171 browser.close()
172 print('FAILED:', len(FAILS))
173 for f in FAILS:
174 print(' -', f)
175 sys.exit(1 if FAILS else 0)
176
177
178if __name__ == '__main__':
179 main()
test/avatar.test.js added +119 −0
@@ -0,0 +1,119 @@
1 'use strict';
2 const { describe, it, beforeEach } = require('node:test');
3 const assert = require('node:assert/strict');
4 const Avatar = require('../src/avatar.js');
5
6 // Minimal DOM stand-in: enough for Avatar.piece.
7 function makeDoc() {
8 function El(tag) {
9 this.tagName = tag.toUpperCase();
10 this.children = [];
11 this.parentNode = null;
12 this.attrs = {};
13 this.listeners = {};
14 this._style = {};
15 const self = this;
16 this.style = new Proxy(this._style, {
17 get(o, k) { if (k === 'setProperty') { return (n, v) => { o[n] = v; }; } return o[k]; },
18 set(o, k, v) { o[k] = v; return true; }
19 });
20 this._classes = new Set();
21 this.classList = {
22 add: (...c) => c.forEach((x) => self._classes.add(x)),
23 remove: (...c) => c.forEach((x) => self._classes.delete(x)),
24 contains: (c) => self._classes.has(c)
25 };
26 this.textContent = '';
27 }
28 Object.defineProperty(El.prototype, 'className', {
29 get() { return [...this._classes].join(' '); },
30 set(v) { this._classes = new Set(String(v).split(/\s+/).filter(Boolean)); }
31 });
32 El.prototype.setAttribute = function (k, v) { this.attrs[k] = v; };
33 El.prototype.appendChild = function (c) { c.parentNode = this; this.children.push(c); return c; };
34 El.prototype.removeChild = function (c) { this.children = this.children.filter((x) => x !== c); c.parentNode = null; };
35 El.prototype.addEventListener = function (t, f) { (this.listeners[t] = this.listeners[t] || []).push(f); };
36 El.prototype.fire = function (t) { (this.listeners[t] || []).forEach((f) => f()); };
37 return { createElement: (t) => new El(t) };
38 }
39
40 const find = (el, cls) => el.children.find((c) => c.classList.contains(cls));
41
42 describe('Avatar helpers', () => {
43 beforeEach(() => { Avatar.failed = {}; Avatar.loaded = {}; });
44
45 it('makes initials from names', () => {
46 assert.equal(Avatar.initials('Tim Falken'), 'TF');
47 assert.equal(Avatar.initials('timfa'), 'TI');
48 assert.equal(Avatar.initials('a'), 'A');
49 assert.equal(Avatar.initials('jan_de_vries'), 'JV');
50 assert.equal(Avatar.initials(''), '?');
51 assert.equal(Avatar.initials(' '), '?');
52 assert.equal(Avatar.initials(null), '?');
53 assert.equal(Avatar.initials('Émile Zola'), 'ÉZ');
54 });
55
56 it('rejects empty, whitespace, script and failed URLs', () => {
57 assert.equal(Avatar.usableUrl(null), null);
58 assert.equal(Avatar.usableUrl(''), null);
59 assert.equal(Avatar.usableUrl(' '), null);
60 assert.equal(Avatar.usableUrl('javascript:alert(1)'), null);
61 assert.equal(Avatar.usableUrl('https://auth.example/avatar/1'), 'https://auth.example/avatar/1');
62 Avatar.failed['https://auth.example/avatar/1'] = true;
63 assert.equal(Avatar.usableUrl('https://auth.example/avatar/1'), null);
64 });
65
66 it('picks readable text colour', () => {
67 assert.equal(Avatar.textColor('#e8c547'), '#111');
68 assert.equal(Avatar.textColor('#1a2a6c'), '#fff');
69 assert.equal(Avatar.textColor('bogus'), '#fff');
70 });
71 });
72
73 describe('Avatar.piece', () => {
74 beforeEach(() => { Avatar.failed = {}; Avatar.loaded = {}; });
75 const doc = makeDoc();
76
77 it('without avatar: coloured circle with initials, no img', () => {
78 const el = Avatar.piece({ id: 'u2', name: 'Opponent Two', color: '#4fa3e8', avatar: null }, { doc });
79 assert.ok(el.classList.contains('piece'));
80 assert.equal(el.style.backgroundColor, '#4fa3e8');
81 assert.equal(el.style.borderColor, '#4fa3e8');
82 assert.equal(find(el, 'piece-initials').textContent, 'OT');
83 assert.equal(find(el, 'piece-img'), undefined);
84 });
85
86 it('image error removes only the img; the token itself stays and keeps initials', () => {
87 const url = 'https://auth.example/avatar/404';
88 const cell = doc.createElement('button');
89 const el = Avatar.piece({ id: 'u3', name: 'Bob', color: '#e85d5d', avatar: url }, { doc });
90 cell.appendChild(el); // token moved into a board cell (like renderBoard)
91 const img = find(el, 'piece-img');
92 assert.ok(img);
93 img.fire('error');
94 assert.equal(cell.children[0], el, 'token still in the cell');
95 assert.equal(find(el, 'piece-img'), undefined);
96 assert.equal(find(el, 'piece-initials').textContent, 'BO');
97 assert.equal(Avatar.failed[url], true);
98 // Next render (3 s poll) skips the broken URL entirely: no flicker.
99 const again = Avatar.piece({ id: 'u3', name: 'Bob', color: '#e85d5d', avatar: url }, { doc });
100 assert.equal(find(again, 'piece-img'), undefined);
101 });
102
103 it('loaded image hides initials via has-img; remembered across renders', () => {
104 const url = 'https://auth.example/avatar/ok';
105 const el = Avatar.piece({ id: 'u1', name: 'Tim', color: '#5dd39e', avatar: url }, { doc });
106 const img = find(el, 'piece-img');
107 img.naturalWidth = 64;
108 img.fire('load');
109 assert.ok(el.classList.contains('has-img'));
110 const again = Avatar.piece({ id: 'u1', name: 'Tim', color: '#5dd39e', avatar: url }, { doc });
111 assert.ok(again.classList.contains('has-img'));
112 });
113
114 it('dead players keep the dead style; missing colour gets a deterministic one', () => {
115 const el = Avatar.piece({ id: 'x', name: 'Z', alive: false }, { doc });
116 assert.ok(el.classList.contains('dead'));
117 assert.equal(el.style.backgroundColor, Avatar.colorFor('x'));
118 });
119 });
@@ -0,0 +1,119 @@
1'use strict';
2const { describe, it, beforeEach } = require('node:test');
3const assert = require('node:assert/strict');
4const Avatar = require('../src/avatar.js');
5
6// Minimal DOM stand-in: enough for Avatar.piece.
7function makeDoc() {
8 function El(tag) {
9 this.tagName = tag.toUpperCase();
10 this.children = [];
11 this.parentNode = null;
12 this.attrs = {};
13 this.listeners = {};
14 this._style = {};
15 const self = this;
16 this.style = new Proxy(this._style, {
17 get(o, k) { if (k === 'setProperty') { return (n, v) => { o[n] = v; }; } return o[k]; },
18 set(o, k, v) { o[k] = v; return true; }
19 });
20 this._classes = new Set();
21 this.classList = {
22 add: (...c) => c.forEach((x) => self._classes.add(x)),
23 remove: (...c) => c.forEach((x) => self._classes.delete(x)),
24 contains: (c) => self._classes.has(c)
25 };
26 this.textContent = '';
27 }
28 Object.defineProperty(El.prototype, 'className', {
29 get() { return [...this._classes].join(' '); },
30 set(v) { this._classes = new Set(String(v).split(/\s+/).filter(Boolean)); }
31 });
32 El.prototype.setAttribute = function (k, v) { this.attrs[k] = v; };
33 El.prototype.appendChild = function (c) { c.parentNode = this; this.children.push(c); return c; };
34 El.prototype.removeChild = function (c) { this.children = this.children.filter((x) => x !== c); c.parentNode = null; };
35 El.prototype.addEventListener = function (t, f) { (this.listeners[t] = this.listeners[t] || []).push(f); };
36 El.prototype.fire = function (t) { (this.listeners[t] || []).forEach((f) => f()); };
37 return { createElement: (t) => new El(t) };
38}
39
40const find = (el, cls) => el.children.find((c) => c.classList.contains(cls));
41
42describe('Avatar helpers', () => {
43 beforeEach(() => { Avatar.failed = {}; Avatar.loaded = {}; });
44
45 it('makes initials from names', () => {
46 assert.equal(Avatar.initials('Tim Falken'), 'TF');
47 assert.equal(Avatar.initials('timfa'), 'TI');
48 assert.equal(Avatar.initials('a'), 'A');
49 assert.equal(Avatar.initials('jan_de_vries'), 'JV');
50 assert.equal(Avatar.initials(''), '?');
51 assert.equal(Avatar.initials(' '), '?');
52 assert.equal(Avatar.initials(null), '?');
53 assert.equal(Avatar.initials('Émile Zola'), 'ÉZ');
54 });
55
56 it('rejects empty, whitespace, script and failed URLs', () => {
57 assert.equal(Avatar.usableUrl(null), null);
58 assert.equal(Avatar.usableUrl(''), null);
59 assert.equal(Avatar.usableUrl(' '), null);
60 assert.equal(Avatar.usableUrl('javascript:alert(1)'), null);
61 assert.equal(Avatar.usableUrl('https://auth.example/avatar/1'), 'https://auth.example/avatar/1');
62 Avatar.failed['https://auth.example/avatar/1'] = true;
63 assert.equal(Avatar.usableUrl('https://auth.example/avatar/1'), null);
64 });
65
66 it('picks readable text colour', () => {
67 assert.equal(Avatar.textColor('#e8c547'), '#111');
68 assert.equal(Avatar.textColor('#1a2a6c'), '#fff');
69 assert.equal(Avatar.textColor('bogus'), '#fff');
70 });
71});
72
73describe('Avatar.piece', () => {
74 beforeEach(() => { Avatar.failed = {}; Avatar.loaded = {}; });
75 const doc = makeDoc();
76
77 it('without avatar: coloured circle with initials, no img', () => {
78 const el = Avatar.piece({ id: 'u2', name: 'Opponent Two', color: '#4fa3e8', avatar: null }, { doc });
79 assert.ok(el.classList.contains('piece'));
80 assert.equal(el.style.backgroundColor, '#4fa3e8');
81 assert.equal(el.style.borderColor, '#4fa3e8');
82 assert.equal(find(el, 'piece-initials').textContent, 'OT');
83 assert.equal(find(el, 'piece-img'), undefined);
84 });
85
86 it('image error removes only the img; the token itself stays and keeps initials', () => {
87 const url = 'https://auth.example/avatar/404';
88 const cell = doc.createElement('button');
89 const el = Avatar.piece({ id: 'u3', name: 'Bob', color: '#e85d5d', avatar: url }, { doc });
90 cell.appendChild(el); // token moved into a board cell (like renderBoard)
91 const img = find(el, 'piece-img');
92 assert.ok(img);
93 img.fire('error');
94 assert.equal(cell.children[0], el, 'token still in the cell');
95 assert.equal(find(el, 'piece-img'), undefined);
96 assert.equal(find(el, 'piece-initials').textContent, 'BO');
97 assert.equal(Avatar.failed[url], true);
98 // Next render (3 s poll) skips the broken URL entirely: no flicker.
99 const again = Avatar.piece({ id: 'u3', name: 'Bob', color: '#e85d5d', avatar: url }, { doc });
100 assert.equal(find(again, 'piece-img'), undefined);
101 });
102
103 it('loaded image hides initials via has-img; remembered across renders', () => {
104 const url = 'https://auth.example/avatar/ok';
105 const el = Avatar.piece({ id: 'u1', name: 'Tim', color: '#5dd39e', avatar: url }, { doc });
106 const img = find(el, 'piece-img');
107 img.naturalWidth = 64;
108 img.fire('load');
109 assert.ok(el.classList.contains('has-img'));
110 const again = Avatar.piece({ id: 'u1', name: 'Tim', color: '#5dd39e', avatar: url }, { doc });
111 assert.ok(again.classList.contains('has-img'));
112 });
113
114 it('dead players keep the dead style; missing colour gets a deterministic one', () => {
115 const el = Avatar.piece({ id: 'x', name: 'Z', alive: false }, { doc });
116 assert.ok(el.classList.contains('dead'));
117 assert.equal(el.style.backgroundColor, Avatar.colorFor('x'));
118 });
119});