1 Commits

Author SHA1 Message Date
62090d7e64 feat(spa): sync host/player hash routes with gameplay phase
All checks were successful
CI / test-and-quality (push) Successful in 1m53s
2026-03-01 17:59:07 +00:00
35 changed files with 254 additions and 1813 deletions

View File

@@ -31,14 +31,3 @@ jobs:
- name: Tests
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,48 +0,0 @@
# Shared i18n architecture (frontend + backend)
## Scope
Issue #175 requires one shared i18n contract for MVP host/player flows across frontend and backend.
## Source of truth
- Catalog: `shared/i18n/lobby.json`
- Locales:
- supported: `en`, `da`
- default/fallback: `en`
Both Angular (`frontend/angular/src/app/lobby-i18n.ts`) and Django (`lobby/i18n.py`) read from this catalog.
## Key naming convention
- Domain-first namespaces:
- `frontend.ui.common.*`
- `frontend.ui.host.*`
- `frontend.ui.player.*`
- `frontend.errors.*`
- `backend.errors.*`
- `backend.error_codes.*`
- UI lookup keys in Angular are shortened aliases mapped under `frontend.ui`, e.g.:
- `host.start_round`
- `player.submit_guess`
- `common.session_code`
- Backend API errors return stable code + localized message:
- `error_code` = machine-stable key from `backend.error_codes`
- `error` = localized message from `backend.errors`
- `locale` = resolved request locale
## Fallback model (robust)
1. Resolve requested locale (`Accept-Language` on backend, user/browser preference on frontend).
2. If locale unsupported -> use default `en`.
3. If key missing -> return key and log warning.
4. If locale translation missing for key -> fallback to `en` translation.
## Audio-routing policy
- Catalog capability: `frontend.capabilities.client_has_no_audio_output = true`
- Host/player clients expose this as a read-only capability flag.
- Policy: phone clients must not play audio directly; only primary/host output is allowed.
## Verification
- Backend tests: `lobby/tests.py` i18n coverage for locale selection + fallback + error-code/message matrix.
- Frontend smoke/e2e-level unit coverage:
- `frontend/angular/src/app/lobby-i18n.spec.ts`
- `frontend/angular/src/app/i18n-mvp-flow-smoke.spec.ts`
- `frontend/angular/src/app/features/host/host-shell.component.spec.ts`
- `frontend/angular/src/app/features/player/player-shell.component.spec.ts`

View File

@@ -1,35 +0,0 @@
# ISSUE-175 Artifact — shared i18n contract + MVP host/player flow
## Delivered
- Shared i18n contract is centralized in `shared/i18n/lobby.json` (da/en, default `en`, robust fallback).
- Frontend host/player MVP copy is read via shared keys (no hardcoded Danish strings in Angular MVP flow components).
- Backend error messages resolve from shared keyspace with locale-aware API payload (`error_code`, `error`, `locale`).
- Audio-routing policy is explicit and shared: `frontend.capabilities.client_has_no_audio_output=true`.
- Architecture + key naming documented in `docs/I18N_ARCHITECTURE.md`.
## Smoke / e2e evidence
### Backend locale + fallback
Command:
```bash
. .venv/bin/activate && python manage.py test \
lobby.tests.LobbyFlowTests.test_join_error_localizes_to_danish_with_accept_language_header \
lobby.tests.LobbyFlowTests.test_join_error_falls_back_to_english_for_unsupported_locale \
lobby.tests.I18nResolverTests
```
Result:
- PASS (7 tests)
- Confirms `da` localization and fallback to `en` for unsupported locale.
### Frontend host/player + language switch + audio policy
Command:
```bash
cd frontend/angular
npm test -- --run \
src/app/lobby-i18n.spec.ts \
src/app/i18n-mvp-flow-smoke.spec.ts \
src/app/features/host/host-shell.component.spec.ts \
src/app/features/player/player-shell.component.spec.ts
```
Result:
- PASS (22 tests)
- Includes smoke for host/player copy in **both en and da** and verifies primary-only audio policy flag (`clientHasNoAudioOutput=true`).

View File

@@ -1,47 +0,0 @@
# Issue #188 Artifact — SPA cutover hardening (asset versioning + rollback)
## Scope
Acceptance for `[READY][SPA][P11] Cutover hardening`:
1. Dokumenteret strategi for cache-busting/versionering af SPA assets i Django staticfiles/reverse proxy setup.
2. Konfigurerbar rollback-procedure for `USE_SPA_UI` (trin-for-trin, target <10 min).
3. Smoke-artefakt for både SPA on/off i samme release-vindue.
4. Ingen gameplay-ændringer.
## 1) Asset versioning/cache-busting strategi
Implementeret i SPA shell render-path:
- Konfiguration i `partyhub/settings.py`:
- `WPP_SPA_ASSET_BASE` (eksisterende)
- `WPP_SPA_ASSET_VERSION` (ny)
- `lobby/ui_views.py` injicerer `spa_asset_version` til template-context.
- `lobby/templates/lobby/spa_shell.html` appender `?v={{ spa_asset_version }}` på:
- `styles.css`
- `main.js`
Effekt:
- Ny release-version (fx SHA/tag) kan tvinge cache-miss i browser/proxy uden ændring af route.
- Rollback kan pege på tidligere stabil version-token med samme mekanisme.
## 2) Rollback playbook (`USE_SPA_UI`) — target <10 min
Dokumenteret i `docs/spa-cutover-flag.md`:
1. Sæt `USE_SPA_UI=false`.
2. Sæt `WPP_SPA_ASSET_VERSION` til sidste stabile release-token.
3. Deploy/reload app-processer.
4. Verificér legacy routes (`/lobby/ui/host` + `/lobby/ui/player`).
5. Kør hurtig smoke sanity.
6. Log trigger/timestamp/resultat i smoke artifact.
## 3) Smoke artifact for SPA OFF/ON i samme release-vindue
Dokumenteret i:
- `docs/UI_SMOKE.md` (sektion: "Samme release-vindue: SPA OFF + ON verifikation")
- `docs/STAGING_GAMEPLAY_SMOKE_ARTIFACT.md` (template udvidet med release-window check + `WPP_SPA_ASSET_VERSION`)
Krav:
- OFF-pass (legacy) og ON-pass (SPA) køres i samme deploy/release-vindue.
- Begge passes logges i samme artifact med UTC timestamps og version-token.
## Non-goals bekræftet
- Ingen gameplay-regler ændret.
- Ingen API-kontrakter ændret.
- Ingen UX-redesign; kun drift/cutover-hardening.

View File

@@ -1,57 +0,0 @@
# Issue #200 Artifact — SPA host→player phase sync (no reload)
## Scope
Acceptance for `[READY][SPA][P14] Gameplay MVP-del 5`:
1. Host handlinger (`start round` / `næste fase`) propagere korrekt til player-ruter i SPA.
2. Happy-path artefakt for én fuld faseovergang uden page reload.
3. Sync-fejl giver kontrolleret fallback/error state.
Afgrænsning overholdt: ingen nye spilregler og ingen redesign af backend event-model.
## Happy-path faseovergang (uden page reload)
Reference-flow i Angular shell:
1. **Host starter runde/fase**
- Host action kalder backend endpoint (`POST /lobby/sessions/:code/start` eller fase-endpoint)
- Host shell hydrerer session igen (`GET /lobby/sessions/:code`)
- Host route synkes via hash-rewrite i samme SPA shell:
- `#/host/<phase>/<CODE>`
- Implementeret i `HostShellComponent.syncRouteFromSession()`
2. **Player modtager ny fase via state sync**
- Player shell kører periodisk session-refresh (3s), uden hard reload
- Når `session.status` ændrer sig, synkes hash-route i samme SPA shell:
- `#/player/<phase>/<CODE>`
- Implementeret i `PlayerShellComponent.syncRouteFromSession()`
3. **Ingen page reload**
- Routing sker med `window.history.replaceState(...)`
- URL opdateres i eksisterende SPA instans (ingen template-hop, ingen full refresh)
## Kontrolleret fallback ved sync-fejl
Når player-sync fejler (netværk/fetch/session-refresh):
- UI går i kontrolleret connection-state:
- `reconnecting` ved online netværksfejl
- `offline` når browser rapporterer offline
- Fejl vises med retry/back-to-join handlinger
- Reconnect forsøges igen via timer (`scheduleReconnect`) uden at crashe shell
## Verifikation (tests)
Kørt i `frontend/angular` med Vitest:
- `src/app/features/host/host-shell.component.spec.ts`
- Verificerer host-faseflow og hash-route sync uden reload
- `src/app/features/player/player-shell.component.spec.ts`
- Verificerer periodisk player state sync + hash-route sync
- Verificerer reconnect/offline fallback ved sync-fejl
- `src/app/api-contract-smoke.spec.ts`
- `src/app/session-route-context.spec.ts`
Kommando:
```bash
npm test -- --reporter=dot
```
Resultat: **4/4 testfiler grønne, 22/22 tests bestået**.

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,35 +0,0 @@
# Issue #207 Artifact — da/en locale switch + audio routing (primary-only)
## Scope
Acceptance for `[READY][i18n][P19]`:
1. Verify one MVP host+player flow in both `en` and `da` locale context.
2. Verify controlled fallback to `en` when a locale key is missing.
3. Verify audio-routing policy is primary-only (client/player has no audio output).
No new feature behavior added — this is verification-only evidence.
## Smoke/e2e evidence (Angular shell test run)
Executed from `frontend/angular`:
```bash
npm test -- --reporter=dot src/app/lobby-i18n.spec.ts src/app/features/host/host-shell.component.spec.ts src/app/features/player/player-shell.component.spec.ts
```
Evidence covered by the run:
- `lobby-i18n.spec.ts`
- subscriber locale switch updates (`en -> da -> en`)
- controlled fallback where `da` key is removed during test and `en` copy is returned
- `clientHasNoAudioOutput === true` (primary-only audio routing)
- `host-shell.component.spec.ts`
- host actions and route sync in SPA (no reload)
- `player-shell.component.spec.ts`
- player session refresh/sync path and retry behavior
## Policy evidence
- Shared catalog capability: `shared/i18n/lobby.json`
- `frontend.capabilities.client_has_no_audio_output = true`
- Angular host/player shells bind this capability:
- `HostShellComponent.clientHasNoAudioOutput`
- `PlayerShellComponent.clientHasNoAudioOutput`
Conclusion: locale switching works in `da`/`en`, fallback resolves to `en` when locale key is intentionally missing, and client audio remains disabled by policy (`primary-only`).

View File

@@ -23,14 +23,11 @@ Formål: levere et lille, ensartet evidensformat for release-nær gameplay-smoke
- Active category/questions present: <yes/no>
- Participants: host + <N> players
- `USE_SPA_UI`: <on/off>
- `WPP_SPA_ASSET_VERSION`: <release-token/sha>
- UI route used:
- OFF (legacy): `/lobby/ui/host` + `/lobby/ui/player`
- ON (SPA shell): `/lobby/ui/host/<spa-path>` + `/lobby/ui/player`
#### Checks (PASS/FAIL)
0. Same release-window verification
- OFF + ON smoke kørt i samme release-vindue: <pass/fail>
1. Cutover route sanity
- Flag OFF serves legacy UI templates: <pass/fail>
- Flag ON serves SPA shell on expected path(s): <pass/fail>
@@ -42,19 +39,6 @@ Formål: levere et lille, ensartet evidensformat for release-nær gameplay-smoke
- next round transitions: <pass/fail>
- final leaderboard visible: <pass/fail>
#### Smoke-gate decision (før `USE_SPA_UI=true`)
- Gate status: <GREEN/RED>
- Gate criteria met:
- [ ] Cutover route sanity = PASS (OFF + ON)
- [ ] Full gameplay round = PASS
- [ ] Next-round/final leaderboard sanity = PASS
- [ ] Ingen nye blocker-regressioner i host/player flow
#### Rollback checkpoint
- Rollback required: <yes/no>
- Trigger reason (if yes): <kort trigger>
- Rollback done (`USE_SPA_UI=false`) verified: <yes/no>
#### Evidence pointers
- Command(s): `<exact command(s)>`
- UI notes/screenshots/log refs: <short refs>

View File

@@ -20,29 +20,4 @@
9. Host: Beregn score og Vis scoreboard.
10. Host: Næste runde eller Afslut spil.
## Smoke-gate (staging cutover)
`USE_SPA_UI` må kun aktiveres i staging når følgende er opfyldt:
- Cutover route sanity er PASS for både OFF (legacy) og ON (SPA shell).
- Én fuld gameplay-runde til scoreboard er PASS.
- Next-round/final leaderboard sanity er PASS.
- Ingen nye blocker-regressioner i host/player kerneflow.
## Samme release-vindue: SPA OFF + ON verifikation
Kør begge checks i samme release-vindue (samme deploy/artifact version):
1. **OFF-pass (legacy)**
- `USE_SPA_UI=false`
- Verificér legacy routes + fuld runde.
2. **ON-pass (SPA)**
- `USE_SPA_UI=true`
- Behold samme release artifact og kun toggl flag/version-token ved behov.
- Verificér SPA shell routes + fuld runde.
3. Dokumentér begge pass i samme smoke-artifact med UTC timestamps og `WPP_SPA_ASSET_VERSION`.
## Rollback check points
Skift straks tilbage til `USE_SPA_UI=false` hvis en gate fejler:
1. Verificér legacy routes (`/lobby/ui/host` + `/lobby/ui/player`) fungerer igen.
2. Log rollback trigger + kort repro i smoke artifact.
3. Opret/link blocker issue før nyt cutover-forsøg.
Resultat: En fuld runde kan køres uden rå API-kald fra terminal.

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

@@ -12,53 +12,6 @@ Sæt env var pr. miljø:
Backward compatibility under cutover:
- Hvis `USE_SPA_UI` ikke er sat, bruges `WPP_SPA_ENABLED` som fallback.
## Static asset versioning/cache-busting (hardening)
Formål: sikre at browser/proxy/CDN hurtigt henter ny SPA bundle i release-vinduet uden at kræve hard refresh.
- `WPP_SPA_ASSET_BASE` peger fortsat på build-output (`/static/frontend/angular/browser`).
- `WPP_SPA_ASSET_VERSION` injiceres i SPA shell URLs som query-param (`?v=<version>`).
- Anbefalet værdi for `WPP_SPA_ASSET_VERSION`: release-tag eller kort commit SHA.
- Ved rollback sættes `WPP_SPA_ASSET_VERSION` til den tidligere kendte stabile release-værdi.
Eksempel (staging/prod env):
```env
USE_SPA_UI=true
WPP_SPA_ASSET_BASE=/static/frontend/angular/browser
WPP_SPA_ASSET_VERSION=rel-2026-03-01-bb82357
```
## Staging rollout-checkliste (`USE_SPA_UI`)
1. **Baseline (flag OFF)**
- Bekræft at staging kører med `USE_SPA_UI=false`.
- Kør gameplay smoke på legacy routes (`/lobby/ui/host` + `/lobby/ui/player`).
2. **Smoke-gate før aktivering (skal være grøn)**
- Cutover route sanity = PASS for både OFF og ON checks.
- Full gameplay round (join/start/round/scoreboard) = PASS.
- Next-round/final leaderboard sanity = PASS.
- Ingen nye blocker-regressioner i host/player kerneflow.
3. **Kontrolleret aktivering i staging**
- Sæt `USE_SPA_UI=true` i staging miljøet.
- Kør smoke-flow igen med SPA-route-verifikation.
4. **Post-cutover dokumentation**
- Log evidens med commit/head SHA, UTC timestamp og gate-status.
## Rollback playbook (`USE_SPA_UI`) — mål: <10 min
Rollback til legacy (`USE_SPA_UI=false`) udføres straks hvis et checkpoint fejler:
- Forkert route/shell for valgt flag i cutover route sanity.
- Gameplay smoke kan ikke gennemføres til scoreboard/final leaderboard.
- Kritisk regression i host/player flow under smoke.
Trin-for-trin:
1. Sæt `USE_SPA_UI=false` i deploy-env.
2. Sæt `WPP_SPA_ASSET_VERSION` til sidste stabile release-token.
3. Deploy/reload app-processer.
4. Verificér legacy routes: `/lobby/ui/host` + `/lobby/ui/player`.
5. Kør hurtig smoke sanity (join/start/scoreboard path).
6. Log UTC tid, trigger, release-token og resultat i smoke artifact.
Target: rollback + sanity-verifikation inden for 10 minutter.
## Verifikation
- Flag OFF: `UiScreenTests.test_legacy_templates_are_used_when_spa_flag_is_off`
- Flag ON (host): `UiScreenTests.test_host_screen_can_render_angular_shell_when_feature_flag_enabled`

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__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__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">
<header class="shell__header">
<h1>{{ copy('app.title') }}</h1>
<h1>WPP Angular Shell</h1>
<nav>
<a routerLink="/host">{{ copy('app.host_nav') }}</a>
<a routerLink="/player">{{ copy('app.player_nav') }}</a>
<a routerLink="/host">Host</a>
<a routerLink="/player">Player</a>
</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>
<section class="shell__content" [attr.data-wpp-locale]="locale">
<section class="shell__content">
<router-outlet></router-outlet>
</section>
</main>

View File

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

View File

@@ -244,23 +244,4 @@ describe('HostShellComponent gameplay wiring', () => {
expect(component.nextRoundError).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 () => {
const fetchMock: FetchMock = vi.fn().mockResolvedValue(jsonResponse(200, sessionDetailPayload('guess', { roundQuestionId: 77 })));
vi.stubGlobal('fetch', fetchMock);
const replaceState = vi.fn();
vi.stubGlobal('window', {
location: { hash: '#/host/lobby/ABCD12' },
history: { state: null, replaceState },
sessionStorage: { getItem: vi.fn().mockReturnValue(null), setItem: vi.fn() },
});
const component = new HostShellComponent();
component.sessionCode = 'ABCD12';
await component.refreshSession();
expect(replaceState).toHaveBeenCalledWith(null, '', '#/host/guess/ABCD12');
});
});

View File

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

View File

@@ -198,30 +198,6 @@ describe('PlayerShellComponent gameplay wiring', () => {
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 () => {
vi.stubGlobal('navigator', { onLine: true });
@@ -233,8 +209,8 @@ describe('PlayerShellComponent gameplay wiring', () => {
await component.refreshSession();
expect(component.connectionState === 'reconnecting' || component.connectionState === 'online').toBe(true);
expect(component.error).toContain('Session refresh failed:');
expect(component.connectionState).toBe('reconnecting');
expect(component.error).toContain('Session refresh failed: Could not load lobby status.');
});
it('uses offline state when browser reports disconnected network', async () => {
@@ -319,35 +295,4 @@ describe('PlayerShellComponent gameplay wiring', () => {
expect(component.submitError).toBeNull();
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,13 @@
import { CommonModule } from '@angular/common';
import type { ActivatedRoute } from '@angular/router';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { createApiClient } from '../../../../../src/api/client';
import { createSessionContextStore } from '../../../../../src/spa/session-context-store';
import { createVerticalSliceController } from '../../../../../src/spa/vertical-slice';
import { clientHasNoAudioOutput, resolvePreferredLocale, subscribeToLocaleChanges, t } from '../../lobby-i18n';
import { syncHashRoute } from '../../gameplay-route-sync';
import type { RouteSessionContext } from '../../session-route-context';
interface SessionDetail {
session: { code: string; status: string; current_round: number };
@@ -28,35 +30,35 @@ function resolveLocalStorage(): Storage | undefined {
standalone: true,
imports: [CommonModule, FormsModule],
template: `
<h2>{{ copy('player.title') }}</h2>
<h2>Player SPA gameplay flow</h2>
<div class="panel" [attr.data-client-has-no-audio-output]="clientHasNoAudioOutput">
<label>{{ copy('common.session_code') }} <input [(ngModel)]="sessionCode" /></label>
<label>{{ copy('player.nickname') }} <input [(ngModel)]="nickname" /></label>
<button (click)="refreshSession()" [disabled]="loading">{{ copy('common.refresh') }}</button>
<button (click)="joinSession()" [disabled]="loading">{{ copy('player.join') }}</button>
<div class="panel">
<label>Session code <input [(ngModel)]="sessionCode" /></label>
<label>Nickname <input [(ngModel)]="nickname" /></label>
<button (click)="refreshSession()" [disabled]="loading">Refresh</button>
<button (click)="joinSession()" [disabled]="loading">Join</button>
</div>
<p *ngIf="connectionState === 'reconnecting'" class="error">
{{ copy('player.reconnecting_text') }}
<button type="button" (click)="retryReconnect()" [disabled]="loading">{{ copy('player.retry_now') }}</button>
<button type="button" (click)="returnToJoin()" [disabled]="loading">{{ copy('common.back_to_join') }}</button>
Reconnecting… trying to refresh session state.
<button type="button" (click)="retryReconnect()" [disabled]="loading">Retry now</button>
<button type="button" (click)="returnToJoin()" [disabled]="loading">Back to join</button>
</p>
<p *ngIf="connectionState === 'offline'" class="error">
{{ copy('player.offline_text') }}
<button type="button" (click)="retryReconnect()" [disabled]="loading">{{ copy('player.retry_now') }}</button>
<button type="button" (click)="returnToJoin()" [disabled]="loading">{{ copy('common.back_to_join') }}</button>
You are offline. Reconnect to continue gameplay.
<button type="button" (click)="retryReconnect()" [disabled]="loading">Retry now</button>
<button type="button" (click)="returnToJoin()" [disabled]="loading">Back to join</button>
</p>
<p *ngIf="loading" class="hint">{{ loadingMessage }}</p>
<div class="panel" *ngIf="session">
<p><strong>{{ copy('common.status') }}:</strong> {{ session.session.status }}</p>
<p *ngIf="session.round_question"><strong>{{ copy('common.prompt') }}:</strong> {{ session.round_question.prompt }}</p>
<p><strong>Status:</strong> {{ session.session.status }}</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>
<button (click)="submitLie()" [disabled]="loading || session.session.status !== 'lie'">{{ copy('player.submit_lie') }}</button>
<button *ngIf="submitError?.kind === 'lie'" (click)="submitLie()" [disabled]="loading">{{ copy('player.retry_lie_submit') }}</button>
<label>Løgn <input [(ngModel)]="lieText" [disabled]="loading || session.session.status !== 'lie'" /></label>
<button (click)="submitLie()" [disabled]="loading || session.session.status !== 'lie'">Submit lie</button>
<button *ngIf="submitError?.kind === 'lie'" (click)="submitLie()" [disabled]="loading">Retry lie submit</button>
<div class="answers" *ngIf="session.round_question?.answers?.length">
<button
@@ -70,11 +72,11 @@ function resolveLocalStorage(): Storage | undefined {
</button>
</div>
<button (click)="submitGuess()" [disabled]="loading || session.session.status !== 'guess' || !selectedGuess">{{ copy('player.submit_guess') }}</button>
<button *ngIf="submitError?.kind === 'guess'" (click)="submitGuess()" [disabled]="loading">{{ copy('player.retry_guess_submit') }}</button>
<button (click)="submitGuess()" [disabled]="loading || session.session.status !== 'guess' || !selectedGuess">Submit guess</button>
<button *ngIf="submitError?.kind === 'guess'" (click)="submitGuess()" [disabled]="loading">Retry guess submit</button>
<div *ngIf="session.session.status === 'finished' && finalLeaderboard.length">
<h3>{{ copy('player.final_leaderboard') }}</h3>
<h3>Final leaderboard</h3>
<ol>
<li *ngFor="let entry of finalLeaderboard">{{ entry.nickname }}: {{ entry.score }}</li>
</ol>
@@ -85,15 +87,12 @@ function resolveLocalStorage(): Storage | undefined {
<p *ngIf="submitError" class="error">{{ submitError.message }}</p>
<div class="panel" *ngIf="error || submitError">
<button type="button" (click)="retryReconnect()" [disabled]="loading">{{ copy('common.retry') }}</button>
<button type="button" (click)="returnToJoin()" [disabled]="loading">{{ copy('common.back_to_join') }}</button>
<button type="button" (click)="retryReconnect()" [disabled]="loading">Retry</button>
<button type="button" (click)="returnToJoin()" [disabled]="loading">Back to join</button>
</div>
`,
})
export class PlayerShellComponent implements OnInit, OnDestroy {
locale = resolvePreferredLocale();
readonly clientHasNoAudioOutput = clientHasNoAudioOutput;
sessionCode = '';
nickname = '';
playerId = 0;
@@ -111,10 +110,8 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
private readonly sessionContextStore = createSessionContextStore(resolveLocalStorage());
private readonly controller = createVerticalSliceController(createApiClient(), this.sessionContextStore);
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private stateSyncTimer: ReturnType<typeof setTimeout> | null = null;
private unsubscribeLocale: (() => void) | null = null;
constructor() {
constructor(private readonly route: Pick<ActivatedRoute, 'snapshot'> = { snapshot: { data: {} } as never }) {
if (typeof navigator !== 'undefined' && !navigator.onLine) {
this.connectionState = 'offline';
}
@@ -126,21 +123,13 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
}
ngOnInit(): void {
this.unsubscribeLocale = subscribeToLocaleChanges((locale) => {
this.locale = locale;
});
const hashRoute = window.location.hash.replace(/^#\/?/, '');
const match = hashRoute.match(/^player(?:\/[^/]+)?(?:\/([^/?#]+))?/i);
const codeFromRoute = match?.[1] ?? '';
const routeContext = this.route.snapshot.data['routeContext'] as RouteSessionContext | undefined;
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) {
return;
}
@@ -155,9 +144,6 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
window.removeEventListener('offline', this.handleOffline);
}
this.clearReconnectTimer();
this.clearStateSyncTimer();
this.unsubscribeLocale?.();
this.unsubscribeLocale = null;
}
private readonly handleOnline = (): void => {
@@ -168,7 +154,6 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
private readonly handleOffline = (): void => {
this.connectionState = 'offline';
this.clearReconnectTimer();
this.clearStateSyncTimer();
};
private clearReconnectTimer(): void {
@@ -178,52 +163,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 {
switch (this.loadingTransition) {
case 'join':
return this.copy('player.loading_join');
return 'Joining session… restoring your player state.';
case 'submit-lie':
return this.copy('player.loading_submit_lie');
return 'Submitting lie… waiting for guess phase.';
case 'submit-guess':
return this.copy('player.loading_submit_guess');
return 'Submitting guess… waiting for reveal.';
case 'refresh':
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 {
return value.trim().toUpperCase();
}
@@ -238,12 +191,9 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
private markOnline(): void {
this.connectionState = 'online';
this.clearReconnectTimer();
this.scheduleStateSync();
}
private markConnectionIssue(error: unknown): void {
this.clearStateSyncTimer();
if (typeof navigator !== 'undefined' && !navigator.onLine) {
this.connectionState = 'offline';
return;
@@ -284,7 +234,6 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
returnToJoin(): void {
this.loadingTransition = null;
this.clearReconnectTimer();
this.clearStateSyncTimer();
this.connectionState = typeof navigator !== 'undefined' && !navigator.onLine ? 'offline' : 'online';
this.session = null;
this.finalLeaderboard = [];
@@ -311,25 +260,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> {
const response = await fetch(path, {
method,
@@ -360,14 +290,16 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
}
this.session = state.session as SessionDetail;
this.sessionCode = this.session.session.code;
if (!syncHashRoute('player', this.session)) {
throw new Error(`Unsupported player phase status: ${this.session.session.status}`);
}
if (this.session.session.status !== 'guess') {
this.selectedGuess = '';
}
this.syncFinalLeaderboard();
this.syncRouteFromSession();
this.markOnline();
} catch (error) {
this.error = `${this.copy('player.session_refresh_failed')}: ${this.toMessage(error)}`;
this.error = `Session refresh failed: ${this.toMessage(error)}`;
this.markConnectionIssue(error);
} finally {
this.loading = false;
@@ -386,6 +318,9 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
}
this.session = state.session as SessionDetail;
this.sessionCode = this.session.session.code;
if (!syncHashRoute('player', this.session)) {
throw new Error(`Unsupported player phase status: ${this.session.session.status}`);
}
const sessionContext = this.sessionContextStore.get();
this.playerId = sessionContext?.playerId ?? 0;
@@ -394,10 +329,9 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
this.selectedGuess = '';
}
this.syncFinalLeaderboard();
this.syncRouteFromSession();
this.markOnline();
} catch (error) {
this.error = `${this.copy('player.join_failed')}: ${this.toMessage(error)}`;
this.error = `Join failed: ${this.toMessage(error)}`;
this.markConnectionIssue(error);
} finally {
this.loading = false;
@@ -425,7 +359,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
await this.refreshSession();
this.markOnline();
} 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);
} finally {
this.loading = false;
@@ -453,7 +387,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
await this.refreshSession();
this.markOnline();
} 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);
} finally {
this.loading = false;

View File

@@ -1,96 +0,0 @@
import { describe, expect, it } from 'vitest';
import { deriveGameplayPhase, transitionGameplayPhase } from '../../../src/spa/gameplay-phase-machine';
describe('gameplay phase machine sync guards', () => {
it('keeps explicit scoreboard status as scoreboard phase', () => {
const phase = deriveGameplayPhase({
session: {
code: 'ABCD12',
status: 'scoreboard',
host_id: 1,
current_round: 1,
players_count: 2,
},
round_question: null,
players: [],
phase_view_model: {
status: 'scoreboard',
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: false,
can_show_question: false,
can_mix_answers: false,
can_calculate_scores: false,
can_reveal_scoreboard: false,
can_start_next_round: true,
can_finish_game: true,
},
player: {
can_join: false,
can_submit_lie: false,
can_submit_guess: false,
can_view_final_result: false,
},
},
});
expect(phase).toBe('scoreboard');
});
it('maps finished status to scoreboard phase fallback', () => {
const phase = deriveGameplayPhase({
session: {
code: 'ABCD12',
status: 'finished',
host_id: 1,
current_round: 1,
players_count: 2,
},
round_question: null,
players: [],
phase_view_model: {
status: 'finished',
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: false,
can_show_question: false,
can_mix_answers: false,
can_calculate_scores: false,
can_reveal_scoreboard: false,
can_start_next_round: false,
can_finish_game: false,
},
player: {
can_join: false,
can_submit_lie: false,
can_submit_guess: false,
can_view_final_result: true,
},
},
});
expect(phase).toBe('scoreboard');
});
it('transitions reveal -> scoreboard on SCOREBOARD_READY', () => {
expect(transitionGameplayPhase('reveal', 'SCOREBOARD_READY')).toEqual({
phase: 'scoreboard',
changed: true,
});
});
});

View File

@@ -0,0 +1,29 @@
import { describe, expect, it, vi } from 'vitest';
import { syncHashRoute } from './gameplay-route-sync';
describe('gameplay route sync', () => {
it('maps host status to hash phase route with session context', () => {
vi.stubGlobal('window', {
location: { hash: '#/host/lobby/ABCD12' },
history: { replaceState: vi.fn() },
});
const ok = syncHashRoute('host', { session: { code: 'abcd12', status: 'guess' } });
expect(ok).toBe(true);
expect(window.history.replaceState).toHaveBeenCalledWith(null, '', '#/host/guess/ABCD12');
});
it('returns false for unsupported status to allow controlled fallback', () => {
vi.stubGlobal('window', {
location: { hash: '#/player/lobby/ABCD12' },
history: { replaceState: vi.fn() },
});
const ok = syncHashRoute('player', { session: { code: 'ABCD12', status: 'waiting' } });
expect(ok).toBe(false);
expect(window.history.replaceState).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,73 @@
import { deriveGameplayPhase } from '../../../src/spa/gameplay-phase-machine';
type ShellMode = 'host' | 'player';
interface SessionLike {
session: {
code: string;
status: string;
};
}
function normalizeCode(value: string): string {
return value.trim().toUpperCase();
}
function toRoutePhase(status: string): string | null {
if (status === 'lobby') {
return 'lobby';
}
const phase = deriveGameplayPhase({
session: { code: 'route-sync', status, host_id: null, current_round: 1, players_count: 0 },
players: [],
round_question: null,
phase_view_model: {
status,
round_number: 1,
players_count: 0,
constraints: {
min_players_to_start: 0,
max_players_mvp: 0,
min_players_reached: false,
max_players_allowed: false,
},
host: {
can_start_round: false,
can_show_question: false,
can_mix_answers: false,
can_calculate_scores: false,
can_reveal_scoreboard: false,
can_start_next_round: false,
can_finish_game: false,
},
player: {
can_join: false,
can_submit_lie: false,
can_submit_guess: false,
can_view_final_result: false,
},
},
});
return phase;
}
export function syncHashRoute(mode: ShellMode, session: SessionLike): boolean {
if (typeof window === 'undefined') {
return true;
}
const code = normalizeCode(session.session.code);
const phase = toRoutePhase(session.session.status);
if (!code || !phase) {
return false;
}
const nextHash = `#/${mode}/${phase}/${encodeURIComponent(code)}`;
if (window.location.hash !== nextHash) {
window.history.replaceState(null, '', nextHash);
}
return true;
}

View File

@@ -1,61 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { HostShellComponent } from './features/host/host-shell.component';
import { PlayerShellComponent } from './features/player/player-shell.component';
import { setPreferredLocale } from './lobby-i18n';
describe('i18n MVP flow smoke (host/player + audio policy)', () => {
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
it('resolves host/player copy in en and da from shared catalog', () => {
vi.stubGlobal('window', {
location: { hash: '', search: '' },
history: { state: null, replaceState: vi.fn() },
localStorage: { getItem: vi.fn().mockReturnValue('en'), setItem: vi.fn(), removeItem: vi.fn() },
sessionStorage: { getItem: vi.fn().mockReturnValue(null), setItem: vi.fn(), removeItem: vi.fn() },
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
});
vi.stubGlobal('navigator', { language: 'en-US', onLine: true });
const host = new HostShellComponent();
const player = new PlayerShellComponent();
host.ngOnInit();
player.ngOnInit();
expect(host.copy('host.start_round')).toBe('Start round');
expect(player.copy('player.submit_guess')).toBe('Submit guess');
setPreferredLocale('da');
expect(host.copy('host.start_round')).toBe('Start runde');
expect(player.copy('player.submit_guess')).toBe('Send gæt');
player.ngOnDestroy();
host.ngOnDestroy();
});
it('keeps audio routing policy primary-only (client has no audio output)', () => {
vi.stubGlobal('window', {
location: { hash: '', search: '' },
history: { state: null, replaceState: vi.fn() },
localStorage: { getItem: vi.fn().mockReturnValue('en'), setItem: vi.fn(), removeItem: vi.fn() },
sessionStorage: { getItem: vi.fn().mockReturnValue(null), setItem: vi.fn(), removeItem: vi.fn() },
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
});
vi.stubGlobal('navigator', { language: 'en-US', onLine: true });
const host = new HostShellComponent();
const player = new PlayerShellComponent();
expect(host.clientHasNoAudioOutput).toBe(true);
expect(player.clientHasNoAudioOutput).toBe(true);
player.ngOnDestroy();
host.ngOnDestroy();
});
});

View File

@@ -1,91 +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']);
});
it('falls back to default en translation when da key is intentionally missing', async () => {
vi.stubGlobal('window', {
location: { search: '' },
localStorage: storageMock({ 'wpp.locale': 'da' }),
});
vi.stubGlobal('navigator', { language: 'da-DK' });
const i18n = await import('./lobby-i18n');
const catalogModule = await import('../../../../shared/i18n/lobby.json');
const catalog = catalogModule.default as {
frontend: {
ui: {
common: {
refresh: {
en?: string;
da?: string;
};
};
};
};
};
const originalDa = catalog.frontend.ui.common.refresh.da;
catalog.frontend.ui.common.refresh.da = undefined;
try {
expect(i18n.t('common.refresh', 'da')).toBe(catalog.frontend.ui.common.refresh.en);
} finally {
catalog.frontend.ui.common.refresh.da = originalDa;
}
});
it('exposes primary-only audio routing policy to clients', async () => {
vi.stubGlobal('window', {
location: { search: '' },
localStorage: storageMock({ 'wpp.locale': 'en' }),
});
vi.stubGlobal('navigator', { language: 'en-US' });
const i18n = await import('./lobby-i18n');
expect(i18n.clientHasNoAudioOutput).toBe(true);
});
});

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

@@ -46,7 +46,7 @@ export function deriveGameplayPhase(session: SessionDetailResponse | null): Game
return null;
}
if (status === 'lie' || status === 'guess' || status === 'reveal' || status === 'scoreboard') {
if (status === 'lie' || status === 'guess' || status === 'reveal') {
return status;
}

View File

@@ -1,48 +1,31 @@
import lobbyCatalog from '../../../shared/i18n/lobby.json';
type FrontendErrorKey = keyof typeof lobbyCatalog.frontend.errors;
const frontendErrors = lobbyCatalog.frontend.errors;
const localeConfig = lobbyCatalog.locales;
type FrontendErrorKey = keyof typeof frontendErrors;
type SupportedLocale = (typeof localeConfig.supported)[number];
const apiErrorMap: Record<string, FrontendErrorKey> = {
session_code_required: 'session_code_required',
session_not_found: 'session_not_found',
nickname_invalid: 'nickname_invalid',
nickname_taken: 'nickname_taken'
};
function isFrontendErrorKey(value: string): value is FrontendErrorKey {
return value in frontendErrors;
export function lobbyMessage(key: FrontendErrorKey): string {
return frontendErrors[key] ?? frontendErrors.unknown;
}
function normalizeLocale(rawLocale?: string): SupportedLocale {
const requested = (rawLocale ?? '').trim().toLowerCase();
if (localeConfig.supported.includes(requested as SupportedLocale)) {
return requested as SupportedLocale;
}
return localeConfig.default;
}
export function lobbyMessage(key: FrontendErrorKey, locale?: string): string {
const resolvedLocale = normalizeLocale(locale);
const translations = frontendErrors[key] as Record<string, string>;
if (translations[resolvedLocale]) {
return translations[resolvedLocale];
}
if (translations[localeConfig.default]) {
return translations[localeConfig.default];
}
return key;
}
export function lobbyMessageFromApiPayload(payload: unknown, fallbackKey: FrontendErrorKey, locale?: string): string {
export function lobbyMessageFromApiPayload(payload: unknown, fallbackKey: FrontendErrorKey): string {
if (!payload || typeof payload !== 'object') {
return lobbyMessage(fallbackKey, locale);
return lobbyMessage(fallbackKey);
}
const record = payload as Record<string, unknown>;
const code = typeof record.error_code === 'string' ? record.error_code : '';
const payloadLocale = typeof record.locale === 'string' ? record.locale : locale;
if (!isFrontendErrorKey(code)) {
return lobbyMessage(fallbackKey, payloadLocale);
const mappedKey = apiErrorMap[code];
if (!mappedKey) {
return lobbyMessage(fallbackKey);
}
return lobbyMessage(code, payloadLocale);
return lobbyMessage(mappedKey);
}

View File

@@ -1,53 +0,0 @@
import { describe, expect, it } from 'vitest';
import lobbyCatalog from '../../shared/i18n/lobby.json';
import { lobbyMessage, lobbyMessageFromApiPayload } from '../src/spa/lobby-i18n';
describe('shared i18n keyspace contract', () => {
it('keeps en as default and da/en matrix for frontend error keys', () => {
expect(lobbyCatalog.locales.default).toBe('en');
expect(lobbyCatalog.locales.supported).toEqual(expect.arrayContaining(['en', 'da']));
for (const [key, translations] of Object.entries(lobbyCatalog.frontend.errors)) {
expect(translations.en, `${key} missing en`).toBeTruthy();
expect(translations.da, `${key} missing da`).toBeTruthy();
}
});
it('keeps backend error-code keyspace aligned with backend translations', () => {
for (const [code, key] of Object.entries(lobbyCatalog.backend.error_codes)) {
expect(code).toBe(key);
expect(lobbyCatalog.backend.errors[key as keyof typeof lobbyCatalog.backend.errors]).toBeDefined();
}
for (const [key, translations] of Object.entries(lobbyCatalog.backend.errors)) {
expect(translations.en, `${key} missing en`).toBeTruthy();
expect(translations.da, `${key} missing da`).toBeTruthy();
}
});
});
describe('lobbyMessage locale handling', () => {
it('uses english by default and falls back to default for unsupported locale', () => {
expect(lobbyMessage('session_code_required')).toBe('Session code is required.');
expect(lobbyMessage('session_code_required', 'fr')).toBe('Session code is required.');
});
it('resolves locale from api payload and maps known backend error codes directly', () => {
expect(
lobbyMessageFromApiPayload(
{ error_code: 'session_not_found', locale: 'da' },
'join_failed',
),
).toBe('Sessionskoden er ugyldig, eller sessionen findes ikke længere.');
});
it('falls back when backend error code has no frontend translation key', () => {
expect(
lobbyMessageFromApiPayload(
{ error_code: 'session_not_joinable', locale: 'da' },
'join_failed',
),
).toBe('Kunne ikke joine. Tjek kode eller kaldenavn og prøv igen.');
});
});

View File

@@ -1,12 +1,8 @@
import json
import logging
from functools import lru_cache
from pathlib import Path
from django.http import HttpRequest, JsonResponse
from django.utils.translation import get_language_from_request
LOGGER = logging.getLogger(__name__)
from django.http import JsonResponse
@lru_cache(maxsize=1)
@@ -16,55 +12,9 @@ def lobby_i18n_catalog() -> dict:
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:
return lobby_i18n_catalog().get("backend", {}).get("error_codes", {})
def lobby_i18n_error_messages() -> dict:
return lobby_i18n_catalog().get("backend", {}).get("errors", {})
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,
)
def api_error(*, code: str, message: str, status: int) -> JsonResponse:
return JsonResponse({"error": message, "error_code": code}, status=status)

View File

@@ -4,10 +4,10 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>WPP SPA Shell</title>
<link rel="stylesheet" href="{{ spa_asset_base }}/styles.css?v={{ spa_asset_version|urlencode }}">
<link rel="stylesheet" href="{{ spa_asset_base }}/styles.css">
</head>
<body data-wpp-shell-route="{{ shell_route }}" data-wpp-shell-kind="{{ shell_kind }}">
<app-root data-wpp-shell-route="{{ shell_route }}" data-wpp-shell-kind="{{ shell_kind }}">Indlæser Angular app-shell…</app-root>
<script type="module" src="{{ spa_asset_base }}/main.js?v={{ spa_asset_version|urlencode }}"></script>
<script type="module" src="{{ spa_asset_base }}/main.js"></script>
</body>
</html>

View File

@@ -2,7 +2,6 @@ import json
import tempfile
from datetime import timedelta
from pathlib import Path
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.core.management import call_command
@@ -20,7 +19,6 @@ from fupogfakta.models import (
RoundConfig,
RoundQuestion,
)
from lobby.i18n import i18n_locale_config, lobby_i18n_catalog, resolve_error_message
User = get_user_model()
@@ -112,32 +110,6 @@ class LobbyFlowTests(TestCase):
self.assertEqual(response.status_code, 400)
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):
session = GameSession.objects.create(host=self.host, code="LMNO45")
Player.objects.create(session=session, nickname="Mia", score=7)
@@ -1023,8 +995,7 @@ class UiScreenTests(TestCase):
self.assertContains(response, "<app-root")
self.assertContains(response, "data-wpp-shell-route=\"/host\"")
self.assertContains(response, "data-wpp-shell-kind=\"host\"")
self.assertContains(response, "/static/frontend/angular/browser/main.js?v=dev")
self.assertContains(response, "/static/frontend/angular/browser/styles.css?v=dev")
self.assertContains(response, "/static/frontend/angular/browser/main.js")
@override_settings(USE_SPA_UI=True)
def test_host_screen_deeplink_preserves_spa_path_when_feature_flag_enabled(self):
@@ -1058,17 +1029,7 @@ class UiScreenTests(TestCase):
self.assertContains(response, "<app-root")
self.assertContains(response, "data-wpp-shell-route=\"/player\"")
self.assertContains(response, "data-wpp-shell-kind=\"player\"")
self.assertContains(response, "/static/frontend/angular/browser/main.js?v=dev")
@override_settings(USE_SPA_UI=True, WPP_SPA_ASSET_VERSION="release-2026-03-01")
def test_spa_shell_uses_configured_asset_version_for_cache_busting(self):
self.client.login(username="host_ui", password="secret123")
response = self.client.get(reverse("lobby:host_screen"))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "/static/frontend/angular/browser/styles.css?v=release-2026-03-01")
self.assertContains(response, "/static/frontend/angular/browser/main.js?v=release-2026-03-01")
self.assertContains(response, "/static/frontend/angular/browser/main.js")
class SessionDetailRoundQuestionTests(TestCase):
@@ -1213,49 +1174,3 @@ class SmokeStagingCommandTests(TestCase):
"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")
def test_missing_backend_key_is_logged_with_context(self):
with self.assertLogs("lobby.i18n", level="WARNING") as logs:
result = resolve_error_message(key="missing_key", locale="da")
self.assertEqual(result, "missing_key")
self.assertTrue(any("i18n key missing in shared catalog" in entry for entry in logs.output))
def test_missing_locale_translation_falls_back_to_default_locale(self):
with patch(
"lobby.i18n.lobby_i18n_error_messages",
return_value={"session_code_required": {"en": "Session code is required"}},
):
self.assertEqual(
resolve_error_message(key="session_code_required", locale="da"),
"Session code is required",
)
def test_shared_catalog_uses_en_default_and_da_en_matrix(self):
default_locale, supported_locales = i18n_locale_config()
catalog = lobby_i18n_catalog()
self.assertEqual(default_locale, "en")
self.assertIn("en", supported_locales)
self.assertIn("da", supported_locales)
for key, translations in catalog["backend"]["errors"].items():
self.assertTrue(translations.get("en"), f"backend key {key} missing en")
self.assertTrue(translations.get("da"), f"backend key {key} missing da")
for key, translations in catalog["frontend"]["errors"].items():
self.assertTrue(translations.get("en"), f"frontend key {key} missing en")
self.assertTrue(translations.get("da"), f"frontend key {key} missing da")
def test_backend_error_codes_map_to_same_named_translation_keys(self):
catalog = lobby_i18n_catalog()
backend_errors = catalog["backend"]["errors"]
for code, key in catalog["backend"]["error_codes"].items():
self.assertEqual(code, key)
self.assertIn(key, backend_errors)

View File

@@ -16,7 +16,6 @@ def _render_spa_shell(request, shell_route: str, shell_kind: str):
"shell_route": shell_route,
"shell_kind": shell_kind,
"spa_asset_base": settings.WPP_SPA_ASSET_BASE,
"spa_asset_version": getattr(settings, "WPP_SPA_ASSET_VERSION", "dev"),
"lobby_i18n": lobby_i18n_catalog(),
},
)

View File

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

View File

@@ -30,7 +30,6 @@ INSTALLED_APPS = [
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
@@ -90,12 +89,7 @@ AUTH_PASSWORD_VALIDATORS = [
{'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]
LANGUAGE_CODE = 'en'
LANGUAGES = [
('en', 'English'),
('da', 'Danish'),
]
LOCALE_PATHS = [BASE_DIR / 'locale']
LANGUAGE_CODE = 'da'
TIME_ZONE = 'Europe/Copenhagen'
USE_I18N = True
USE_TZ = True
@@ -111,9 +105,6 @@ if USE_SPA_UI_RAW is None:
USE_SPA_UI_RAW = env('WPP_SPA_ENABLED', 'false')
USE_SPA_UI = USE_SPA_UI_RAW.lower() == 'true'
WPP_SPA_ASSET_BASE = env('WPP_SPA_ASSET_BASE', '/static/frontend/angular/browser').rstrip('/')
# Cache-busting token for SPA shell static asset URLs (querystring versioning).
# Set to release id / commit SHA in deploy env for deterministic invalidation.
WPP_SPA_ASSET_VERSION = env('WPP_SPA_ASSET_VERSION', 'dev')
CHANNEL_REDIS_HOST = env('CHANNEL_REDIS_HOST', '127.0.0.1')
CHANNEL_REDIS_PORT = int(env('CHANNEL_REDIS_PORT', '6379'))

View File

@@ -1,266 +1,14 @@
{
"locales": {
"default": "en",
"supported": [
"en",
"da"
]
},
"frontend": {
"errors": {
"session_code_required": {
"en": "Session code is required.",
"da": "Sessionskoden er påkrævet."
},
"session_fetch_failed": {
"en": "Could not load lobby status.",
"da": "Kunne ikke indlæse lobby-status."
},
"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
"session_code_required": "Session code is required.",
"session_fetch_failed": "Could not load lobby status.",
"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_not_found": "Session code is invalid or the session no longer exists.",
"nickname_invalid": "Nickname must be between 2 and 40 characters.",
"nickname_taken": "Nickname is already taken.",
"unknown": "Action failed. Refresh status and try again."
}
},
"backend": {
@@ -274,44 +22,6 @@
"category_not_found": "category_not_found",
"round_start_invalid_phase": "round_start_invalid_phase",
"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"
}
}
}
}
}