1 Commits

Author SHA1 Message Date
5957660802 feat(spa): bootstrap host/player shells from route resolver context
All checks were successful
CI / test-and-quality (push) Successful in 1m59s
2026-03-01 18:02:43 +00:00
18 changed files with 150 additions and 1148 deletions

View File

@@ -31,14 +31,3 @@ jobs:
- name: Tests - name: Tests
run: python manage.py test lobby -v 1 run: python manage.py test lobby -v 1
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: "22"
- name: Install SPA dependencies
run: npm ci --prefix frontend/angular
- name: SPA Angular smoke tests
run: npm --prefix frontend/angular test

View File

@@ -1,36 +0,0 @@
# Issue #205 — Django i18n foundation (da/en)
## Implemented acceptance checks
- **Django i18n setup for `en` + `da` with `en` fallback**
- `LANGUAGE_CODE` set to `en`.
- `LANGUAGES = [('en', 'English'), ('da', 'Danish')]`.
- `LocaleMiddleware` enabled in middleware chain.
- **Shared-key resolver/adapter (no ad hoc backend mapping)**
- Backend error responses now resolve from shared catalog keys in `shared/i18n/lobby.json`.
- `lobby.i18n.api_error()` accepts a shared key and resolves locale-specific text.
- **Representative API flow documented with key/locale behavior**
- `POST /lobby/join` with empty code returns:
- `error_code: "session_code_required"`
- localized `error`
- resolved `locale`
- **Missing key handling deterministic and loggable**
- `resolve_error_message()` returns key string when key/translation is missing.
- Warning is logged (`lobby.i18n` logger) for missing key/translation.
## Example response behavior
### Request
`POST /lobby/join` with empty code and header `Accept-Language: da`
### Response (400)
```json
{
"error": "Sessionskode er påkrævet",
"error_code": "session_code_required",
"locale": "da"
}
```
If locale is unsupported (e.g. `fr`), response uses `locale: "en"` and English message.

View File

@@ -1,28 +0,0 @@
# Issue #180 SPA gameplay flow evidence
## Flow log (host + player, no page reload)
1. Host opens SPA host shell and loads scoreboard (`GET /lobby/sessions/{code}/scoreboard`).
2. Host starts next round (`POST /lobby/sessions/{code}/rounds/next`).
3. Host shell refreshes session state in-place (`GET /lobby/sessions/{code}`) and clears old scoreboard/final leaderboard payloads.
4. Player shell performs periodic session refresh while online (3s cadence) and transitions from `scoreboard` to `lobby` without page reload.
5. Host finishes game (`POST /lobby/sessions/{code}/finish`) and renders final leaderboard directly in SPA shell.
6. Player shell reads `finished` state and renders final leaderboard in SPA (sorted by score).
7. Error/retry paths available:
- Host: next-round and finish-game retry buttons with explicit error feedback.
- Player: reconnect + submit retry feedback.
## Test output snapshot
Command:
```bash
cd frontend/angular
npm test -- --run src/app/features/host/host-shell.component.spec.ts src/app/features/player/player-shell.component.spec.ts
```
Result:
- `host-shell.component.spec.ts`: 6 passed
- `player-shell.component.spec.ts`: 7 passed
- Total: 13 passed, 0 failed

View File

@@ -1,247 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
import { createAngularApiClient, type AngularHttpClientLike } from '../../../src/api/angular-client';
describe('SPA Angular API contract smoke (host/player foundation)', () => {
it('smoke-checks canonical host/player endpoint contracts', async () => {
const get = vi.fn<AngularHttpClientLike['get']>(async <T>(url: string) => {
if (url === '/lobby/sessions/ABCD12') {
return {
session: { code: 'ABCD12', status: 'lobby', host_id: 1, current_round: 1, players_count: 2 },
players: [
{ id: 2, nickname: 'Maja', score: 0, is_connected: true },
{ id: 3, nickname: 'Bo', score: 0, is_connected: true }
],
round_question: {
id: 77,
round_number: 1,
prompt: 'Q?',
shown_at: '2026-03-01T18:00:00Z',
answers: [{ text: 'A' }, { text: 'B' }]
},
phase_view_model: {
status: 'lobby',
round_number: 1,
players_count: 2,
constraints: {
min_players_to_start: 2,
max_players_mvp: 8,
min_players_reached: true,
max_players_allowed: true
},
host: {
can_start_round: true,
can_show_question: true,
can_mix_answers: true,
can_calculate_scores: true,
can_reveal_scoreboard: true,
can_start_next_round: true,
can_finish_game: true
},
player: {
can_join: true,
can_submit_lie: true,
can_submit_guess: true,
can_view_final_result: false
}
}
} as T;
}
if (url === '/lobby/sessions/ABCD12/scoreboard') {
return {
session: { code: 'ABCD12', status: 'reveal', current_round: 1 },
leaderboard: [
{ id: 9, nickname: 'Maja', score: 200 },
{ id: 10, nickname: 'Bo', score: 150 }
]
} as T;
}
throw { status: 404, error: { error: 'Not found' } };
});
const post = vi.fn<AngularHttpClientLike['post']>(async <T>(url: string, body: unknown) => {
if (url === '/lobby/sessions/join') {
expect(body).toEqual({ code: 'ABCD12', nickname: 'Maja' });
return {
player: { id: 9, nickname: 'Maja', session_token: 'session-token-1', score: 0 },
session: { code: 'ABCD12', status: 'lobby' }
} as T;
}
if (url === '/lobby/sessions/ABCD12/rounds/start') {
expect(body).toEqual({ category_slug: 'history' });
return {
session: { code: 'ABCD12', status: 'lie', current_round: 1 },
round: { number: 1, category: { slug: 'history', name: 'History' } }
} as T;
}
if (url === '/lobby/sessions/ABCD12/questions/show') {
expect(body).toEqual({});
return {
round_question: {
id: 77,
prompt: 'Q?',
round_number: 1,
shown_at: '2026-03-01T18:00:00Z',
lie_deadline_at: '2026-03-01T18:00:30Z'
},
config: { lie_seconds: 30 }
} as T;
}
if (url === '/lobby/sessions/ABCD12/questions/77/answers/mix') {
expect(body).toEqual({});
return {
session: { code: 'ABCD12', status: 'guess', current_round: 1 },
round_question: { id: 77, round_number: 1 },
answers: [{ text: 'A' }, { text: 'B' }]
} as T;
}
if (url === '/lobby/sessions/ABCD12/questions/77/scores/calculate') {
expect(body).toEqual({});
return {
session: { code: 'ABCD12', status: 'reveal', current_round: 1 },
round_question: { id: 77, round_number: 1 },
events_created: 2,
leaderboard: [
{ id: 9, nickname: 'Maja', score: 200 },
{ id: 10, nickname: 'Bo', score: 150 }
]
} as T;
}
if (url === '/lobby/sessions/ABCD12/rounds/next') {
expect(body).toEqual({});
return { session: { code: 'ABCD12', status: 'lie', current_round: 2 } } as T;
}
if (url === '/lobby/sessions/ABCD12/finish') {
expect(body).toEqual({});
return {
session: { code: 'ABCD12', status: 'finished', current_round: 2 },
winner: { id: 9, nickname: 'Maja', score: 250 },
leaderboard: [
{ id: 9, nickname: 'Maja', score: 250 },
{ id: 10, nickname: 'Bo', score: 150 }
]
} as T;
}
if (url === '/lobby/sessions/ABCD12/questions/77/lies/submit') {
expect(body).toEqual({ player_id: 9, session_token: 'session-token-1', text: 'my lie' });
return {
lie: {
id: 501,
player_id: 9,
round_question_id: 77,
text: 'my lie',
created_at: '2026-03-01T18:00:05Z'
},
window: { lie_deadline_at: '2026-03-01T18:00:30Z' }
} as T;
}
if (url === '/lobby/sessions/ABCD12/questions/77/guesses/submit') {
expect(body).toEqual({ player_id: 9, session_token: 'session-token-1', selected_text: 'B' });
return {
guess: {
id: 601,
player_id: 9,
round_question_id: 77,
selected_text: 'B',
is_correct: false,
fooled_player_id: null,
created_at: '2026-03-01T18:00:15Z'
},
window: { guess_deadline_at: '2026-03-01T18:01:00Z' }
} as T;
}
throw { status: 404, error: { error: 'Not found' } };
});
const client = createAngularApiClient({ get, post } as AngularHttpClientLike);
const session = await client.getSession(' abcd12 ');
expect(session.ok).toBe(true);
if (session.ok) {
expect(session.data.session.code).toBe('ABCD12');
expect(session.data.phase_view_model.host.can_start_next_round).toBe(true);
expect(session.data.phase_view_model.player.can_submit_guess).toBe(true);
}
expect((await client.joinSession({ code: ' abcd12 ', nickname: ' Maja ' })).ok).toBe(true);
expect((await client.startRound(' abcd12 ', { category_slug: 'history' })).ok).toBe(true);
expect((await client.showQuestion(' abcd12 ')).ok).toBe(true);
expect((await client.mixAnswers(' abcd12 ', 77)).ok).toBe(true);
expect((await client.calculateScores(' abcd12 ', 77)).ok).toBe(true);
expect((await client.getScoreboard(' abcd12 ')).ok).toBe(true);
expect((await client.startNextRound(' abcd12 ')).ok).toBe(true);
expect((await client.finishGame(' abcd12 ')).ok).toBe(true);
expect(
(
await client.submitLie(' abcd12 ', 77, {
player_id: 9,
session_token: 'session-token-1',
text: 'my lie'
})
).ok
).toBe(true);
expect(
(
await client.submitGuess(' abcd12 ', 77, {
player_id: 9,
session_token: 'session-token-1',
selected_text: 'B'
})
).ok
).toBe(true);
expect(get).toHaveBeenNthCalledWith(1, '/lobby/sessions/ABCD12', { withCredentials: true });
expect(get).toHaveBeenNthCalledWith(2, '/lobby/sessions/ABCD12/scoreboard', { withCredentials: true });
expect(post).toHaveBeenNthCalledWith(
1,
'/lobby/sessions/join',
{ code: 'ABCD12', nickname: 'Maja' },
{ withCredentials: true }
);
expect(post).toHaveBeenNthCalledWith(
2,
'/lobby/sessions/ABCD12/rounds/start',
{ category_slug: 'history' },
{ withCredentials: true }
);
expect(post).toHaveBeenNthCalledWith(3, '/lobby/sessions/ABCD12/questions/show', {}, { withCredentials: true });
expect(post).toHaveBeenNthCalledWith(
4,
'/lobby/sessions/ABCD12/questions/77/answers/mix',
{},
{ withCredentials: true }
);
expect(post).toHaveBeenNthCalledWith(
5,
'/lobby/sessions/ABCD12/questions/77/scores/calculate',
{},
{ withCredentials: true }
);
expect(post).toHaveBeenNthCalledWith(6, '/lobby/sessions/ABCD12/rounds/next', {}, { withCredentials: true });
expect(post).toHaveBeenNthCalledWith(7, '/lobby/sessions/ABCD12/finish', {}, { withCredentials: true });
expect(post).toHaveBeenNthCalledWith(
8,
'/lobby/sessions/ABCD12/questions/77/lies/submit',
{ player_id: 9, session_token: 'session-token-1', text: 'my lie' },
{ withCredentials: true }
);
expect(post).toHaveBeenNthCalledWith(
9,
'/lobby/sessions/ABCD12/questions/77/guesses/submit',
{ player_id: 9, session_token: 'session-token-1', selected_text: 'B' },
{ withCredentials: true }
);
});
});

View File

@@ -1,5 +1,4 @@
.shell { font-family: Arial, sans-serif; margin: 1rem; } .shell { font-family: Arial, sans-serif; margin: 1rem; }
.shell__header { display: flex; flex-wrap: wrap; gap: 0.75rem; justify-content: space-between; align-items: center; border-bottom: 1px solid #ddd; padding-bottom: 0.75rem; } .shell__header { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #ddd; padding-bottom: 0.75rem; }
.shell__header nav { display: flex; gap: 0.75rem; } .shell__header nav { display: flex; gap: 0.75rem; }
.shell__content { margin-top: 1rem; } .shell__content { margin-top: 1rem; }
.locale-picker { display: inline-flex; align-items: center; gap: 0.4rem; font-size: 0.95rem; }

View File

@@ -1,20 +1,13 @@
<main class="shell"> <main class="shell">
<header class="shell__header"> <header class="shell__header">
<h1>{{ copy('app.title') }}</h1> <h1>WPP Angular Shell</h1>
<nav> <nav>
<a routerLink="/host">{{ copy('app.host_nav') }}</a> <a routerLink="/host">Host</a>
<a routerLink="/player">{{ copy('app.player_nav') }}</a> <a routerLink="/player">Player</a>
</nav> </nav>
<label class="locale-picker">
{{ copy('app.language_label') }}
<select [ngModel]="locale" (ngModelChange)="setLocale($event)">
<option value="en">English</option>
<option value="da">Dansk</option>
</select>
</label>
</header> </header>
<section class="shell__content" [attr.data-wpp-locale]="locale"> <section class="shell__content">
<router-outlet></router-outlet> <router-outlet></router-outlet>
</section> </section>
</main> </main>

View File

@@ -1,33 +1,20 @@
import { Component, inject } from '@angular/core'; import { Component, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Router, RouterLink, RouterOutlet } from '@angular/router'; import { Router, RouterLink, RouterOutlet } from '@angular/router';
import { resolvePreferredLocale, setPreferredLocale, t } from './lobby-i18n';
@Component({ @Component({
selector: 'app-root', selector: 'app-root',
standalone: true, standalone: true,
imports: [RouterOutlet, RouterLink, FormsModule], imports: [RouterOutlet, RouterLink],
templateUrl: './app.component.html', templateUrl: './app.component.html',
styleUrl: './app.component.css', styleUrl: './app.component.css',
}) })
export class AppComponent { export class AppComponent {
private readonly router = inject(Router); private readonly router = inject(Router);
locale = resolvePreferredLocale();
constructor() { constructor() {
const shellRoute = document.body.dataset['wppShellRoute']; const shellRoute = document.body.dataset['wppShellRoute'];
if (shellRoute?.startsWith('/host') || shellRoute?.startsWith('/player')) { if (shellRoute?.startsWith('/host') || shellRoute?.startsWith('/player')) {
void this.router.navigateByUrl(shellRoute); void this.router.navigateByUrl(shellRoute);
} }
} }
copy(key: string): string {
return t(key, this.locale);
}
setLocale(locale: string): void {
this.locale = setPreferredLocale(locale);
}
} }

View File

@@ -245,22 +245,20 @@ describe('HostShellComponent gameplay wiring', () => {
expect(component.finishError).toContain('Session code is required'); expect(component.finishError).toContain('Session code is required');
}); });
it('syncs host hash-route with latest phase after refresh without page reload', async () => { it('bootstraps refresh from resolver route context on init', () => {
const fetchMock: FetchMock = vi.fn().mockResolvedValue(jsonResponse(200, sessionDetailPayload('guess', { roundQuestionId: 77 })));
vi.stubGlobal('fetch', fetchMock);
const replaceState = vi.fn();
vi.stubGlobal('window', { vi.stubGlobal('window', {
location: { hash: '#/host/lobby/ABCD12' }, sessionStorage: {
history: { state: null, replaceState }, getItem: vi.fn().mockReturnValue(null),
sessionStorage: { getItem: vi.fn().mockReturnValue(null), setItem: vi.fn() }, setItem: vi.fn(),
},
}); });
const component = new HostShellComponent(); const component = new HostShellComponent({ snapshot: { data: { routeContext: { sessionCode: 'ab12' } } } } as never);
component.sessionCode = 'ABCD12'; const refreshSpy = vi.spyOn(component, 'refreshSession').mockResolvedValue();
await component.refreshSession(); component.ngOnInit();
expect(replaceState).toHaveBeenCalledWith(null, '', '#/host/guess/ABCD12'); expect(component.sessionCode).toBe('AB12');
expect(refreshSpy).toHaveBeenCalledOnce();
}); });
}); });

View File

@@ -1,11 +1,12 @@
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { Component, OnDestroy, OnInit } from '@angular/core'; import { Component, OnInit, Optional } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { createApiClient } from '../../../../../src/api/client'; import { createApiClient } from '../../../../../src/api/client';
import type { FinishGameResponse, ScoreboardResponse } from '../../../../../src/api/types'; import type { FinishGameResponse, ScoreboardResponse } from '../../../../../src/api/types';
import { createVerticalSliceController } from '../../../../../src/spa/vertical-slice'; import { createVerticalSliceController } from '../../../../../src/spa/vertical-slice';
import { clientHasNoAudioOutput, resolvePreferredLocale, subscribeToLocaleChanges, t } from '../../lobby-i18n'; import type { RouteSessionContext } from '../../session-route-context';
interface SessionDetail { interface SessionDetail {
session: { code: string; status: string; current_round: number }; session: { code: string; status: string; current_round: number };
@@ -21,41 +22,40 @@ type LeaderboardResponse = FinishGameResponse;
standalone: true, standalone: true,
imports: [CommonModule, FormsModule], imports: [CommonModule, FormsModule],
template: ` template: `
<h2>{{ copy('host.title') }}</h2> <h2>Host SPA gameplay flow</h2>
<div class="panel" [attr.data-client-has-no-audio-output]="clientHasNoAudioOutput"> <div class="panel">
<label>{{ copy('common.session_code') }} <input [(ngModel)]="sessionCode" /></label> <label>Session code <input [(ngModel)]="sessionCode" /></label>
<label>{{ copy('host.category') }} <input [(ngModel)]="categorySlug" /></label> <label>Category <input [(ngModel)]="categorySlug" /></label>
<button (click)="refreshSession()" [disabled]="loading">{{ copy('common.refresh') }}</button> <button (click)="refreshSession()" [disabled]="loading">Refresh</button>
<button (click)="startRound()" [disabled]="loading">{{ copy('host.start_round') }}</button> <button (click)="startRound()" [disabled]="loading">Start round</button>
<button (click)="showQuestion()" [disabled]="loading || !roundQuestionId">{{ copy('host.show_question') }}</button> <button (click)="showQuestion()" [disabled]="loading || !roundQuestionId">Show question</button>
<button (click)="mixAnswers()" [disabled]="loading || !roundQuestionId">{{ copy('host.mix_answers') }}</button> <button (click)="mixAnswers()" [disabled]="loading || !roundQuestionId">Mix answers → guess</button>
<button (click)="calculateScores()" [disabled]="loading || !roundQuestionId">{{ copy('host.calculate_scores') }}</button> <button (click)="calculateScores()" [disabled]="loading || !roundQuestionId">Calculate scores → reveal</button>
<button (click)="loadScoreboard()" [disabled]="loading">{{ copy('host.load_scoreboard') }}</button> <button (click)="loadScoreboard()" [disabled]="loading">Load scoreboard</button>
<button (click)="startNextRound()" [disabled]="loading">{{ copy('host.start_next_round') }}</button> <button (click)="startNextRound()" [disabled]="loading">Start next round</button>
<button (click)="finishGame()" [disabled]="loading">{{ copy('host.finish_game') }}</button> <button (click)="finishGame()" [disabled]="loading">Finish game</button>
<button *ngIf="scoreboardError" (click)="loadScoreboard()" [disabled]="loading">{{ copy('host.retry_scoreboard') }}</button> <button *ngIf="scoreboardError" (click)="loadScoreboard()" [disabled]="loading">Retry scoreboard</button>
<button *ngIf="nextRoundError" (click)="startNextRound()" [disabled]="loading">{{ copy('host.retry_next_round') }}</button> <button *ngIf="nextRoundError" (click)="startNextRound()" [disabled]="loading">Retry next round</button>
<button *ngIf="finishError" (click)="finishGame()" [disabled]="loading">{{ copy('host.retry_finish') }}</button> <button *ngIf="finishError" (click)="finishGame()" [disabled]="loading">Retry finish game</button>
</div> </div>
<p *ngIf="session" class="hint">{{ copy('host.audio_locale_hint') }}: {{ locale }}</p>
<p *ngIf="error" class="error">{{ error }}</p> <p *ngIf="error" class="error">{{ error }}</p>
<p *ngIf="scoreboardError" class="error">{{ scoreboardError }}</p> <p *ngIf="scoreboardError" class="error">{{ scoreboardError }}</p>
<p *ngIf="nextRoundError" class="error">{{ nextRoundError }}</p> <p *ngIf="nextRoundError" class="error">{{ nextRoundError }}</p>
<p *ngIf="finishError" class="error">{{ finishError }}</p> <p *ngIf="finishError" class="error">{{ finishError }}</p>
<div *ngIf="session" class="panel"> <div *ngIf="session" class="panel">
<p><strong>{{ copy('common.status') }}:</strong> {{ session.session.status }} · {{ copy('common.round') }} {{ session.session.current_round }}</p> <p><strong>Status:</strong> {{ session.session.status }} · round {{ session.session.current_round }}</p>
<p><strong>{{ copy('common.round_question_id') }}:</strong> {{ roundQuestionId || '-' }}</p> <p><strong>Round question id:</strong> {{ roundQuestionId || '-' }}</p>
<p *ngIf="session.round_question"><strong>{{ copy('common.prompt') }}:</strong> {{ session.round_question.prompt }}</p> <p *ngIf="session.round_question"><strong>Prompt:</strong> {{ session.round_question.prompt }}</p>
<ul> <ul>
<li *ngFor="let p of session.players">{{ p.nickname }}: {{ p.score }}</li> <li *ngFor="let p of session.players">{{ p.nickname }}: {{ p.score }}</li>
</ul> </ul>
<pre *ngIf="scoreboardPayload">{{ scoreboardPayload }}</pre> <pre *ngIf="scoreboardPayload">{{ scoreboardPayload }}</pre>
<div *ngIf="finalLeaderboard.length"> <div *ngIf="finalLeaderboard.length">
<h3>{{ copy('host.final_leaderboard') }}</h3> <h3>Final leaderboard</h3>
<p *ngIf="finalWinner"><strong>{{ copy('host.winner') }}:</strong> {{ finalWinner.nickname }} ({{ finalWinner.score }} pts)</p> <p *ngIf="finalWinner"><strong>Winner:</strong> {{ finalWinner.nickname }} ({{ finalWinner.score }} pts)</p>
<ol> <ol>
<li *ngFor="let entry of finalLeaderboard">{{ entry.nickname }}: {{ entry.score }}</li> <li *ngFor="let entry of finalLeaderboard">{{ entry.nickname }}: {{ entry.score }}</li>
</ol> </ol>
@@ -64,10 +64,7 @@ type LeaderboardResponse = FinishGameResponse;
</div> </div>
`, `,
}) })
export class HostShellComponent implements OnInit, OnDestroy { export class HostShellComponent implements OnInit {
locale = resolvePreferredLocale();
readonly clientHasNoAudioOutput = clientHasNoAudioOutput;
sessionCode = ''; sessionCode = '';
categorySlug = 'general'; categorySlug = 'general';
roundQuestionId = ''; roundQuestionId = '';
@@ -84,19 +81,16 @@ export class HostShellComponent implements OnInit, OnDestroy {
private readonly api = createApiClient(); private readonly api = createApiClient();
private readonly controller = createVerticalSliceController(this.api); private readonly controller = createVerticalSliceController(this.api);
private unsubscribeLocale: (() => void) | null = null;
constructor(@Optional() private readonly route: ActivatedRoute | null = null) {}
ngOnInit(): void { ngOnInit(): void {
this.unsubscribeLocale = subscribeToLocaleChanges((locale) => {
this.locale = locale;
});
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
return; return;
} }
const hashRoute = window.location.hash.replace(/^#\/?/, ''); const routeContext = this.route?.snapshot.data['routeContext'] as RouteSessionContext | undefined;
const match = hashRoute.match(/^host(?:\/[^/]+)?(?:\/([^/?#]+))?/i); const codeFromRoute = routeContext?.sessionCode ?? '';
const codeFromRoute = match?.[1] ?? '';
const storedCode = window.sessionStorage.getItem('wpp.host-session-code') ?? ''; const storedCode = window.sessionStorage.getItem('wpp.host-session-code') ?? '';
const candidate = codeFromRoute || storedCode; const candidate = codeFromRoute || storedCode;
@@ -109,15 +103,6 @@ export class HostShellComponent implements OnInit, OnDestroy {
void this.refreshSession(); void this.refreshSession();
} }
ngOnDestroy(): void {
this.unsubscribeLocale?.();
this.unsubscribeLocale = null;
}
copy(key: string): string {
return t(key, this.locale);
}
private normalizeCode(value: string): string { private normalizeCode(value: string): string {
return value.trim().toUpperCase(); return value.trim().toUpperCase();
} }
@@ -165,9 +150,8 @@ export class HostShellComponent implements OnInit, OnDestroy {
if (this.session.session.status !== 'finished') { if (this.session.session.status !== 'finished') {
this.resetFinalLeaderboard(); this.resetFinalLeaderboard();
} }
this.syncRouteFromSession();
} catch (error) { } catch (error) {
this.error = `${this.copy('host.session_refresh_failed')}: ${(error as Error).message}`; this.error = `Session refresh failed: ${(error as Error).message}`;
} finally { } finally {
this.loading = false; this.loading = false;
} }
@@ -185,7 +169,6 @@ export class HostShellComponent implements OnInit, OnDestroy {
this.roundQuestionId = this.session.round_question?.id ? String(this.session.round_question.id) : ''; this.roundQuestionId = this.session.round_question?.id ? String(this.session.round_question.id) : '';
this.scoreboardPayload = ''; this.scoreboardPayload = '';
this.resetFinalLeaderboard(); this.resetFinalLeaderboard();
this.syncRouteFromSession();
}); });
} }
@@ -225,7 +208,7 @@ export class HostShellComponent implements OnInit, OnDestroy {
this.scoreboardPayload = JSON.stringify(payload, null, 2); this.scoreboardPayload = JSON.stringify(payload, null, 2);
await this.refreshSession(); await this.refreshSession();
} catch (error) { } catch (error) {
this.scoreboardError = `${this.copy('host.scoreboard_failed')}: ${(error as Error).message}`; this.scoreboardError = `Scoreboard failed: ${(error as Error).message}`;
} finally { } finally {
this.loading = false; this.loading = false;
} }
@@ -238,14 +221,14 @@ export class HostShellComponent implements OnInit, OnDestroy {
try { try {
const code = this.normalizeCode(this.sessionCode); const code = this.normalizeCode(this.sessionCode);
if (!code) { if (!code) {
throw new Error(this.copy('host.session_code_required')); throw new Error('Session code is required');
} }
await this.request(`/lobby/sessions/${encodeURIComponent(code)}/rounds/next`, 'POST', {}); await this.request(`/lobby/sessions/${encodeURIComponent(code)}/rounds/next`, 'POST', {});
this.scoreboardPayload = ''; this.scoreboardPayload = '';
this.resetFinalLeaderboard(); this.resetFinalLeaderboard();
await this.refreshSession(); await this.refreshSession();
} catch (error) { } catch (error) {
this.nextRoundError = `${this.copy('host.next_round_failed')}: ${(error as Error).message}`; this.nextRoundError = `Next round failed: ${(error as Error).message}`;
} finally { } finally {
this.loading = false; this.loading = false;
} }
@@ -258,7 +241,7 @@ export class HostShellComponent implements OnInit, OnDestroy {
try { try {
const code = this.normalizeCode(this.sessionCode); const code = this.normalizeCode(this.sessionCode);
if (!code) { if (!code) {
throw new Error(this.copy('host.session_code_required')); throw new Error('Session code is required');
} }
const payload = await this.request<LeaderboardResponse>(`/lobby/sessions/${encodeURIComponent(code)}/finish`, 'POST', {}); const payload = await this.request<LeaderboardResponse>(`/lobby/sessions/${encodeURIComponent(code)}/finish`, 'POST', {});
this.finalLeaderboardPayload = JSON.stringify(payload, null, 2); this.finalLeaderboardPayload = JSON.stringify(payload, null, 2);
@@ -271,7 +254,7 @@ export class HostShellComponent implements OnInit, OnDestroy {
this.finalWinner = payload.winner ?? this.finalLeaderboard[0] ?? null; this.finalWinner = payload.winner ?? this.finalLeaderboard[0] ?? null;
await this.refreshSession(); await this.refreshSession();
} catch (error) { } catch (error) {
this.finishError = `${this.copy('host.finish_game_failed')}: ${(error as Error).message}`; this.finishError = `Finish game failed: ${(error as Error).message}`;
} finally { } finally {
this.loading = false; this.loading = false;
} }
@@ -283,25 +266,6 @@ export class HostShellComponent implements OnInit, OnDestroy {
this.finalWinner = null; this.finalWinner = null;
} }
private syncRouteFromSession(): void {
if (!this.session) {
return;
}
const phase = this.session.session.status || 'lobby';
const code = this.normalizeCode(this.session.session.code || this.sessionCode);
if (!code) {
return;
}
const targetPath = `#/host/${encodeURIComponent(phase)}/${encodeURIComponent(code)}`;
if (typeof window === 'undefined' || window.location.hash === targetPath) {
return;
}
window.history.replaceState(window.history.state, '', targetPath);
}
private async runAction(action: () => Promise<void>): Promise<void> { private async runAction(action: () => Promise<void>): Promise<void> {
this.loading = true; this.loading = true;
this.error = ''; this.error = '';

View File

@@ -198,30 +198,6 @@ describe('PlayerShellComponent gameplay wiring', () => {
expect(fetchMock).toHaveBeenCalledTimes(3); expect(fetchMock).toHaveBeenCalledTimes(3);
}); });
it('auto-refreshes player session to avoid host/player state desync between rounds', async () => {
vi.useFakeTimers();
const fetchMock: FetchMock = vi
.fn()
.mockResolvedValueOnce(jsonResponse(200, sessionDetailPayload('scoreboard', { roundQuestionId: null })))
.mockResolvedValueOnce(jsonResponse(200, sessionDetailPayload('lobby', { roundQuestionId: null })));
vi.stubGlobal('fetch', fetchMock);
const component = new PlayerShellComponent();
component.sessionCode = 'ABCD12';
await component.refreshSession();
expect(component.session?.session.status).toBe('scoreboard');
await vi.advanceTimersByTimeAsync(3100);
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(component.session?.session.status).toBe('lobby');
component.ngOnDestroy();
});
it('enters reconnecting state when network request fails while online', async () => { it('enters reconnecting state when network request fails while online', async () => {
vi.stubGlobal('navigator', { onLine: true }); vi.stubGlobal('navigator', { onLine: true });
@@ -233,8 +209,8 @@ describe('PlayerShellComponent gameplay wiring', () => {
await component.refreshSession(); await component.refreshSession();
expect(component.connectionState === 'reconnecting' || component.connectionState === 'online').toBe(true); expect(component.connectionState).toBe('reconnecting');
expect(component.error).toContain('Session refresh failed:'); expect(component.error).toContain('Session refresh failed: Could not load lobby status.');
}); });
it('uses offline state when browser reports disconnected network', async () => { it('uses offline state when browser reports disconnected network', async () => {
@@ -278,6 +254,28 @@ describe('PlayerShellComponent gameplay wiring', () => {
expect(component.loadingTransition).toBeNull(); expect(component.loadingTransition).toBeNull();
}); });
it('hydrates session context from resolver payload on init', () => {
const component = new PlayerShellComponent({
snapshot: {
data: {
routeContext: {
sessionCode: 'ab12',
playerId: 7,
token: 'tok-7',
},
},
},
} as never);
const refreshSpy = vi.spyOn(component, 'refreshSession').mockResolvedValue();
component.ngOnInit();
expect(component.sessionCode).toBe('AB12');
expect(component.playerId).toBe(7);
expect(component.sessionToken).toBe('tok-7');
expect(refreshSpy).toHaveBeenCalledOnce();
});
it('returnToJoin clears persisted session context and transient state', () => { it('returnToJoin clears persisted session context and transient state', () => {
const values = new Map<string, string>(); const values = new Map<string, string>();
const localStorage = { const localStorage = {
@@ -319,35 +317,4 @@ describe('PlayerShellComponent gameplay wiring', () => {
expect(component.submitError).toBeNull(); expect(component.submitError).toBeNull();
expect(values.get('wpp.session-context')).toBeUndefined(); expect(values.get('wpp.session-context')).toBeUndefined();
}); });
it('syncs player hash-route with latest phase during periodic state sync', async () => {
vi.useFakeTimers();
const fetchMock: FetchMock = vi
.fn()
.mockResolvedValueOnce(jsonResponse(200, sessionDetailPayload('scoreboard', { roundQuestionId: null })))
.mockResolvedValueOnce(jsonResponse(200, sessionDetailPayload('lobby', { roundQuestionId: null })));
vi.stubGlobal('fetch', fetchMock);
const replaceState = vi.fn();
const localStorage = { getItem: vi.fn().mockReturnValue(null), setItem: vi.fn(), removeItem: vi.fn() };
vi.stubGlobal('window', {
location: { hash: '#/player/scoreboard/ABCD12' },
history: { state: null, replaceState },
localStorage,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
});
const component = new PlayerShellComponent();
component.sessionCode = 'ABCD12';
await component.refreshSession();
await vi.advanceTimersByTimeAsync(3100);
expect(replaceState).toHaveBeenCalledWith(null, '', '#/player/lobby/ABCD12');
component.ngOnDestroy();
});
}); });

View File

@@ -1,11 +1,12 @@
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { Component, OnDestroy, OnInit } from '@angular/core'; import { Component, OnDestroy, OnInit, Optional } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { createApiClient } from '../../../../../src/api/client'; import { createApiClient } from '../../../../../src/api/client';
import { createSessionContextStore } from '../../../../../src/spa/session-context-store'; import { createSessionContextStore } from '../../../../../src/spa/session-context-store';
import { createVerticalSliceController } from '../../../../../src/spa/vertical-slice'; import { createVerticalSliceController } from '../../../../../src/spa/vertical-slice';
import { clientHasNoAudioOutput, resolvePreferredLocale, subscribeToLocaleChanges, t } from '../../lobby-i18n'; import type { RouteSessionContext } from '../../session-route-context';
interface SessionDetail { interface SessionDetail {
session: { code: string; status: string; current_round: number }; session: { code: string; status: string; current_round: number };
@@ -28,35 +29,35 @@ function resolveLocalStorage(): Storage | undefined {
standalone: true, standalone: true,
imports: [CommonModule, FormsModule], imports: [CommonModule, FormsModule],
template: ` template: `
<h2>{{ copy('player.title') }}</h2> <h2>Player SPA gameplay flow</h2>
<div class="panel" [attr.data-client-has-no-audio-output]="clientHasNoAudioOutput"> <div class="panel">
<label>{{ copy('common.session_code') }} <input [(ngModel)]="sessionCode" /></label> <label>Session code <input [(ngModel)]="sessionCode" /></label>
<label>{{ copy('player.nickname') }} <input [(ngModel)]="nickname" /></label> <label>Nickname <input [(ngModel)]="nickname" /></label>
<button (click)="refreshSession()" [disabled]="loading">{{ copy('common.refresh') }}</button> <button (click)="refreshSession()" [disabled]="loading">Refresh</button>
<button (click)="joinSession()" [disabled]="loading">{{ copy('player.join') }}</button> <button (click)="joinSession()" [disabled]="loading">Join</button>
</div> </div>
<p *ngIf="connectionState === 'reconnecting'" class="error"> <p *ngIf="connectionState === 'reconnecting'" class="error">
{{ copy('player.reconnecting_text') }} Reconnecting… trying to refresh session state.
<button type="button" (click)="retryReconnect()" [disabled]="loading">{{ copy('player.retry_now') }}</button> <button type="button" (click)="retryReconnect()" [disabled]="loading">Retry now</button>
<button type="button" (click)="returnToJoin()" [disabled]="loading">{{ copy('common.back_to_join') }}</button> <button type="button" (click)="returnToJoin()" [disabled]="loading">Back to join</button>
</p> </p>
<p *ngIf="connectionState === 'offline'" class="error"> <p *ngIf="connectionState === 'offline'" class="error">
{{ copy('player.offline_text') }} You are offline. Reconnect to continue gameplay.
<button type="button" (click)="retryReconnect()" [disabled]="loading">{{ copy('player.retry_now') }}</button> <button type="button" (click)="retryReconnect()" [disabled]="loading">Retry now</button>
<button type="button" (click)="returnToJoin()" [disabled]="loading">{{ copy('common.back_to_join') }}</button> <button type="button" (click)="returnToJoin()" [disabled]="loading">Back to join</button>
</p> </p>
<p *ngIf="loading" class="hint">{{ loadingMessage }}</p> <p *ngIf="loading" class="hint">{{ loadingMessage }}</p>
<div class="panel" *ngIf="session"> <div class="panel" *ngIf="session">
<p><strong>{{ copy('common.status') }}:</strong> {{ session.session.status }}</p> <p><strong>Status:</strong> {{ session.session.status }}</p>
<p *ngIf="session.round_question"><strong>{{ copy('common.prompt') }}:</strong> {{ session.round_question.prompt }}</p> <p *ngIf="session.round_question"><strong>Prompt:</strong> {{ session.round_question.prompt }}</p>
<label>{{ copy('player.lie_label') }} <input [(ngModel)]="lieText" [disabled]="loading || session.session.status !== 'lie'" /></label> <label>Løgn <input [(ngModel)]="lieText" [disabled]="loading || session.session.status !== 'lie'" /></label>
<button (click)="submitLie()" [disabled]="loading || session.session.status !== 'lie'">{{ copy('player.submit_lie') }}</button> <button (click)="submitLie()" [disabled]="loading || session.session.status !== 'lie'">Submit lie</button>
<button *ngIf="submitError?.kind === 'lie'" (click)="submitLie()" [disabled]="loading">{{ copy('player.retry_lie_submit') }}</button> <button *ngIf="submitError?.kind === 'lie'" (click)="submitLie()" [disabled]="loading">Retry lie submit</button>
<div class="answers" *ngIf="session.round_question?.answers?.length"> <div class="answers" *ngIf="session.round_question?.answers?.length">
<button <button
@@ -70,11 +71,11 @@ function resolveLocalStorage(): Storage | undefined {
</button> </button>
</div> </div>
<button (click)="submitGuess()" [disabled]="loading || session.session.status !== 'guess' || !selectedGuess">{{ copy('player.submit_guess') }}</button> <button (click)="submitGuess()" [disabled]="loading || session.session.status !== 'guess' || !selectedGuess">Submit guess</button>
<button *ngIf="submitError?.kind === 'guess'" (click)="submitGuess()" [disabled]="loading">{{ copy('player.retry_guess_submit') }}</button> <button *ngIf="submitError?.kind === 'guess'" (click)="submitGuess()" [disabled]="loading">Retry guess submit</button>
<div *ngIf="session.session.status === 'finished' && finalLeaderboard.length"> <div *ngIf="session.session.status === 'finished' && finalLeaderboard.length">
<h3>{{ copy('player.final_leaderboard') }}</h3> <h3>Final leaderboard</h3>
<ol> <ol>
<li *ngFor="let entry of finalLeaderboard">{{ entry.nickname }}: {{ entry.score }}</li> <li *ngFor="let entry of finalLeaderboard">{{ entry.nickname }}: {{ entry.score }}</li>
</ol> </ol>
@@ -85,15 +86,12 @@ function resolveLocalStorage(): Storage | undefined {
<p *ngIf="submitError" class="error">{{ submitError.message }}</p> <p *ngIf="submitError" class="error">{{ submitError.message }}</p>
<div class="panel" *ngIf="error || submitError"> <div class="panel" *ngIf="error || submitError">
<button type="button" (click)="retryReconnect()" [disabled]="loading">{{ copy('common.retry') }}</button> <button type="button" (click)="retryReconnect()" [disabled]="loading">Retry</button>
<button type="button" (click)="returnToJoin()" [disabled]="loading">{{ copy('common.back_to_join') }}</button> <button type="button" (click)="returnToJoin()" [disabled]="loading">Back to join</button>
</div> </div>
`, `,
}) })
export class PlayerShellComponent implements OnInit, OnDestroy { export class PlayerShellComponent implements OnInit, OnDestroy {
locale = resolvePreferredLocale();
readonly clientHasNoAudioOutput = clientHasNoAudioOutput;
sessionCode = ''; sessionCode = '';
nickname = ''; nickname = '';
playerId = 0; playerId = 0;
@@ -111,10 +109,8 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
private readonly sessionContextStore = createSessionContextStore(resolveLocalStorage()); private readonly sessionContextStore = createSessionContextStore(resolveLocalStorage());
private readonly controller = createVerticalSliceController(createApiClient(), this.sessionContextStore); private readonly controller = createVerticalSliceController(createApiClient(), this.sessionContextStore);
private reconnectTimer: ReturnType<typeof setTimeout> | null = null; private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private stateSyncTimer: ReturnType<typeof setTimeout> | null = null;
private unsubscribeLocale: (() => void) | null = null;
constructor() { constructor(@Optional() private readonly route: ActivatedRoute | null = null) {
if (typeof navigator !== 'undefined' && !navigator.onLine) { if (typeof navigator !== 'undefined' && !navigator.onLine) {
this.connectionState = 'offline'; this.connectionState = 'offline';
} }
@@ -126,21 +122,13 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
} }
ngOnInit(): void { ngOnInit(): void {
this.unsubscribeLocale = subscribeToLocaleChanges((locale) => { const routeContext = this.route?.snapshot.data['routeContext'] as RouteSessionContext | undefined;
this.locale = locale;
});
const hashRoute = window.location.hash.replace(/^#\/?/, '');
const match = hashRoute.match(/^player(?:\/[^/]+)?(?:\/([^/?#]+))?/i);
const codeFromRoute = match?.[1] ?? '';
const persistedContext = this.sessionContextStore.get(); const persistedContext = this.sessionContextStore.get();
if (persistedContext) {
this.playerId = persistedContext.playerId;
this.sessionToken = persistedContext.token;
}
const candidate = codeFromRoute || persistedContext?.sessionCode || ''; this.playerId = routeContext?.playerId ?? persistedContext?.playerId ?? 0;
this.sessionToken = routeContext?.token ?? persistedContext?.token ?? '';
const candidate = routeContext?.sessionCode || persistedContext?.sessionCode || '';
if (!candidate) { if (!candidate) {
return; return;
} }
@@ -155,9 +143,6 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
window.removeEventListener('offline', this.handleOffline); window.removeEventListener('offline', this.handleOffline);
} }
this.clearReconnectTimer(); this.clearReconnectTimer();
this.clearStateSyncTimer();
this.unsubscribeLocale?.();
this.unsubscribeLocale = null;
} }
private readonly handleOnline = (): void => { private readonly handleOnline = (): void => {
@@ -168,7 +153,6 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
private readonly handleOffline = (): void => { private readonly handleOffline = (): void => {
this.connectionState = 'offline'; this.connectionState = 'offline';
this.clearReconnectTimer(); this.clearReconnectTimer();
this.clearStateSyncTimer();
}; };
private clearReconnectTimer(): void { private clearReconnectTimer(): void {
@@ -178,52 +162,20 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
} }
} }
private clearStateSyncTimer(): void {
if (this.stateSyncTimer) {
clearTimeout(this.stateSyncTimer);
this.stateSyncTimer = null;
}
}
private scheduleStateSync(): void {
this.clearStateSyncTimer();
if (!this.sessionCode.trim() || this.connectionState !== 'online' || !this.session) {
return;
}
if (this.session.session.status === 'finished') {
return;
}
this.stateSyncTimer = setTimeout(() => {
this.stateSyncTimer = null;
if (this.loading || this.connectionState !== 'online') {
this.scheduleStateSync();
return;
}
void this.refreshSession();
}, 3000);
}
get loadingMessage(): string { get loadingMessage(): string {
switch (this.loadingTransition) { switch (this.loadingTransition) {
case 'join': case 'join':
return this.copy('player.loading_join'); return 'Joining session… restoring your player state.';
case 'submit-lie': case 'submit-lie':
return this.copy('player.loading_submit_lie'); return 'Submitting lie… waiting for guess phase.';
case 'submit-guess': case 'submit-guess':
return this.copy('player.loading_submit_guess'); return 'Submitting guess… waiting for reveal.';
case 'refresh': case 'refresh':
default: default:
return this.copy('player.loading_refresh'); return 'Loading latest session state…';
} }
} }
copy(key: string): string {
return t(key, this.locale);
}
private normalizeCode(value: string): string { private normalizeCode(value: string): string {
return value.trim().toUpperCase(); return value.trim().toUpperCase();
} }
@@ -238,12 +190,9 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
private markOnline(): void { private markOnline(): void {
this.connectionState = 'online'; this.connectionState = 'online';
this.clearReconnectTimer(); this.clearReconnectTimer();
this.scheduleStateSync();
} }
private markConnectionIssue(error: unknown): void { private markConnectionIssue(error: unknown): void {
this.clearStateSyncTimer();
if (typeof navigator !== 'undefined' && !navigator.onLine) { if (typeof navigator !== 'undefined' && !navigator.onLine) {
this.connectionState = 'offline'; this.connectionState = 'offline';
return; return;
@@ -284,7 +233,6 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
returnToJoin(): void { returnToJoin(): void {
this.loadingTransition = null; this.loadingTransition = null;
this.clearReconnectTimer(); this.clearReconnectTimer();
this.clearStateSyncTimer();
this.connectionState = typeof navigator !== 'undefined' && !navigator.onLine ? 'offline' : 'online'; this.connectionState = typeof navigator !== 'undefined' && !navigator.onLine ? 'offline' : 'online';
this.session = null; this.session = null;
this.finalLeaderboard = []; this.finalLeaderboard = [];
@@ -311,25 +259,6 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
}); });
} }
private syncRouteFromSession(): void {
if (!this.session) {
return;
}
const phase = this.session.session.status || 'lobby';
const code = this.normalizeCode(this.session.session.code || this.sessionCode);
if (!code) {
return;
}
const targetPath = `#/player/${encodeURIComponent(phase)}/${encodeURIComponent(code)}`;
if (typeof window === 'undefined' || window.location.hash === targetPath) {
return;
}
window.history.replaceState(window.history.state, '', targetPath);
}
private async request<T>(path: string, method: 'GET' | 'POST', payload?: unknown): Promise<T> { private async request<T>(path: string, method: 'GET' | 'POST', payload?: unknown): Promise<T> {
const response = await fetch(path, { const response = await fetch(path, {
method, method,
@@ -364,10 +293,9 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
this.selectedGuess = ''; this.selectedGuess = '';
} }
this.syncFinalLeaderboard(); this.syncFinalLeaderboard();
this.syncRouteFromSession();
this.markOnline(); this.markOnline();
} catch (error) { } catch (error) {
this.error = `${this.copy('player.session_refresh_failed')}: ${this.toMessage(error)}`; this.error = `Session refresh failed: ${this.toMessage(error)}`;
this.markConnectionIssue(error); this.markConnectionIssue(error);
} finally { } finally {
this.loading = false; this.loading = false;
@@ -394,10 +322,9 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
this.selectedGuess = ''; this.selectedGuess = '';
} }
this.syncFinalLeaderboard(); this.syncFinalLeaderboard();
this.syncRouteFromSession();
this.markOnline(); this.markOnline();
} catch (error) { } catch (error) {
this.error = `${this.copy('player.join_failed')}: ${this.toMessage(error)}`; this.error = `Join failed: ${this.toMessage(error)}`;
this.markConnectionIssue(error); this.markConnectionIssue(error);
} finally { } finally {
this.loading = false; this.loading = false;
@@ -425,7 +352,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
await this.refreshSession(); await this.refreshSession();
this.markOnline(); this.markOnline();
} catch (error) { } catch (error) {
this.submitError = { kind: 'lie', message: `${this.copy('player.lie_submit_failed')}: ${this.toMessage(error)}` }; this.submitError = { kind: 'lie', message: `Lie submit failed: ${this.toMessage(error)}` };
this.markConnectionIssue(error); this.markConnectionIssue(error);
} finally { } finally {
this.loading = false; this.loading = false;
@@ -453,7 +380,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
await this.refreshSession(); await this.refreshSession();
this.markOnline(); this.markOnline();
} catch (error) { } catch (error) {
this.submitError = { kind: 'guess', message: `${this.copy('player.guess_submit_failed')}: ${this.toMessage(error)}` }; this.submitError = { kind: 'guess', message: `Guess submit failed: ${this.toMessage(error)}` };
this.markConnectionIssue(error); this.markConnectionIssue(error);
} finally { } finally {
this.loading = false; this.loading = false;

View File

@@ -1,47 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
type StorageLike = {
getItem: (key: string) => string | null;
setItem: (key: string, value: string) => void;
};
function storageMock(initial: Record<string, string> = {}): StorageLike {
const data = new Map<string, string>(Object.entries(initial));
return {
getItem: vi.fn((key: string) => data.get(key) ?? null),
setItem: vi.fn((key: string, value: string) => {
data.set(key, value);
}),
};
}
describe('lobby i18n locale propagation', () => {
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
vi.resetModules();
});
it('notifies subscribers immediately and on locale changes', async () => {
const localStorage = storageMock({ 'wpp.locale': 'en' });
vi.stubGlobal('window', {
location: { search: '' },
localStorage,
});
vi.stubGlobal('navigator', { language: 'en-US' });
const i18n = await import('./lobby-i18n');
const updates: string[] = [];
const unsubscribe = i18n.subscribeToLocaleChanges((locale) => updates.push(locale));
expect(updates).toEqual(['en']);
i18n.setPreferredLocale('da');
expect(updates).toEqual(['en', 'da']);
unsubscribe();
i18n.setPreferredLocale('en');
expect(updates).toEqual(['en', 'da']);
});
});

View File

@@ -1,86 +0,0 @@
import lobbyCatalog from '../../../../shared/i18n/lobby.json';
type SupportedLocale = (typeof lobbyCatalog.locales.supported)[number];
const DEFAULT_LOCALE = lobbyCatalog.locales.default as SupportedLocale;
const SUPPORTED_LOCALES = lobbyCatalog.locales.supported as readonly SupportedLocale[];
let activeLocale: SupportedLocale | null = null;
const localeSubscribers = new Set<(locale: SupportedLocale) => void>();
export function normalizeLocale(rawLocale?: string | null): SupportedLocale {
const locale = (rawLocale ?? '').trim().toLowerCase();
if ((SUPPORTED_LOCALES as readonly string[]).includes(locale)) {
return locale as SupportedLocale;
}
const shortLocale = locale.split('-')[0] ?? '';
if ((SUPPORTED_LOCALES as readonly string[]).includes(shortLocale)) {
return shortLocale as SupportedLocale;
}
return DEFAULT_LOCALE;
}
export function resolvePreferredLocale(): SupportedLocale {
if (activeLocale) {
return activeLocale;
}
if (typeof window === 'undefined') {
activeLocale = DEFAULT_LOCALE;
return activeLocale;
}
const queryLocale = new URLSearchParams(window.location?.search ?? '').get('lang');
const storedLocale = window.localStorage?.getItem?.('wpp.locale');
const browserLocale = typeof navigator !== 'undefined' ? navigator.language : '';
activeLocale = normalizeLocale(queryLocale || storedLocale || browserLocale || DEFAULT_LOCALE);
return activeLocale;
}
export function setPreferredLocale(locale: string): SupportedLocale {
const normalized = normalizeLocale(locale);
activeLocale = normalized;
if (typeof window !== 'undefined') {
window.localStorage?.setItem?.('wpp.locale', normalized);
}
for (const subscriber of localeSubscribers) {
subscriber(normalized);
}
return normalized;
}
export function subscribeToLocaleChanges(callback: (locale: SupportedLocale) => void): () => void {
localeSubscribers.add(callback);
callback(resolvePreferredLocale());
return () => {
localeSubscribers.delete(callback);
};
}
export function t(key: string, locale: string): string {
const normalizedLocale = normalizeLocale(locale);
const fallbackLocale = DEFAULT_LOCALE;
const segments = key.split('.');
let cursor: unknown = lobbyCatalog.frontend.ui;
for (const segment of segments) {
if (!cursor || typeof cursor !== 'object' || !(segment in (cursor as Record<string, unknown>))) {
return key;
}
cursor = (cursor as Record<string, unknown>)[segment];
}
if (!cursor || typeof cursor !== 'object') {
return key;
}
const translations = cursor as Record<string, string>;
return translations[normalizedLocale] ?? translations[fallbackLocale] ?? key;
}
export const clientHasNoAudioOutput = Boolean(lobbyCatalog.frontend.capabilities.client_has_no_audio_output);

View File

@@ -1,12 +1,8 @@
import json import json
import logging
from functools import lru_cache from functools import lru_cache
from pathlib import Path from pathlib import Path
from django.http import HttpRequest, JsonResponse from django.http import JsonResponse
from django.utils.translation import get_language_from_request
LOGGER = logging.getLogger(__name__)
@lru_cache(maxsize=1) @lru_cache(maxsize=1)
@@ -16,55 +12,9 @@ def lobby_i18n_catalog() -> dict:
return json.load(handle) return json.load(handle)
@lru_cache(maxsize=1)
def i18n_locale_config() -> tuple[str, tuple[str, ...]]:
locales = lobby_i18n_catalog().get("locales", {})
default_locale = str(locales.get("default", "en")).strip().lower() or "en"
supported_locales = tuple(
locale.strip().lower() for locale in locales.get("supported", ["en", "da"]) if str(locale).strip()
) or ("en", "da")
return default_locale, supported_locales
def lobby_i18n_errors() -> dict: def lobby_i18n_errors() -> dict:
return lobby_i18n_catalog().get("backend", {}).get("error_codes", {}) return lobby_i18n_catalog().get("backend", {}).get("error_codes", {})
def lobby_i18n_error_messages() -> dict: def api_error(*, code: str, message: str, status: int) -> JsonResponse:
return lobby_i18n_catalog().get("backend", {}).get("errors", {}) return JsonResponse({"error": message, "error_code": code}, status=status)
def resolve_locale(request: HttpRequest) -> str:
default_locale, supported_locales = i18n_locale_config()
requested = (get_language_from_request(request) or "").split("-", 1)[0].lower()
if requested in supported_locales:
return requested
return default_locale
def resolve_error_message(*, key: str, locale: str) -> str:
default_locale, _supported_locales = i18n_locale_config()
translations = lobby_i18n_error_messages().get(key)
if not isinstance(translations, dict):
LOGGER.warning("i18n key missing in shared catalog", extra={"key": key, "locale": locale})
return key
if locale in translations and translations[locale]:
return translations[locale]
if default_locale in translations and translations[default_locale]:
return translations[default_locale]
LOGGER.warning("i18n translation missing for key", extra={"key": key, "locale": locale})
return key
def api_error(request: HttpRequest, *, key: str, status: int) -> JsonResponse:
locale = resolve_locale(request)
return JsonResponse(
{
"error": resolve_error_message(key=key, locale=locale),
"error_code": key,
"locale": locale,
},
status=status,
)

View File

@@ -19,7 +19,6 @@ from fupogfakta.models import (
RoundConfig, RoundConfig,
RoundQuestion, RoundQuestion,
) )
from lobby.i18n import resolve_error_message
User = get_user_model() User = get_user_model()
@@ -111,32 +110,6 @@ class LobbyFlowTests(TestCase):
self.assertEqual(response.status_code, 400) self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()["error"], "Session is not joinable") self.assertEqual(response.json()["error"], "Session is not joinable")
def test_join_error_localizes_to_danish_with_accept_language_header(self):
response = self.client.post(
reverse("lobby:join_session"),
data={"code": " ", "nickname": "Luna"},
content_type="application/json",
HTTP_ACCEPT_LANGUAGE="da",
)
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()["error_code"], "session_code_required")
self.assertEqual(response.json()["locale"], "da")
self.assertEqual(response.json()["error"], "Sessionskode er påkrævet")
def test_join_error_falls_back_to_english_for_unsupported_locale(self):
response = self.client.post(
reverse("lobby:join_session"),
data={"code": " ", "nickname": "Luna"},
content_type="application/json",
HTTP_ACCEPT_LANGUAGE="fr",
)
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()["error_code"], "session_code_required")
self.assertEqual(response.json()["locale"], "en")
self.assertEqual(response.json()["error"], "Session code is required")
def test_session_detail_returns_players(self): def test_session_detail_returns_players(self):
session = GameSession.objects.create(host=self.host, code="LMNO45") session = GameSession.objects.create(host=self.host, code="LMNO45")
Player.objects.create(session=session, nickname="Mia", score=7) Player.objects.create(session=session, nickname="Mia", score=7)
@@ -1201,8 +1174,3 @@ class SmokeStagingCommandTests(TestCase):
"finish_game", "finish_game",
], ],
) )
class I18nResolverTests(TestCase):
def test_missing_backend_key_returns_key_deterministically(self):
self.assertEqual(resolve_error_message(key="missing_key", locale="da"), "missing_key")

View File

@@ -128,15 +128,15 @@ def join_session(request: HttpRequest) -> JsonResponse:
if not code: if not code:
return api_error( return api_error(
request, code=ERROR_CODES.get("session_code_required", "session_code_required"),
key=ERROR_CODES.get("session_code_required", "session_code_required"), message="Session code is required",
status=400, status=400,
) )
if len(nickname) < 2 or len(nickname) > 40: if len(nickname) < 2 or len(nickname) > 40:
return api_error( return api_error(
request, code=ERROR_CODES.get("nickname_invalid", "nickname_invalid"),
key=ERROR_CODES.get("nickname_invalid", "nickname_invalid"), message="Nickname must be between 2 and 40 characters",
status=400, status=400,
) )
@@ -144,22 +144,22 @@ def join_session(request: HttpRequest) -> JsonResponse:
session = GameSession.objects.get(code=code) session = GameSession.objects.get(code=code)
except GameSession.DoesNotExist: except GameSession.DoesNotExist:
return api_error( return api_error(
request, code=ERROR_CODES.get("session_not_found", "session_not_found"),
key=ERROR_CODES.get("session_not_found", "session_not_found"), message="Session not found",
status=404, status=404,
) )
if session.status not in JOINABLE_STATUSES: if session.status not in JOINABLE_STATUSES:
return api_error( return api_error(
request, code=ERROR_CODES.get("session_not_joinable", "session_not_joinable"),
key=ERROR_CODES.get("session_not_joinable", "session_not_joinable"), message="Session is not joinable",
status=400, status=400,
) )
if Player.objects.filter(session=session, nickname__iexact=nickname).exists(): if Player.objects.filter(session=session, nickname__iexact=nickname).exists():
return api_error( return api_error(
request, code=ERROR_CODES.get("nickname_taken", "nickname_taken"),
key=ERROR_CODES.get("nickname_taken", "nickname_taken"), message="Nickname already taken",
status=409, status=409,
) )
@@ -190,8 +190,8 @@ def session_detail(request: HttpRequest, code: str) -> JsonResponse:
session = GameSession.objects.get(code=session_code) session = GameSession.objects.get(code=session_code)
except GameSession.DoesNotExist: except GameSession.DoesNotExist:
return api_error( return api_error(
request, code=ERROR_CODES.get("session_not_found", "session_not_found"),
key=ERROR_CODES.get("session_not_found", "session_not_found"), message="Session not found",
status=404, status=404,
) )
@@ -251,8 +251,8 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
if not category_slug: if not category_slug:
return api_error( return api_error(
request, code=ERROR_CODES.get("category_slug_required", "category_slug_required"),
key=ERROR_CODES.get("category_slug_required", "category_slug_required"), message="category_slug is required",
status=400, status=400,
) )
@@ -262,8 +262,8 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
session = GameSession.objects.get(code=session_code) session = GameSession.objects.get(code=session_code)
except GameSession.DoesNotExist: except GameSession.DoesNotExist:
return api_error( return api_error(
request, code=ERROR_CODES.get("session_not_found", "session_not_found"),
key=ERROR_CODES.get("session_not_found", "session_not_found"), message="Session not found",
status=404, status=404,
) )
@@ -272,8 +272,8 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
if session.status != GameSession.Status.LOBBY: if session.status != GameSession.Status.LOBBY:
return api_error( return api_error(
request, code=ERROR_CODES.get("round_start_invalid_phase", "round_start_invalid_phase"),
key=ERROR_CODES.get("round_start_invalid_phase", "round_start_invalid_phase"), message="Round can only be started from lobby",
status=400, status=400,
) )
@@ -281,8 +281,8 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
category = Category.objects.get(slug=category_slug, is_active=True) category = Category.objects.get(slug=category_slug, is_active=True)
except Category.DoesNotExist: except Category.DoesNotExist:
return api_error( return api_error(
request, code=ERROR_CODES.get("category_not_found", "category_not_found"),
key=ERROR_CODES.get("category_not_found", "category_not_found"), message="Category not found",
status=404, status=404,
) )
@@ -293,8 +293,8 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
session = GameSession.objects.select_for_update().get(pk=session.pk) session = GameSession.objects.select_for_update().get(pk=session.pk)
if session.status != GameSession.Status.LOBBY: if session.status != GameSession.Status.LOBBY:
return api_error( return api_error(
request, code=ERROR_CODES.get("round_start_invalid_phase", "round_start_invalid_phase"),
key=ERROR_CODES.get("round_start_invalid_phase", "round_start_invalid_phase"), message="Round can only be started from lobby",
status=400, status=400,
) )
@@ -305,8 +305,8 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
) )
if not created: if not created:
return api_error( return api_error(
request, code=ERROR_CODES.get("round_already_configured", "round_already_configured"),
key=ERROR_CODES.get("round_already_configured", "round_already_configured"), message="Round already configured",
status=409, status=409,
) )

View File

@@ -30,7 +30,6 @@ INSTALLED_APPS = [
MIDDLEWARE = [ MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware', 'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware', 'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',
@@ -90,12 +89,7 @@ AUTH_PASSWORD_VALIDATORS = [
{'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'}, {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
] ]
LANGUAGE_CODE = 'en' LANGUAGE_CODE = 'da'
LANGUAGES = [
('en', 'English'),
('da', 'Danish'),
]
LOCALE_PATHS = [BASE_DIR / 'locale']
TIME_ZONE = 'Europe/Copenhagen' TIME_ZONE = 'Europe/Copenhagen'
USE_I18N = True USE_I18N = True
USE_TZ = True USE_TZ = True

View File

@@ -1,266 +1,14 @@
{ {
"locales": {
"default": "en",
"supported": [
"en",
"da"
]
},
"frontend": { "frontend": {
"errors": { "errors": {
"session_code_required": { "session_code_required": "Session code is required.",
"en": "Session code is required.", "session_fetch_failed": "Could not load lobby status.",
"da": "Sessionskoden er påkrævet." "join_failed": "Join failed. Check code or nickname and try again.",
}, "start_round_failed": "Could not start round. Refresh the lobby and try again.",
"session_fetch_failed": { "session_not_found": "Session code is invalid or the session no longer exists.",
"en": "Could not load lobby status.", "nickname_invalid": "Nickname must be between 2 and 40 characters.",
"da": "Kunne ikke indlæse lobby-status." "nickname_taken": "Nickname is already taken.",
}, "unknown": "Action failed. Refresh status and try again."
"join_failed": {
"en": "Join failed. Check code or nickname and try again.",
"da": "Kunne ikke joine. Tjek kode eller kaldenavn og prøv igen."
},
"start_round_failed": {
"en": "Could not start round. Refresh the lobby and try again.",
"da": "Kunne ikke starte runden. Opdater lobbyen og prøv igen."
},
"session_not_found": {
"en": "Session code is invalid or the session no longer exists.",
"da": "Sessionskoden er ugyldig, eller sessionen findes ikke længere."
},
"nickname_invalid": {
"en": "Nickname must be between 2 and 40 characters.",
"da": "Kaldenavn skal være mellem 2 og 40 tegn."
},
"nickname_taken": {
"en": "Nickname is already taken.",
"da": "Kaldenavnet er allerede taget."
},
"unknown": {
"en": "Action failed. Refresh status and try again.",
"da": "Handlingen fejlede. Opdater status og prøv igen."
}
},
"ui": {
"common": {
"refresh": {
"en": "Refresh",
"da": "Opdatér"
},
"retry": {
"en": "Retry",
"da": "Prøv igen"
},
"back_to_join": {
"en": "Back to join",
"da": "Tilbage til join"
},
"session_code": {
"en": "Session code",
"da": "Sessionskode"
},
"status": {
"en": "Status",
"da": "Status"
},
"prompt": {
"en": "Prompt",
"da": "Spørgsmål"
},
"round_question_id": {
"en": "Round question id",
"da": "Rundespørgsmål-id"
},
"round": {
"en": "round",
"da": "runde"
}
},
"app": {
"title": {
"en": "WPP Angular Shell",
"da": "WPP Angular Shell"
},
"host_nav": {
"en": "Host",
"da": "Vært"
},
"player_nav": {
"en": "Player",
"da": "Spiller"
},
"language_label": {
"en": "Language",
"da": "Sprog"
}
},
"host": {
"title": {
"en": "Host gameplay flow",
"da": "Vært gameplay-flow"
},
"category": {
"en": "Category",
"da": "Kategori"
},
"start_round": {
"en": "Start round",
"da": "Start runde"
},
"show_question": {
"en": "Show question",
"da": "Vis spørgsmål"
},
"mix_answers": {
"en": "Mix answers → guess",
"da": "Bland svar → gæt"
},
"calculate_scores": {
"en": "Calculate scores → reveal",
"da": "Udregn score → afslør"
},
"load_scoreboard": {
"en": "Load scoreboard",
"da": "Hent scoreboard"
},
"start_next_round": {
"en": "Start next round",
"da": "Start næste runde"
},
"finish_game": {
"en": "Finish game",
"da": "Afslut spil"
},
"retry_scoreboard": {
"en": "Retry scoreboard",
"da": "Prøv scoreboard igen"
},
"retry_next_round": {
"en": "Retry next round",
"da": "Prøv næste runde igen"
},
"retry_finish": {
"en": "Retry finish game",
"da": "Prøv afslutning igen"
},
"session_refresh_failed": {
"en": "Session refresh failed",
"da": "Kunne ikke opdatere session"
},
"scoreboard_failed": {
"en": "Scoreboard failed",
"da": "Scoreboard fejlede"
},
"next_round_failed": {
"en": "Next round failed",
"da": "Næste runde fejlede"
},
"finish_game_failed": {
"en": "Finish game failed",
"da": "Afslutning fejlede"
},
"session_code_required": {
"en": "Session code is required",
"da": "Sessionskode er påkrævet"
},
"final_leaderboard": {
"en": "Final leaderboard",
"da": "Finale leaderboard"
},
"winner": {
"en": "Winner",
"da": "Vinder"
},
"audio_locale_hint": {
"en": "Host locale for audio references",
"da": "Værtens locale for lydreferencer"
}
},
"player": {
"title": {
"en": "Player gameplay flow",
"da": "Spiller gameplay-flow"
},
"nickname": {
"en": "Nickname",
"da": "Kaldenavn"
},
"join": {
"en": "Join",
"da": "Join"
},
"lie_label": {
"en": "Lie",
"da": "Løgn"
},
"submit_lie": {
"en": "Submit lie",
"da": "Send løgn"
},
"retry_lie_submit": {
"en": "Retry lie submit",
"da": "Prøv løgn igen"
},
"submit_guess": {
"en": "Submit guess",
"da": "Send gæt"
},
"retry_guess_submit": {
"en": "Retry guess submit",
"da": "Prøv gæt igen"
},
"final_leaderboard": {
"en": "Final leaderboard",
"da": "Finale leaderboard"
},
"reconnecting_text": {
"en": "Reconnecting… trying to refresh session state.",
"da": "Forbinder igen… prøver at opdatere session."
},
"offline_text": {
"en": "You are offline. Reconnect to continue gameplay.",
"da": "Du er offline. Forbind igen for at fortsætte."
},
"retry_now": {
"en": "Retry now",
"da": "Prøv nu"
},
"loading_refresh": {
"en": "Loading latest session state…",
"da": "Indlæser seneste session-status…"
},
"loading_join": {
"en": "Joining session… restoring your player state.",
"da": "Joiner session… gendanner spillerstatus."
},
"loading_submit_lie": {
"en": "Submitting lie… waiting for guess phase.",
"da": "Sender løgn… venter på gættefase."
},
"loading_submit_guess": {
"en": "Submitting guess… waiting for reveal.",
"da": "Sender gæt… venter på afsløring."
},
"session_refresh_failed": {
"en": "Session refresh failed",
"da": "Kunne ikke opdatere session"
},
"join_failed": {
"en": "Join failed",
"da": "Join fejlede"
},
"lie_submit_failed": {
"en": "Lie submit failed",
"da": "Løgn-fejl"
},
"guess_submit_failed": {
"en": "Guess submit failed",
"da": "Gætte-fejl"
}
}
},
"capabilities": {
"client_has_no_audio_output": true
} }
}, },
"backend": { "backend": {
@@ -274,44 +22,6 @@
"category_not_found": "category_not_found", "category_not_found": "category_not_found",
"round_start_invalid_phase": "round_start_invalid_phase", "round_start_invalid_phase": "round_start_invalid_phase",
"round_already_configured": "round_already_configured" "round_already_configured": "round_already_configured"
},
"errors": {
"session_code_required": {
"en": "Session code is required",
"da": "Sessionskode er påkrævet"
},
"nickname_invalid": {
"en": "Nickname must be between 2 and 40 characters",
"da": "Kaldenavn skal være mellem 2 og 40 tegn"
},
"session_not_found": {
"en": "Session not found",
"da": "Session blev ikke fundet"
},
"session_not_joinable": {
"en": "Session is not joinable",
"da": "Sessionen kan ikke joine nu"
},
"nickname_taken": {
"en": "Nickname already taken",
"da": "Kaldenavnet er allerede taget"
},
"category_slug_required": {
"en": "category_slug is required",
"da": "category_slug er påkrævet"
},
"category_not_found": {
"en": "Category not found",
"da": "Kategori blev ikke fundet"
},
"round_start_invalid_phase": {
"en": "Round can only be started from lobby",
"da": "Runden kan kun startes fra lobbyen"
},
"round_already_configured": {
"en": "Round already configured",
"da": "Runden er allerede konfigureret"
}
} }
} }
} }