Compare commits
57 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5957660802 | |||
| 177574ae19 | |||
| d26d2b1a09 | |||
| c4850f2e0e | |||
| 60ce650653 | |||
| fb782432ea | |||
| 71c90109e4 | |||
| 7f42fa12c9 | |||
| 9a69110c7d | |||
| 82711dd537 | |||
| 8ed88c9762 | |||
| 8ba737be7f | |||
| f3ea19fcd7 | |||
| 386ac5b7c1 | |||
| 0e7bb1b041 | |||
| de5007943e | |||
| 634bd617e7 | |||
| 7cc1e4c17f | |||
| a20dcebe0a | |||
| 55e646651e | |||
| 3fc92c9ba0 | |||
| 0fb10f08c9 | |||
| fbfb948e99 | |||
| 25688cde79 | |||
| 3253f4d343 | |||
| c6aaef9d94 | |||
| a5c9e4f255 | |||
| 84c88e5627 | |||
| de4302622b | |||
| 70c9b71f99 | |||
| 89870f44ac | |||
| 2f6a21de9c | |||
| 176218c360 | |||
| 9e54aa0ab2 | |||
| 58f7f02af3 | |||
| c9c2ec23a2 | |||
| 749997a8fb | |||
| 85e970b90c | |||
| b52896d137 | |||
| b0aca04420 | |||
| 24a319fd8f | |||
| 093a928e6a | |||
| 538368de99 | |||
| cab5c47759 | |||
| 68325944c1 | |||
| d1e1ef0fde | |||
| 07a8c9568d | |||
| 4a6acd79c1 | |||
| b647db2048 | |||
| 29ef754389 | |||
| 702ab6b9ee | |||
| 7294ad409c | |||
| 2f142aeb24 | |||
| 84438b2880 | |||
| ea82f920b1 | |||
| 5bdbdbd837 | |||
| 7180cc9b0d |
@@ -0,0 +1,28 @@
|
|||||||
|
# Issue #180 Evidence — SPA next-round + final leaderboard
|
||||||
|
|
||||||
|
## Flow log (Angular SPA)
|
||||||
|
1. Host reaches `reveal` phase and runs `loadScoreboard()` (`GET /lobby/sessions/:code/scoreboard`).
|
||||||
|
2. Host can start next round directly in SPA via `startNextRound()` (`POST /lobby/sessions/:code/rounds/next`) and then session hydrate (`GET /lobby/sessions/:code`) without page reload.
|
||||||
|
3. Host can finish game directly in SPA via `finishGame()` (`POST /lobby/sessions/:code/finish`), rendering winner + sorted final leaderboard (plus raw payload for debug) in the same shell.
|
||||||
|
4. Player SPA renders final leaderboard from refreshed finished-session payload (sorted by score desc, nickname tiebreak) without leaving SPA route.
|
||||||
|
5. Error/retry paths are implemented and covered:
|
||||||
|
- scoreboard failure -> `scoreboardError` + retry button
|
||||||
|
- next-round failure -> `nextRoundError` + retry button
|
||||||
|
- finish-game/final-leaderboard failure -> `finishError` + retry button
|
||||||
|
|
||||||
|
## Test evidence
|
||||||
|
### `frontend/angular` (Vitest)
|
||||||
|
- `src/app/features/host/host-shell.component.spec.ts`
|
||||||
|
- `runs next-round transition without reload and clears scoreboard payload`
|
||||||
|
- `captures finish-game failure for retry and stores final leaderboard on success`
|
||||||
|
- `src/app/features/player/player-shell.component.spec.ts`
|
||||||
|
- `builds final leaderboard in finished status without legacy page hop`
|
||||||
|
|
||||||
|
Result:
|
||||||
|
- Test Files: 2 passed
|
||||||
|
- Tests: 9 passed
|
||||||
|
|
||||||
|
### `frontend` shared SPA tests (regression)
|
||||||
|
Result:
|
||||||
|
- Test Files: 5 passed
|
||||||
|
- Tests: 24 passed
|
||||||
@@ -22,13 +22,20 @@ Formål: levere et lille, ensartet evidensformat for release-nær gameplay-smoke
|
|||||||
- Host authenticated in Django admin: <yes/no>
|
- Host authenticated in Django admin: <yes/no>
|
||||||
- Active category/questions present: <yes/no>
|
- Active category/questions present: <yes/no>
|
||||||
- Participants: host + <N> players
|
- Participants: host + <N> players
|
||||||
|
- `USE_SPA_UI`: <on/off>
|
||||||
|
- 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)
|
#### Checks (PASS/FAIL)
|
||||||
1. Lobby -> join -> start
|
1. Cutover route sanity
|
||||||
|
- Flag OFF serves legacy UI templates: <pass/fail>
|
||||||
|
- Flag ON serves SPA shell on expected path(s): <pass/fail>
|
||||||
|
2. Lobby -> join -> start
|
||||||
- Mixed-case + whitespace session code accepted: <pass/fail>
|
- Mixed-case + whitespace session code accepted: <pass/fail>
|
||||||
2. One full round to scoreboard
|
3. One full round to scoreboard
|
||||||
- submit lie -> mix -> submit guess -> calculate score -> show scoreboard: <pass/fail>
|
- submit lie -> mix -> submit guess -> calculate score -> show scoreboard: <pass/fail>
|
||||||
3. Next-round + game-end sanity
|
4. Next-round + game-end sanity
|
||||||
- next round transitions: <pass/fail>
|
- next round transitions: <pass/fail>
|
||||||
- final leaderboard visible: <pass/fail>
|
- final leaderboard visible: <pass/fail>
|
||||||
|
|
||||||
|
|||||||
+14
-9
@@ -4,15 +4,20 @@
|
|||||||
- Host er logget ind i Django.
|
- Host er logget ind i Django.
|
||||||
- Mindst én aktiv kategori med spørgsmål findes.
|
- Mindst én aktiv kategori med spørgsmål findes.
|
||||||
|
|
||||||
|
## Cutover-forudsætning (`USE_SPA_UI`)
|
||||||
|
- `USE_SPA_UI=false` (default): brug legacy routes `/lobby/ui/host` + `/lobby/ui/player`.
|
||||||
|
- `USE_SPA_UI=true`: host må gerne testes på SPA deep-link route `/lobby/ui/host/<spa-path>` (fx `/lobby/ui/host/guess`), player på `/lobby/ui/player`.
|
||||||
|
|
||||||
## Flow
|
## Flow
|
||||||
1. Åbn host-siden på /lobby/ui/host og tryk Opret session.
|
1. Verificér cutover-route matcher valgt flag (legacy vs SPA shell).
|
||||||
2. Åbn player-siden i 3 faner/enheder på /lobby/ui/player.
|
2. Åbn host-siden og tryk Opret session.
|
||||||
3. Join alle spillere med sessionkode og nickname.
|
3. Åbn player-siden i 3 faner/enheder.
|
||||||
4. Host: vælg kategori, Start runde, Vis spørgsmål.
|
4. Join alle spillere med sessionkode og nickname.
|
||||||
5. Spillere: brug round_question_id og submit løgn.
|
5. Host: vælg kategori, Start runde, Vis spørgsmål.
|
||||||
6. Host: Mix svar.
|
6. Spillere: brug round_question_id og submit løgn.
|
||||||
7. Spillere: submit gæt.
|
7. Host: Mix svar.
|
||||||
8. Host: Beregn score og Vis scoreboard.
|
8. Spillere: submit gæt.
|
||||||
9. Host: Næste runde eller Afslut spil.
|
9. Host: Beregn score og Vis scoreboard.
|
||||||
|
10. Host: Næste runde eller Afslut spil.
|
||||||
|
|
||||||
Resultat: En fuld runde kan køres uden rå API-kald fra terminal.
|
Resultat: En fuld runde kan køres uden rå API-kald fra terminal.
|
||||||
|
|||||||
@@ -15,4 +15,6 @@ Backward compatibility under cutover:
|
|||||||
## Verifikation
|
## Verifikation
|
||||||
- Flag OFF: `UiScreenTests.test_legacy_templates_are_used_when_spa_flag_is_off`
|
- 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`
|
- Flag ON (host): `UiScreenTests.test_host_screen_can_render_angular_shell_when_feature_flag_enabled`
|
||||||
|
- Flag ON (host deep-link): `UiScreenTests.test_host_screen_deeplink_preserves_spa_path_when_feature_flag_enabled`
|
||||||
- Flag ON (player): `UiScreenTests.test_player_screen_can_render_angular_shell_when_feature_flag_enabled`
|
- Flag ON (player): `UiScreenTests.test_player_screen_can_render_angular_shell_when_feature_flag_enabled`
|
||||||
|
- Smoke-checkliste for cutover paths: `docs/STAGING_GAMEPLAY_SMOKE_ARTIFACT.md` + `docs/UI_SMOKE.md`
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
.angular/
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
{
|
||||||
|
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
|
||||||
|
"version": 1,
|
||||||
|
"projects": {
|
||||||
|
"wpp-angular-shell": {
|
||||||
|
"projectType": "application",
|
||||||
|
"root": "",
|
||||||
|
"sourceRoot": "src",
|
||||||
|
"prefix": "app",
|
||||||
|
"architect": {
|
||||||
|
"build": {
|
||||||
|
"builder": "@angular/build:application",
|
||||||
|
"options": {
|
||||||
|
"outputPath": "dist/wpp-angular-shell",
|
||||||
|
"index": "src/index.html",
|
||||||
|
"browser": "src/main.ts",
|
||||||
|
"polyfills": ["zone.js"],
|
||||||
|
"tsConfig": "tsconfig.app.json",
|
||||||
|
"assets": [],
|
||||||
|
"styles": ["src/styles.css"],
|
||||||
|
"outputHashing": "none"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"serve": {
|
||||||
|
"builder": "@angular/build:dev-server",
|
||||||
|
"options": {
|
||||||
|
"buildTarget": "wpp-angular-shell:build"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"cli": {
|
||||||
|
"analytics": false
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+8577
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,28 @@
|
|||||||
|
{
|
||||||
|
"name": "wpp-angular-shell",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"start": "ng serve",
|
||||||
|
"build": "ng build",
|
||||||
|
"test": "vitest run"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@angular/common": "^19.2.0",
|
||||||
|
"@angular/compiler": "^19.2.0",
|
||||||
|
"@angular/core": "^19.2.0",
|
||||||
|
"@angular/forms": "^19.2.0",
|
||||||
|
"@angular/platform-browser": "^19.2.0",
|
||||||
|
"@angular/router": "^19.2.0",
|
||||||
|
"rxjs": "~7.8.0",
|
||||||
|
"tslib": "^2.3.0",
|
||||||
|
"zone.js": "~0.15.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@angular/build": "^19.2.0",
|
||||||
|
"@angular/cli": "^19.2.0",
|
||||||
|
"@angular/compiler-cli": "^19.2.0",
|
||||||
|
"typescript": "~5.7.2",
|
||||||
|
"vitest": "^2.1.9"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
.shell { font-family: Arial, sans-serif; margin: 1rem; }
|
||||||
|
.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; }
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<main class="shell">
|
||||||
|
<header class="shell__header">
|
||||||
|
<h1>WPP Angular Shell</h1>
|
||||||
|
<nav>
|
||||||
|
<a routerLink="/host">Host</a>
|
||||||
|
<a routerLink="/player">Player</a>
|
||||||
|
</nav>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section class="shell__content">
|
||||||
|
<router-outlet></router-outlet>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { Component, inject } from '@angular/core';
|
||||||
|
import { Router, RouterLink, RouterOutlet } from '@angular/router';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-root',
|
||||||
|
standalone: true,
|
||||||
|
imports: [RouterOutlet, RouterLink],
|
||||||
|
templateUrl: './app.component.html',
|
||||||
|
styleUrl: './app.component.css',
|
||||||
|
})
|
||||||
|
export class AppComponent {
|
||||||
|
private readonly router = inject(Router);
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
const shellRoute = document.body.dataset['wppShellRoute'];
|
||||||
|
if (shellRoute?.startsWith('/host') || shellRoute?.startsWith('/player')) {
|
||||||
|
void this.router.navigateByUrl(shellRoute);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { ApplicationConfig } from '@angular/core';
|
||||||
|
import { provideRouter, withHashLocation } from '@angular/router';
|
||||||
|
import { routes } from './app.routes';
|
||||||
|
|
||||||
|
export const appConfig: ApplicationConfig = {
|
||||||
|
providers: [provideRouter(routes, withHashLocation())],
|
||||||
|
};
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { Routes } from '@angular/router';
|
||||||
|
|
||||||
|
import {
|
||||||
|
hostRouteContextResolver,
|
||||||
|
hostRouteGuard,
|
||||||
|
playerRouteContextResolver,
|
||||||
|
playerRouteGuard,
|
||||||
|
} from './session-route-context';
|
||||||
|
|
||||||
|
export const routes: Routes = [
|
||||||
|
{
|
||||||
|
path: 'host',
|
||||||
|
resolve: { routeContext: hostRouteContextResolver },
|
||||||
|
canActivate: [hostRouteGuard],
|
||||||
|
loadComponent: () => import('./features/host/host-shell.component').then((m) => m.HostShellComponent),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'host/:phase',
|
||||||
|
resolve: { routeContext: hostRouteContextResolver },
|
||||||
|
canActivate: [hostRouteGuard],
|
||||||
|
loadComponent: () => import('./features/host/host-shell.component').then((m) => m.HostShellComponent),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'host/:phase/:context',
|
||||||
|
resolve: { routeContext: hostRouteContextResolver },
|
||||||
|
canActivate: [hostRouteGuard],
|
||||||
|
loadComponent: () => import('./features/host/host-shell.component').then((m) => m.HostShellComponent),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'player',
|
||||||
|
resolve: { routeContext: playerRouteContextResolver },
|
||||||
|
canActivate: [playerRouteGuard],
|
||||||
|
loadComponent: () => import('./features/player/player-shell.component').then((m) => m.PlayerShellComponent),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'player/:phase',
|
||||||
|
resolve: { routeContext: playerRouteContextResolver },
|
||||||
|
canActivate: [playerRouteGuard],
|
||||||
|
loadComponent: () => import('./features/player/player-shell.component').then((m) => m.PlayerShellComponent),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'player/:phase/:context',
|
||||||
|
resolve: { routeContext: playerRouteContextResolver },
|
||||||
|
canActivate: [playerRouteGuard],
|
||||||
|
loadComponent: () => import('./features/player/player-shell.component').then((m) => m.PlayerShellComponent),
|
||||||
|
},
|
||||||
|
{ path: '', pathMatch: 'full', redirectTo: 'player' },
|
||||||
|
{ path: '**', redirectTo: 'player' },
|
||||||
|
];
|
||||||
@@ -0,0 +1,264 @@
|
|||||||
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
import { HostShellComponent } from './host-shell.component';
|
||||||
|
|
||||||
|
type FetchMock = ReturnType<typeof vi.fn>;
|
||||||
|
|
||||||
|
function jsonResponse(status: number, body: unknown) {
|
||||||
|
return {
|
||||||
|
ok: status >= 200 && status < 300,
|
||||||
|
status,
|
||||||
|
json: vi.fn().mockResolvedValue(body),
|
||||||
|
} as unknown as Response;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sessionDetailPayload(status: string, options?: { roundQuestionId?: number | null }) {
|
||||||
|
const roundQuestionId = options?.roundQuestionId ?? 41;
|
||||||
|
|
||||||
|
return {
|
||||||
|
session: {
|
||||||
|
code: 'ABCD12',
|
||||||
|
status,
|
||||||
|
host_id: 1,
|
||||||
|
current_round: status === 'lobby' ? 2 : 1,
|
||||||
|
players_count: 2,
|
||||||
|
},
|
||||||
|
round_question:
|
||||||
|
roundQuestionId === null
|
||||||
|
? null
|
||||||
|
: {
|
||||||
|
id: roundQuestionId,
|
||||||
|
round_number: 1,
|
||||||
|
prompt: 'Q?',
|
||||||
|
shown_at: '2026-01-01T00:00:00Z',
|
||||||
|
answers: [],
|
||||||
|
},
|
||||||
|
players: [
|
||||||
|
{ id: 1, nickname: 'Host', score: 0, is_connected: true },
|
||||||
|
{ id: 2, nickname: 'Mads', score: 120, is_connected: true },
|
||||||
|
],
|
||||||
|
phase_view_model: {
|
||||||
|
status,
|
||||||
|
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: status === 'lobby',
|
||||||
|
can_show_question: status === 'lie',
|
||||||
|
can_mix_answers: status === 'lie',
|
||||||
|
can_calculate_scores: status === 'guess',
|
||||||
|
can_reveal_scoreboard: status === 'reveal',
|
||||||
|
can_start_next_round: status === 'scoreboard',
|
||||||
|
can_finish_game: status === 'scoreboard',
|
||||||
|
},
|
||||||
|
player: {
|
||||||
|
can_join: status === 'lobby',
|
||||||
|
can_submit_lie: status === 'lie',
|
||||||
|
can_submit_guess: status === 'guess',
|
||||||
|
can_view_final_result: status === 'finished',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('HostShellComponent gameplay wiring', () => {
|
||||||
|
afterEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('runs startRound transition and refreshes session details', async () => {
|
||||||
|
const fetchMock: FetchMock = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
jsonResponse(201, {
|
||||||
|
session: { code: 'ABCD12', status: 'lie', current_round: 1 },
|
||||||
|
round: { number: 1, category: { slug: 'history', name: 'History' } },
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.mockResolvedValueOnce(jsonResponse(200, sessionDetailPayload('lie')));
|
||||||
|
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
|
||||||
|
const component = new HostShellComponent();
|
||||||
|
component.sessionCode = ' abcd12 ';
|
||||||
|
component.categorySlug = ' history ';
|
||||||
|
|
||||||
|
await component.startRound();
|
||||||
|
|
||||||
|
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||||
|
1,
|
||||||
|
'/lobby/sessions/ABCD12/rounds/start',
|
||||||
|
expect.objectContaining({ method: 'POST', body: JSON.stringify({ category_slug: 'history' }) })
|
||||||
|
);
|
||||||
|
expect(fetchMock).toHaveBeenNthCalledWith(2, '/lobby/sessions/ABCD12', expect.objectContaining({ method: 'GET' }));
|
||||||
|
expect(component.session?.session.status).toBe('lie');
|
||||||
|
expect(component.roundQuestionId).toBe('41');
|
||||||
|
expect(component.loading).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('captures scoreboard error for retry path', async () => {
|
||||||
|
const fetchMock: FetchMock = vi.fn().mockResolvedValue(jsonResponse(500, { error: 'Scoreboard unavailable' }));
|
||||||
|
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
|
||||||
|
const component = new HostShellComponent();
|
||||||
|
component.sessionCode = 'ABCD12';
|
||||||
|
|
||||||
|
await component.loadScoreboard();
|
||||||
|
|
||||||
|
expect(fetchMock).toHaveBeenCalledWith('/lobby/sessions/ABCD12/scoreboard', expect.objectContaining({ method: 'GET' }));
|
||||||
|
expect(component.scoreboardError).toContain('Scoreboard failed: Scoreboard unavailable');
|
||||||
|
expect(component.loading).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('wires showQuestion, mixAnswers and calculateScores with expected request payloads', async () => {
|
||||||
|
const fetchMock: FetchMock = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
jsonResponse(200, {
|
||||||
|
round_question: {
|
||||||
|
id: 77,
|
||||||
|
round_number: 1,
|
||||||
|
prompt: 'Q?',
|
||||||
|
shown_at: '2026-01-01T00:00:00Z',
|
||||||
|
lie_deadline_at: '2026-01-01T00:00:45Z',
|
||||||
|
},
|
||||||
|
config: { lie_seconds: 45 },
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.mockResolvedValueOnce(jsonResponse(200, sessionDetailPayload('lie', { roundQuestionId: 77 })))
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
jsonResponse(200, {
|
||||||
|
session: { code: 'ABCD12', status: 'guess', current_round: 1 },
|
||||||
|
round_question: { id: 77, round_number: 1 },
|
||||||
|
answers: [{ text: 'A' }],
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.mockResolvedValueOnce(jsonResponse(200, sessionDetailPayload('guess', { roundQuestionId: 77 })))
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
jsonResponse(200, {
|
||||||
|
session: { code: 'ABCD12', status: 'reveal', current_round: 1 },
|
||||||
|
round_question: { id: 77, round_number: 1 },
|
||||||
|
events_created: 2,
|
||||||
|
leaderboard: [{ id: 1, nickname: 'Luna', score: 320 }],
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.mockResolvedValueOnce(jsonResponse(200, sessionDetailPayload('reveal', { roundQuestionId: 77 })));
|
||||||
|
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
|
||||||
|
const component = new HostShellComponent();
|
||||||
|
component.sessionCode = ' abcd12 ';
|
||||||
|
component.roundQuestionId = ' 77 ';
|
||||||
|
|
||||||
|
await component.showQuestion();
|
||||||
|
await component.mixAnswers();
|
||||||
|
await component.calculateScores();
|
||||||
|
|
||||||
|
expect(component.error).toBe('');
|
||||||
|
expect(component.loading).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('runs next-round transition without reload and clears scoreboard payload', async () => {
|
||||||
|
const fetchMock: FetchMock = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(jsonResponse(200, { session: { code: 'ABCD12', status: 'lobby', current_round: 2 } }))
|
||||||
|
.mockResolvedValueOnce(jsonResponse(200, sessionDetailPayload('lobby', { roundQuestionId: null })));
|
||||||
|
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
|
||||||
|
const component = new HostShellComponent();
|
||||||
|
component.sessionCode = ' abcd12 ';
|
||||||
|
component.scoreboardPayload = '{"leaderboard":[]}';
|
||||||
|
component.finalLeaderboardPayload = '{"leaderboard":[{"nickname":"Old","score":1}]}' ;
|
||||||
|
component.finalLeaderboard = [{ id: 9, nickname: 'Old', score: 1 }];
|
||||||
|
|
||||||
|
await component.startNextRound();
|
||||||
|
|
||||||
|
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||||
|
1,
|
||||||
|
'/lobby/sessions/ABCD12/rounds/next',
|
||||||
|
expect.objectContaining({ method: 'POST', body: JSON.stringify({}) })
|
||||||
|
);
|
||||||
|
expect(fetchMock).toHaveBeenNthCalledWith(2, '/lobby/sessions/ABCD12', expect.objectContaining({ method: 'GET' }));
|
||||||
|
expect(component.session?.session.status).toBe('lobby');
|
||||||
|
expect(component.scoreboardPayload).toBe('');
|
||||||
|
expect(component.finalLeaderboardPayload).toBe('');
|
||||||
|
expect(component.finalLeaderboard).toEqual([]);
|
||||||
|
expect(component.nextRoundError).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('captures finish-game failure for retry and stores final leaderboard on success', async () => {
|
||||||
|
const fetchMock: FetchMock = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(jsonResponse(503, { error: 'Final leaderboard timeout' }))
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
jsonResponse(200, {
|
||||||
|
session: { code: 'ABCD12', status: 'finished', current_round: 2 },
|
||||||
|
winner: { id: 1, nickname: 'Luna', score: 320 },
|
||||||
|
leaderboard: [
|
||||||
|
{ id: 2, nickname: 'Mads', score: 120 },
|
||||||
|
{ id: 1, nickname: 'Luna', score: 320 },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.mockResolvedValueOnce(jsonResponse(200, sessionDetailPayload('finished', { roundQuestionId: null })));
|
||||||
|
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
|
||||||
|
const component = new HostShellComponent();
|
||||||
|
component.sessionCode = 'ABCD12';
|
||||||
|
|
||||||
|
await component.finishGame();
|
||||||
|
expect(component.finishError).toContain('Finish game failed: Final leaderboard timeout');
|
||||||
|
|
||||||
|
await component.finishGame();
|
||||||
|
|
||||||
|
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||||
|
2,
|
||||||
|
'/lobby/sessions/ABCD12/finish',
|
||||||
|
expect.objectContaining({ method: 'POST', body: JSON.stringify({}) })
|
||||||
|
);
|
||||||
|
expect(component.finishError).toBe('');
|
||||||
|
expect(component.finalLeaderboardPayload).toContain('"status": "finished"');
|
||||||
|
expect(component.finalWinner?.nickname).toBe('Luna');
|
||||||
|
expect(component.finalLeaderboard.map((entry) => entry.nickname)).toEqual(['Luna', 'Mads']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('guards next-round and finish actions when session code is missing', async () => {
|
||||||
|
const fetchMock: FetchMock = vi.fn();
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
|
||||||
|
const component = new HostShellComponent();
|
||||||
|
component.sessionCode = ' ';
|
||||||
|
|
||||||
|
await component.startNextRound();
|
||||||
|
await component.finishGame();
|
||||||
|
|
||||||
|
expect(fetchMock).not.toHaveBeenCalled();
|
||||||
|
expect(component.nextRoundError).toContain('Session code is required');
|
||||||
|
expect(component.finishError).toContain('Session code is required');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('bootstraps refresh from resolver route context on init', () => {
|
||||||
|
vi.stubGlobal('window', {
|
||||||
|
sessionStorage: {
|
||||||
|
getItem: vi.fn().mockReturnValue(null),
|
||||||
|
setItem: vi.fn(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const component = new HostShellComponent({ snapshot: { data: { routeContext: { sessionCode: 'ab12' } } } } as never);
|
||||||
|
const refreshSpy = vi.spyOn(component, 'refreshSession').mockResolvedValue();
|
||||||
|
|
||||||
|
component.ngOnInit();
|
||||||
|
|
||||||
|
expect(component.sessionCode).toBe('AB12');
|
||||||
|
expect(refreshSpy).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component, OnInit, Optional } from '@angular/core';
|
||||||
|
import { ActivatedRoute } from '@angular/router';
|
||||||
|
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 type { RouteSessionContext } from '../../session-route-context';
|
||||||
|
|
||||||
|
interface SessionDetail {
|
||||||
|
session: { code: string; status: string; current_round: number };
|
||||||
|
round_question: { id: number; prompt: string; answers: Array<{ text: string }> } | null;
|
||||||
|
players: Array<{ id: number; nickname: string; score: number }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
type LeaderboardEntry = ScoreboardResponse['leaderboard'][number];
|
||||||
|
type LeaderboardResponse = FinishGameResponse;
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-host-shell',
|
||||||
|
standalone: true,
|
||||||
|
imports: [CommonModule, FormsModule],
|
||||||
|
template: `
|
||||||
|
<h2>Host SPA gameplay flow</h2>
|
||||||
|
|
||||||
|
<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="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>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>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>
|
||||||
|
</div>
|
||||||
|
<pre *ngIf="finalLeaderboardPayload">{{ finalLeaderboardPayload }}</pre>
|
||||||
|
</div>
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class HostShellComponent implements OnInit {
|
||||||
|
sessionCode = '';
|
||||||
|
categorySlug = 'general';
|
||||||
|
roundQuestionId = '';
|
||||||
|
loading = false;
|
||||||
|
error = '';
|
||||||
|
scoreboardError = '';
|
||||||
|
nextRoundError = '';
|
||||||
|
finishError = '';
|
||||||
|
scoreboardPayload = '';
|
||||||
|
finalLeaderboardPayload = '';
|
||||||
|
finalLeaderboard: LeaderboardEntry[] = [];
|
||||||
|
finalWinner: LeaderboardEntry | null = null;
|
||||||
|
session: SessionDetail | null = null;
|
||||||
|
|
||||||
|
private readonly api = createApiClient();
|
||||||
|
private readonly controller = createVerticalSliceController(this.api);
|
||||||
|
|
||||||
|
constructor(@Optional() private readonly route: ActivatedRoute | null = null) {}
|
||||||
|
|
||||||
|
ngOnInit(): void {
|
||||||
|
if (typeof window === 'undefined') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
if (!candidate) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.sessionCode = this.normalizeCode(candidate);
|
||||||
|
this.persistSessionCode(this.sessionCode);
|
||||||
|
void this.refreshSession();
|
||||||
|
}
|
||||||
|
|
||||||
|
private normalizeCode(value: string): string {
|
||||||
|
return value.trim().toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
private persistSessionCode(code: string): void {
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
window.sessionStorage.setItem('wpp.host-session-code', code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async request<T>(path: string, method: 'GET' | 'POST', payload?: unknown): Promise<T> {
|
||||||
|
const response = await fetch(path, {
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
Accept: 'application/json',
|
||||||
|
...(payload === undefined ? {} : { 'Content-Type': 'application/json' }),
|
||||||
|
},
|
||||||
|
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
|
||||||
|
credentials: 'same-origin',
|
||||||
|
});
|
||||||
|
|
||||||
|
const body = await response.json().catch(() => ({}));
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error((body as { error?: string }).error ?? `HTTP ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return body as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
async refreshSession(): Promise<void> {
|
||||||
|
this.loading = true;
|
||||||
|
this.error = '';
|
||||||
|
this.scoreboardError = '';
|
||||||
|
this.nextRoundError = '';
|
||||||
|
this.finishError = '';
|
||||||
|
try {
|
||||||
|
const state = await this.controller.hydrateLobby(this.sessionCode);
|
||||||
|
if (!state.session || state.errorMessage) {
|
||||||
|
throw new Error(state.errorMessage ?? 'Unknown error');
|
||||||
|
}
|
||||||
|
this.session = state.session as SessionDetail;
|
||||||
|
this.sessionCode = this.session.session.code;
|
||||||
|
this.persistSessionCode(this.sessionCode);
|
||||||
|
this.roundQuestionId = this.session.round_question?.id ? String(this.session.round_question.id) : '';
|
||||||
|
if (this.session.session.status !== 'finished') {
|
||||||
|
this.resetFinalLeaderboard();
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
this.error = `Session refresh failed: ${(error as Error).message}`;
|
||||||
|
} finally {
|
||||||
|
this.loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async startRound(): Promise<void> {
|
||||||
|
await this.runAction(async () => {
|
||||||
|
const state = await this.controller.startRound(this.sessionCode, this.categorySlug.trim());
|
||||||
|
if (!state.session || state.errorMessage) {
|
||||||
|
throw new Error(state.errorMessage ?? 'Unknown error');
|
||||||
|
}
|
||||||
|
this.session = state.session as SessionDetail;
|
||||||
|
this.sessionCode = this.session.session.code;
|
||||||
|
this.persistSessionCode(this.sessionCode);
|
||||||
|
this.roundQuestionId = this.session.round_question?.id ? String(this.session.round_question.id) : '';
|
||||||
|
this.scoreboardPayload = '';
|
||||||
|
this.resetFinalLeaderboard();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async showQuestion(): Promise<void> {
|
||||||
|
await this.runAction(async () => {
|
||||||
|
const code = this.normalizeCode(this.sessionCode);
|
||||||
|
await this.request(`/lobby/sessions/${encodeURIComponent(code)}/questions/show`, 'POST', {});
|
||||||
|
await this.refreshSession();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async mixAnswers(): Promise<void> {
|
||||||
|
await this.runAction(async () => {
|
||||||
|
const code = this.normalizeCode(this.sessionCode);
|
||||||
|
const roundQuestionId = this.roundQuestionId.trim();
|
||||||
|
await this.request(`/lobby/sessions/${encodeURIComponent(code)}/questions/${roundQuestionId}/answers/mix`, 'POST', {});
|
||||||
|
await this.refreshSession();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async calculateScores(): Promise<void> {
|
||||||
|
await this.runAction(async () => {
|
||||||
|
const code = this.normalizeCode(this.sessionCode);
|
||||||
|
const roundQuestionId = this.roundQuestionId.trim();
|
||||||
|
await this.request(`/lobby/sessions/${encodeURIComponent(code)}/questions/${roundQuestionId}/scores/calculate`, 'POST', {});
|
||||||
|
await this.refreshSession();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async loadScoreboard(): Promise<void> {
|
||||||
|
this.loading = true;
|
||||||
|
this.scoreboardError = '';
|
||||||
|
this.error = '';
|
||||||
|
try {
|
||||||
|
const code = this.normalizeCode(this.sessionCode);
|
||||||
|
const payload = await this.request<unknown>(`/lobby/sessions/${encodeURIComponent(code)}/scoreboard`, 'GET');
|
||||||
|
this.scoreboardPayload = JSON.stringify(payload, null, 2);
|
||||||
|
await this.refreshSession();
|
||||||
|
} catch (error) {
|
||||||
|
this.scoreboardError = `Scoreboard failed: ${(error as Error).message}`;
|
||||||
|
} finally {
|
||||||
|
this.loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async startNextRound(): Promise<void> {
|
||||||
|
this.loading = true;
|
||||||
|
this.nextRoundError = '';
|
||||||
|
this.error = '';
|
||||||
|
try {
|
||||||
|
const code = this.normalizeCode(this.sessionCode);
|
||||||
|
if (!code) {
|
||||||
|
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 = `Next round failed: ${(error as Error).message}`;
|
||||||
|
} finally {
|
||||||
|
this.loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async finishGame(): Promise<void> {
|
||||||
|
this.loading = true;
|
||||||
|
this.finishError = '';
|
||||||
|
this.error = '';
|
||||||
|
try {
|
||||||
|
const code = this.normalizeCode(this.sessionCode);
|
||||||
|
if (!code) {
|
||||||
|
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);
|
||||||
|
this.finalLeaderboard = [...payload.leaderboard].sort((a, b) => {
|
||||||
|
if (b.score !== a.score) {
|
||||||
|
return b.score - a.score;
|
||||||
|
}
|
||||||
|
return a.nickname.localeCompare(b.nickname);
|
||||||
|
});
|
||||||
|
this.finalWinner = payload.winner ?? this.finalLeaderboard[0] ?? null;
|
||||||
|
await this.refreshSession();
|
||||||
|
} catch (error) {
|
||||||
|
this.finishError = `Finish game failed: ${(error as Error).message}`;
|
||||||
|
} finally {
|
||||||
|
this.loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private resetFinalLeaderboard(): void {
|
||||||
|
this.finalLeaderboardPayload = '';
|
||||||
|
this.finalLeaderboard = [];
|
||||||
|
this.finalWinner = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async runAction(action: () => Promise<void>): Promise<void> {
|
||||||
|
this.loading = true;
|
||||||
|
this.error = '';
|
||||||
|
try {
|
||||||
|
await action();
|
||||||
|
} catch (error) {
|
||||||
|
this.error = (error as Error).message;
|
||||||
|
} finally {
|
||||||
|
this.loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,320 @@
|
|||||||
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
import { PlayerShellComponent } from './player-shell.component';
|
||||||
|
|
||||||
|
type FetchMock = ReturnType<typeof vi.fn>;
|
||||||
|
|
||||||
|
function jsonResponse(status: number, body: unknown) {
|
||||||
|
return {
|
||||||
|
ok: status >= 200 && status < 300,
|
||||||
|
status,
|
||||||
|
json: vi.fn().mockResolvedValue(body),
|
||||||
|
} as unknown as Response;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sessionDetailPayload(status: string, options?: { answers?: string[]; players?: Array<{ id: number; nickname: string; score: number }>; roundQuestionId?: number | null }) {
|
||||||
|
const answers = options?.answers ?? [];
|
||||||
|
const roundQuestionId = options?.roundQuestionId ?? 11;
|
||||||
|
|
||||||
|
return {
|
||||||
|
session: {
|
||||||
|
code: 'ABCD12',
|
||||||
|
status,
|
||||||
|
host_id: null,
|
||||||
|
current_round: 1,
|
||||||
|
players_count: (options?.players ?? []).length,
|
||||||
|
},
|
||||||
|
round_question:
|
||||||
|
roundQuestionId === null
|
||||||
|
? null
|
||||||
|
: {
|
||||||
|
id: roundQuestionId,
|
||||||
|
round_number: 1,
|
||||||
|
prompt: 'Q?',
|
||||||
|
shown_at: '2026-01-01T00:00:00Z',
|
||||||
|
answers: answers.map((text) => ({ text })),
|
||||||
|
},
|
||||||
|
players: (options?.players ?? []).map((player) => ({
|
||||||
|
...player,
|
||||||
|
is_connected: true,
|
||||||
|
})),
|
||||||
|
phase_view_model: {
|
||||||
|
status,
|
||||||
|
round_number: 1,
|
||||||
|
players_count: (options?.players ?? []).length,
|
||||||
|
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: status === 'lobby',
|
||||||
|
can_submit_lie: status === 'lie',
|
||||||
|
can_submit_guess: status === 'guess',
|
||||||
|
can_view_final_result: status === 'finished',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('PlayerShellComponent gameplay wiring', () => {
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers();
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears selected guess when refreshed status is no longer guess', async () => {
|
||||||
|
const fetchMock: FetchMock = vi.fn().mockResolvedValue(
|
||||||
|
jsonResponse(200, sessionDetailPayload('reveal', { answers: ['A'] }))
|
||||||
|
);
|
||||||
|
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
|
||||||
|
const component = new PlayerShellComponent();
|
||||||
|
component.sessionCode = 'abcd12';
|
||||||
|
component.selectedGuess = 'A';
|
||||||
|
|
||||||
|
await component.refreshSession();
|
||||||
|
|
||||||
|
expect(fetchMock).toHaveBeenCalledWith(
|
||||||
|
'/lobby/sessions/ABCD12',
|
||||||
|
expect.objectContaining({ method: 'GET' })
|
||||||
|
);
|
||||||
|
expect(component.selectedGuess).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('surfaces lie submit error and allows retry success flow', async () => {
|
||||||
|
const fetchMock: FetchMock = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(jsonResponse(500, { error: 'Temporary submit outage' }))
|
||||||
|
.mockResolvedValueOnce(jsonResponse(201, { lie: { id: 1, player_id: 9, round_question_id: 11, text: 'my lie', created_at: '2026-01-01T00:00:01Z' }, window: { lie_deadline_at: '2026-01-01T00:00:45Z' } }))
|
||||||
|
.mockResolvedValueOnce(jsonResponse(200, sessionDetailPayload('guess', { answers: ['A', 'B'] })));
|
||||||
|
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
|
||||||
|
const component = new PlayerShellComponent();
|
||||||
|
component.sessionCode = 'ABCD12';
|
||||||
|
component.playerId = 9;
|
||||||
|
component.sessionToken = 'token-1';
|
||||||
|
component.lieText = 'my lie';
|
||||||
|
component.session = {
|
||||||
|
session: { code: 'ABCD12', status: 'lie', current_round: 1 },
|
||||||
|
round_question: { id: 11, prompt: 'Q?', answers: [] },
|
||||||
|
players: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
await component.submitLie();
|
||||||
|
|
||||||
|
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||||
|
1,
|
||||||
|
'/lobby/sessions/ABCD12/questions/11/lies/submit',
|
||||||
|
expect.objectContaining({
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ player_id: 9, session_token: 'token-1', text: 'my lie' }),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
expect(component.submitError?.kind).toBe('lie');
|
||||||
|
expect(component.submitError?.message).toContain('Lie submit failed: Temporary submit outage');
|
||||||
|
|
||||||
|
await component.submitLie();
|
||||||
|
|
||||||
|
expect(component.submitError).toBeNull();
|
||||||
|
expect(component.session?.session.status).toBe('guess');
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds final leaderboard in finished status without legacy page hop', async () => {
|
||||||
|
const fetchMock: FetchMock = vi.fn().mockResolvedValue(
|
||||||
|
jsonResponse(
|
||||||
|
200,
|
||||||
|
sessionDetailPayload('finished', {
|
||||||
|
roundQuestionId: null,
|
||||||
|
players: [
|
||||||
|
{ id: 2, nickname: 'Mads', score: 150 },
|
||||||
|
{ id: 1, nickname: 'Luna', score: 320 },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
|
||||||
|
const component = new PlayerShellComponent();
|
||||||
|
component.sessionCode = 'ABCD12';
|
||||||
|
|
||||||
|
await component.refreshSession();
|
||||||
|
|
||||||
|
expect(component.finalLeaderboard.map((entry) => entry.nickname)).toEqual(['Luna', 'Mads']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('surfaces guess submit error and retries with selected answer payload', async () => {
|
||||||
|
const fetchMock: FetchMock = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(jsonResponse(503, { error: 'Guess queue busy' }))
|
||||||
|
.mockResolvedValueOnce(jsonResponse(201, { guess: { id: 2, player_id: 9, round_question_id: 11, selected_text: 'B', is_correct: false, fooled_player_id: 3, created_at: '2026-01-01T00:00:10Z' }, window: { guess_deadline_at: '2026-01-01T00:01:30Z' } }))
|
||||||
|
.mockResolvedValueOnce(jsonResponse(200, sessionDetailPayload('reveal', { answers: ['A', 'B'] })));
|
||||||
|
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
|
||||||
|
const component = new PlayerShellComponent();
|
||||||
|
component.sessionCode = ' abcd12 ';
|
||||||
|
component.playerId = 9;
|
||||||
|
component.sessionToken = 'token-1';
|
||||||
|
component.selectedGuess = 'B';
|
||||||
|
component.session = {
|
||||||
|
session: { code: 'ABCD12', status: 'guess', current_round: 1 },
|
||||||
|
round_question: { id: 11, prompt: 'Q?', answers: [{ text: 'A' }, { text: 'B' }] },
|
||||||
|
players: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
await component.submitGuess();
|
||||||
|
|
||||||
|
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||||
|
1,
|
||||||
|
'/lobby/sessions/ABCD12/questions/11/guesses/submit',
|
||||||
|
expect.objectContaining({
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ player_id: 9, session_token: 'token-1', selected_text: 'B' }),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
expect(component.submitError?.kind).toBe('guess');
|
||||||
|
expect(component.submitError?.message).toContain('Guess submit failed: Guess queue busy');
|
||||||
|
|
||||||
|
await component.submitGuess();
|
||||||
|
|
||||||
|
expect(component.submitError).toBeNull();
|
||||||
|
expect(component.session?.session.status).toBe('reveal');
|
||||||
|
expect(component.selectedGuess).toBe('');
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('enters reconnecting state when network request fails while online', async () => {
|
||||||
|
vi.stubGlobal('navigator', { onLine: true });
|
||||||
|
|
||||||
|
const fetchMock: FetchMock = vi.fn().mockRejectedValueOnce(new TypeError('Failed to fetch'));
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
|
||||||
|
const component = new PlayerShellComponent();
|
||||||
|
component.sessionCode = 'ABCD12';
|
||||||
|
|
||||||
|
await component.refreshSession();
|
||||||
|
|
||||||
|
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 () => {
|
||||||
|
vi.stubGlobal('navigator', { onLine: false });
|
||||||
|
|
||||||
|
const fetchMock: FetchMock = vi.fn().mockRejectedValue(new TypeError('Failed to fetch'));
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
|
||||||
|
const component = new PlayerShellComponent();
|
||||||
|
component.sessionCode = 'ABCD12';
|
||||||
|
|
||||||
|
await component.refreshSession();
|
||||||
|
|
||||||
|
expect(component.connectionState).toBe('offline');
|
||||||
|
expect(component.error).toContain('Session refresh failed');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tracks loading transition message for join action', async () => {
|
||||||
|
let resolveJoin: ((value: Response) => void) | null = null;
|
||||||
|
const fetchMock: FetchMock = vi.fn().mockImplementation(
|
||||||
|
() =>
|
||||||
|
new Promise<Response>((resolve) => {
|
||||||
|
resolveJoin = resolve;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
|
||||||
|
const component = new PlayerShellComponent();
|
||||||
|
component.sessionCode = 'ABCD12';
|
||||||
|
component.nickname = 'Luna';
|
||||||
|
|
||||||
|
const joinPromise = component.joinSession();
|
||||||
|
|
||||||
|
expect(component.loading).toBe(true);
|
||||||
|
expect(component.loadingMessage).toBe('Joining session… restoring your player state.');
|
||||||
|
|
||||||
|
resolveJoin?.(jsonResponse(201, sessionDetailPayload('lobby', { roundQuestionId: null })));
|
||||||
|
await joinPromise;
|
||||||
|
|
||||||
|
expect(component.loading).toBe(false);
|
||||||
|
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', () => {
|
||||||
|
const values = new Map<string, string>();
|
||||||
|
const localStorage = {
|
||||||
|
getItem: vi.fn((key: string) => values.get(key) ?? null),
|
||||||
|
setItem: vi.fn((key: string, value: string) => {
|
||||||
|
values.set(key, value);
|
||||||
|
}),
|
||||||
|
removeItem: vi.fn((key: string) => {
|
||||||
|
values.delete(key);
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
vi.stubGlobal('window', {
|
||||||
|
addEventListener: vi.fn(),
|
||||||
|
removeEventListener: vi.fn(),
|
||||||
|
localStorage,
|
||||||
|
});
|
||||||
|
|
||||||
|
values.set('wpp.session-context', JSON.stringify({ sessionCode: 'ABCD12', playerId: 9, token: 'tok-1' }));
|
||||||
|
|
||||||
|
const component = new PlayerShellComponent();
|
||||||
|
component.sessionCode = 'ABCD12';
|
||||||
|
component.playerId = 9;
|
||||||
|
component.sessionToken = 'tok-1';
|
||||||
|
component.error = 'Session refresh failed';
|
||||||
|
component.submitError = { kind: 'guess', message: 'Guess submit failed' };
|
||||||
|
component.session = {
|
||||||
|
session: { code: 'ABCD12', status: 'guess', current_round: 1 },
|
||||||
|
round_question: { id: 11, prompt: 'Q?', answers: [{ text: 'A' }] },
|
||||||
|
players: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
component.returnToJoin();
|
||||||
|
|
||||||
|
expect(component.playerId).toBe(0);
|
||||||
|
expect(component.sessionToken).toBe('');
|
||||||
|
expect(component.session).toBeNull();
|
||||||
|
expect(component.error).toBe('');
|
||||||
|
expect(component.submitError).toBeNull();
|
||||||
|
expect(values.get('wpp.session-context')).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,390 @@
|
|||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component, OnDestroy, OnInit, Optional } from '@angular/core';
|
||||||
|
import { ActivatedRoute } from '@angular/router';
|
||||||
|
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 type { RouteSessionContext } from '../../session-route-context';
|
||||||
|
|
||||||
|
interface SessionDetail {
|
||||||
|
session: { code: string; status: string; current_round: number };
|
||||||
|
round_question: { id: number; prompt: string; answers: Array<{ text: string }> } | null;
|
||||||
|
players: Array<{ id: number; nickname: string; score: number }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
type ConnectionState = 'online' | 'reconnecting' | 'offline';
|
||||||
|
type LoadingTransition = 'refresh' | 'join' | 'submit-lie' | 'submit-guess' | null;
|
||||||
|
|
||||||
|
function resolveLocalStorage(): Storage | undefined {
|
||||||
|
if (typeof window === 'undefined') {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return window.localStorage;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-player-shell',
|
||||||
|
standalone: true,
|
||||||
|
imports: [CommonModule, FormsModule],
|
||||||
|
template: `
|
||||||
|
<h2>Player SPA gameplay flow</h2>
|
||||||
|
|
||||||
|
<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">
|
||||||
|
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">
|
||||||
|
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>Status:</strong> {{ session.session.status }}</p>
|
||||||
|
<p *ngIf="session.round_question"><strong>Prompt:</strong> {{ session.round_question.prompt }}</p>
|
||||||
|
|
||||||
|
<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
|
||||||
|
type="button"
|
||||||
|
*ngFor="let answer of session.round_question?.answers"
|
||||||
|
(click)="selectedGuess = answer.text"
|
||||||
|
[class.active]="selectedGuess === answer.text"
|
||||||
|
[disabled]="loading || session.session.status !== 'guess'"
|
||||||
|
>
|
||||||
|
{{ answer.text }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<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>Final leaderboard</h3>
|
||||||
|
<ol>
|
||||||
|
<li *ngFor="let entry of finalLeaderboard">{{ entry.nickname }}: {{ entry.score }}</li>
|
||||||
|
</ol>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p *ngIf="error" class="error">{{ error }}</p>
|
||||||
|
<p *ngIf="submitError" class="error">{{ submitError.message }}</p>
|
||||||
|
|
||||||
|
<div class="panel" *ngIf="error || submitError">
|
||||||
|
<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 {
|
||||||
|
sessionCode = '';
|
||||||
|
nickname = '';
|
||||||
|
playerId = 0;
|
||||||
|
sessionToken = '';
|
||||||
|
lieText = '';
|
||||||
|
selectedGuess = '';
|
||||||
|
loading = false;
|
||||||
|
error = '';
|
||||||
|
submitError: { kind: 'lie' | 'guess'; message: string } | null = null;
|
||||||
|
session: SessionDetail | null = null;
|
||||||
|
finalLeaderboard: Array<{ id: number; nickname: string; score: number }> = [];
|
||||||
|
connectionState: ConnectionState = 'online';
|
||||||
|
loadingTransition: LoadingTransition = null;
|
||||||
|
|
||||||
|
private readonly sessionContextStore = createSessionContextStore(resolveLocalStorage());
|
||||||
|
private readonly controller = createVerticalSliceController(createApiClient(), this.sessionContextStore);
|
||||||
|
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
|
constructor(@Optional() private readonly route: ActivatedRoute | null = null) {
|
||||||
|
if (typeof navigator !== 'undefined' && !navigator.onLine) {
|
||||||
|
this.connectionState = 'offline';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
window.addEventListener('online', this.handleOnline);
|
||||||
|
window.addEventListener('offline', this.handleOffline);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnInit(): void {
|
||||||
|
const routeContext = this.route?.snapshot.data['routeContext'] as RouteSessionContext | undefined;
|
||||||
|
const persistedContext = this.sessionContextStore.get();
|
||||||
|
|
||||||
|
this.playerId = routeContext?.playerId ?? persistedContext?.playerId ?? 0;
|
||||||
|
this.sessionToken = routeContext?.token ?? persistedContext?.token ?? '';
|
||||||
|
|
||||||
|
const candidate = routeContext?.sessionCode || persistedContext?.sessionCode || '';
|
||||||
|
if (!candidate) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.sessionCode = this.normalizeCode(candidate);
|
||||||
|
void this.refreshSession();
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnDestroy(): void {
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
window.removeEventListener('online', this.handleOnline);
|
||||||
|
window.removeEventListener('offline', this.handleOffline);
|
||||||
|
}
|
||||||
|
this.clearReconnectTimer();
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly handleOnline = (): void => {
|
||||||
|
this.connectionState = 'reconnecting';
|
||||||
|
void this.retryReconnect();
|
||||||
|
};
|
||||||
|
|
||||||
|
private readonly handleOffline = (): void => {
|
||||||
|
this.connectionState = 'offline';
|
||||||
|
this.clearReconnectTimer();
|
||||||
|
};
|
||||||
|
|
||||||
|
private clearReconnectTimer(): void {
|
||||||
|
if (this.reconnectTimer) {
|
||||||
|
clearTimeout(this.reconnectTimer);
|
||||||
|
this.reconnectTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
get loadingMessage(): string {
|
||||||
|
switch (this.loadingTransition) {
|
||||||
|
case 'join':
|
||||||
|
return 'Joining session… restoring your player state.';
|
||||||
|
case 'submit-lie':
|
||||||
|
return 'Submitting lie… waiting for guess phase.';
|
||||||
|
case 'submit-guess':
|
||||||
|
return 'Submitting guess… waiting for reveal.';
|
||||||
|
case 'refresh':
|
||||||
|
default:
|
||||||
|
return 'Loading latest session state…';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private normalizeCode(value: string): string {
|
||||||
|
return value.trim().toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
private toMessage(error: unknown): string {
|
||||||
|
if (error instanceof Error && error.message) {
|
||||||
|
return error.message;
|
||||||
|
}
|
||||||
|
return 'Unknown error';
|
||||||
|
}
|
||||||
|
|
||||||
|
private markOnline(): void {
|
||||||
|
this.connectionState = 'online';
|
||||||
|
this.clearReconnectTimer();
|
||||||
|
}
|
||||||
|
|
||||||
|
private markConnectionIssue(error: unknown): void {
|
||||||
|
if (typeof navigator !== 'undefined' && !navigator.onLine) {
|
||||||
|
this.connectionState = 'offline';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const message = this.toMessage(error).toLowerCase();
|
||||||
|
if (
|
||||||
|
message.includes('fetch') ||
|
||||||
|
message.includes('network') ||
|
||||||
|
message.includes('failed to') ||
|
||||||
|
message.includes('could not load lobby status') ||
|
||||||
|
message.includes('session refresh failed')
|
||||||
|
) {
|
||||||
|
this.connectionState = 'reconnecting';
|
||||||
|
this.scheduleReconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private scheduleReconnect(): void {
|
||||||
|
if (this.reconnectTimer || !this.sessionCode.trim()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.reconnectTimer = setTimeout(() => {
|
||||||
|
this.reconnectTimer = null;
|
||||||
|
void this.retryReconnect();
|
||||||
|
}, 2000);
|
||||||
|
}
|
||||||
|
|
||||||
|
async retryReconnect(): Promise<void> {
|
||||||
|
if (!this.sessionCode.trim() || this.loading) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.refreshSession();
|
||||||
|
}
|
||||||
|
|
||||||
|
returnToJoin(): void {
|
||||||
|
this.loadingTransition = null;
|
||||||
|
this.clearReconnectTimer();
|
||||||
|
this.connectionState = typeof navigator !== 'undefined' && !navigator.onLine ? 'offline' : 'online';
|
||||||
|
this.session = null;
|
||||||
|
this.finalLeaderboard = [];
|
||||||
|
this.selectedGuess = '';
|
||||||
|
this.lieText = '';
|
||||||
|
this.submitError = null;
|
||||||
|
this.error = '';
|
||||||
|
this.playerId = 0;
|
||||||
|
this.sessionToken = '';
|
||||||
|
this.sessionContextStore.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private syncFinalLeaderboard(): void {
|
||||||
|
if (!this.session || this.session.session.status !== 'finished') {
|
||||||
|
this.finalLeaderboard = [];
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.finalLeaderboard = [...this.session.players].sort((a, b) => {
|
||||||
|
if (b.score !== a.score) {
|
||||||
|
return b.score - a.score;
|
||||||
|
}
|
||||||
|
return a.nickname.localeCompare(b.nickname);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async request<T>(path: string, method: 'GET' | 'POST', payload?: unknown): Promise<T> {
|
||||||
|
const response = await fetch(path, {
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
Accept: 'application/json',
|
||||||
|
...(payload === undefined ? {} : { 'Content-Type': 'application/json' }),
|
||||||
|
},
|
||||||
|
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
|
||||||
|
credentials: 'same-origin',
|
||||||
|
});
|
||||||
|
|
||||||
|
const body = await response.json().catch(() => ({}));
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error((body as { error?: string }).error ?? `HTTP ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return body as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
async refreshSession(): Promise<void> {
|
||||||
|
this.loading = true;
|
||||||
|
this.loadingTransition = 'refresh';
|
||||||
|
this.error = '';
|
||||||
|
try {
|
||||||
|
const state = await this.controller.hydrateLobby(this.sessionCode);
|
||||||
|
if (!state.session || state.errorMessage) {
|
||||||
|
throw new Error(state.errorMessage ?? 'Unknown error');
|
||||||
|
}
|
||||||
|
this.session = state.session as SessionDetail;
|
||||||
|
this.sessionCode = this.session.session.code;
|
||||||
|
if (this.session.session.status !== 'guess') {
|
||||||
|
this.selectedGuess = '';
|
||||||
|
}
|
||||||
|
this.syncFinalLeaderboard();
|
||||||
|
this.markOnline();
|
||||||
|
} catch (error) {
|
||||||
|
this.error = `Session refresh failed: ${this.toMessage(error)}`;
|
||||||
|
this.markConnectionIssue(error);
|
||||||
|
} finally {
|
||||||
|
this.loading = false;
|
||||||
|
this.loadingTransition = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async joinSession(): Promise<void> {
|
||||||
|
this.loading = true;
|
||||||
|
this.loadingTransition = 'join';
|
||||||
|
this.error = '';
|
||||||
|
try {
|
||||||
|
const state = await this.controller.joinLobby(this.sessionCode, this.nickname);
|
||||||
|
if (!state.session || state.errorMessage) {
|
||||||
|
throw new Error(state.errorMessage ?? 'Unknown error');
|
||||||
|
}
|
||||||
|
this.session = state.session as SessionDetail;
|
||||||
|
this.sessionCode = this.session.session.code;
|
||||||
|
|
||||||
|
const sessionContext = this.sessionContextStore.get();
|
||||||
|
this.playerId = sessionContext?.playerId ?? 0;
|
||||||
|
this.sessionToken = sessionContext?.token ?? '';
|
||||||
|
if (this.session.session.status !== 'guess') {
|
||||||
|
this.selectedGuess = '';
|
||||||
|
}
|
||||||
|
this.syncFinalLeaderboard();
|
||||||
|
this.markOnline();
|
||||||
|
} catch (error) {
|
||||||
|
this.error = `Join failed: ${this.toMessage(error)}`;
|
||||||
|
this.markConnectionIssue(error);
|
||||||
|
} finally {
|
||||||
|
this.loading = false;
|
||||||
|
this.loadingTransition = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async submitLie(): Promise<void> {
|
||||||
|
if (!this.session?.round_question?.id) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.loading = true;
|
||||||
|
this.loadingTransition = 'submit-lie';
|
||||||
|
this.submitError = null;
|
||||||
|
try {
|
||||||
|
await this.request(
|
||||||
|
`/lobby/sessions/${encodeURIComponent(this.normalizeCode(this.sessionCode))}/questions/${this.session.round_question.id}/lies/submit`,
|
||||||
|
'POST',
|
||||||
|
{
|
||||||
|
player_id: this.playerId,
|
||||||
|
session_token: this.sessionToken,
|
||||||
|
text: this.lieText,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
await this.refreshSession();
|
||||||
|
this.markOnline();
|
||||||
|
} catch (error) {
|
||||||
|
this.submitError = { kind: 'lie', message: `Lie submit failed: ${this.toMessage(error)}` };
|
||||||
|
this.markConnectionIssue(error);
|
||||||
|
} finally {
|
||||||
|
this.loading = false;
|
||||||
|
this.loadingTransition = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async submitGuess(): Promise<void> {
|
||||||
|
if (!this.session?.round_question?.id || !this.selectedGuess) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.loading = true;
|
||||||
|
this.loadingTransition = 'submit-guess';
|
||||||
|
this.submitError = null;
|
||||||
|
try {
|
||||||
|
await this.request(
|
||||||
|
`/lobby/sessions/${encodeURIComponent(this.normalizeCode(this.sessionCode))}/questions/${this.session.round_question.id}/guesses/submit`,
|
||||||
|
'POST',
|
||||||
|
{
|
||||||
|
player_id: this.playerId,
|
||||||
|
session_token: this.sessionToken,
|
||||||
|
selected_text: this.selectedGuess,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
await this.refreshSession();
|
||||||
|
this.markOnline();
|
||||||
|
} catch (error) {
|
||||||
|
this.submitError = { kind: 'guess', message: `Guess submit failed: ${this.toMessage(error)}` };
|
||||||
|
this.markConnectionIssue(error);
|
||||||
|
} finally {
|
||||||
|
this.loading = false;
|
||||||
|
this.loadingTransition = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
import { hostRouteContextResolver, playerRouteContextResolver, resolveSessionCode } from './session-route-context';
|
||||||
|
|
||||||
|
type RouteLike = {
|
||||||
|
paramMap: { get: (key: string) => string | null };
|
||||||
|
queryParamMap: { get: (key: string) => string | null };
|
||||||
|
};
|
||||||
|
|
||||||
|
function route(params: Record<string, string | null>, query: Record<string, string | null> = {}): RouteLike {
|
||||||
|
return {
|
||||||
|
paramMap: { get: (key: string) => params[key] ?? null },
|
||||||
|
queryParamMap: { get: (key: string) => query[key] ?? null },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function storageMock(initial: Record<string, string> = {}): Storage {
|
||||||
|
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);
|
||||||
|
}),
|
||||||
|
removeItem: vi.fn((key: string) => {
|
||||||
|
data.delete(key);
|
||||||
|
}),
|
||||||
|
clear: vi.fn(() => {
|
||||||
|
data.clear();
|
||||||
|
}),
|
||||||
|
key: vi.fn((index: number) => Array.from(data.keys())[index] ?? null),
|
||||||
|
get length() {
|
||||||
|
return data.size;
|
||||||
|
},
|
||||||
|
} as unknown as Storage;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setWindow(localStorage: Storage, sessionStorage: Storage): void {
|
||||||
|
vi.stubGlobal('window', { localStorage, sessionStorage });
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('session route context', () => {
|
||||||
|
afterEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolves player code from persisted session context when route has no code', () => {
|
||||||
|
setWindow(
|
||||||
|
storageMock({ 'wpp.session-context': JSON.stringify({ sessionCode: 'ab12', playerId: 7, token: 'tok' }) }),
|
||||||
|
storageMock()
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(resolveSessionCode(route({}, {}) as never, 'player')).toBe('AB12');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolves host code from session query string', () => {
|
||||||
|
setWindow(storageMock(), storageMock());
|
||||||
|
|
||||||
|
expect(resolveSessionCode(route({}, { session: 'qwe9' }) as never, 'host')).toBe('QWE9');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('player resolver emits player id/token when context matches route session', () => {
|
||||||
|
setWindow(
|
||||||
|
storageMock({ 'wpp.session-context': JSON.stringify({ sessionCode: 'AB12', playerId: 5, token: 'tok-5' }) }),
|
||||||
|
storageMock()
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(playerRouteContextResolver(route({ context: 'ab12' }) as never, {} as never)).toEqual({
|
||||||
|
sessionCode: 'AB12',
|
||||||
|
playerId: 5,
|
||||||
|
token: 'tok-5',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('host resolver stores normalized host session code for refresh bootstrap', () => {
|
||||||
|
const sessionStorage = storageMock();
|
||||||
|
setWindow(storageMock(), sessionStorage);
|
||||||
|
|
||||||
|
expect(hostRouteContextResolver(route({ context: 'ab12' }) as never, {} as never)).toEqual({
|
||||||
|
sessionCode: 'AB12',
|
||||||
|
playerId: null,
|
||||||
|
token: null,
|
||||||
|
});
|
||||||
|
expect(sessionStorage.setItem).toHaveBeenCalledWith('wpp.host-session-code', 'AB12');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import { inject } from '@angular/core';
|
||||||
|
import { type ActivatedRouteSnapshot, type CanActivateFn, type ResolveFn, Router, type UrlTree } from '@angular/router';
|
||||||
|
|
||||||
|
import { createSessionContextStore } from '../../../src/spa/session-context-store';
|
||||||
|
|
||||||
|
export interface RouteSessionContext {
|
||||||
|
sessionCode: string | null;
|
||||||
|
playerId: number | null;
|
||||||
|
token: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const HOST_STORAGE_KEY = 'wpp.host-session-code';
|
||||||
|
|
||||||
|
function normalizeCode(value: string): string {
|
||||||
|
return value.trim().toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
function isCodeLike(value: string | null | undefined): value is string {
|
||||||
|
return !!value && /^[A-Za-z0-9]{4,12}$/.test(value.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasPlayerSessionContext(sessionCode: string): boolean {
|
||||||
|
const context = createSessionContextStore(window.localStorage).get();
|
||||||
|
if (!context) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
isCodeLike(context.sessionCode) &&
|
||||||
|
normalizeCode(context.sessionCode) === normalizeCode(sessionCode) &&
|
||||||
|
Number.isInteger(context.playerId) &&
|
||||||
|
context.playerId > 0 &&
|
||||||
|
!!context.token.trim()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveSessionCode(route: ActivatedRouteSnapshot, mode: 'host' | 'player'): string | null {
|
||||||
|
const contextParam = route.paramMap.get('context');
|
||||||
|
const queryCode = route.queryParamMap.get('session');
|
||||||
|
|
||||||
|
if (isCodeLike(contextParam)) {
|
||||||
|
return normalizeCode(contextParam);
|
||||||
|
}
|
||||||
|
if (isCodeLike(queryCode)) {
|
||||||
|
return normalizeCode(queryCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mode === 'player') {
|
||||||
|
const persisted = createSessionContextStore(window.localStorage).get()?.sessionCode;
|
||||||
|
if (isCodeLike(persisted)) {
|
||||||
|
return normalizeCode(persisted);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const stored = window.sessionStorage.getItem(HOST_STORAGE_KEY);
|
||||||
|
if (isCodeLike(stored)) {
|
||||||
|
return normalizeCode(stored);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sessionExists(code: string): Promise<boolean> {
|
||||||
|
const response = await fetch(`/lobby/sessions/${encodeURIComponent(code)}`, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: { Accept: 'application/json' },
|
||||||
|
credentials: 'same-origin',
|
||||||
|
});
|
||||||
|
|
||||||
|
return response.ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requireSessionContext(route: ActivatedRouteSnapshot, mode: 'host' | 'player'): Promise<boolean> {
|
||||||
|
const phase = route.paramMap.get('phase');
|
||||||
|
const code = resolveSessionCode(route, mode);
|
||||||
|
|
||||||
|
if (!phase) {
|
||||||
|
if (mode === 'host' && code) {
|
||||||
|
window.sessionStorage.setItem(HOST_STORAGE_KEY, code);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!code) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mode === 'player' && !hasPlayerSessionContext(code)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ok = await sessionExists(code);
|
||||||
|
if (!ok) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mode === 'host') {
|
||||||
|
window.sessionStorage.setItem(HOST_STORAGE_KEY, code);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function guard(mode: 'host' | 'player', route: ActivatedRouteSnapshot): Promise<boolean | UrlTree> {
|
||||||
|
const router = inject(Router);
|
||||||
|
const allowed = await requireSessionContext(route, mode);
|
||||||
|
if (allowed) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return router.createUrlTree([`/${mode}`]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const hostRouteGuard: CanActivateFn = (route) => guard('host', route);
|
||||||
|
|
||||||
|
export const playerRouteGuard: CanActivateFn = (route) => guard('player', route);
|
||||||
|
|
||||||
|
export const hostRouteContextResolver: ResolveFn<RouteSessionContext> = (route) => {
|
||||||
|
const code = resolveSessionCode(route, 'host');
|
||||||
|
if (code) {
|
||||||
|
window.sessionStorage.setItem(HOST_STORAGE_KEY, code);
|
||||||
|
}
|
||||||
|
return { sessionCode: code, playerId: null, token: null };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const playerRouteContextResolver: ResolveFn<RouteSessionContext> = (route) => {
|
||||||
|
const code = resolveSessionCode(route, 'player');
|
||||||
|
const context = createSessionContextStore(window.localStorage).get();
|
||||||
|
|
||||||
|
if (!code || !context || normalizeCode(context.sessionCode) !== code) {
|
||||||
|
return { sessionCode: code, playerId: null, token: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
sessionCode: code,
|
||||||
|
playerId: Number.isInteger(context.playerId) && context.playerId > 0 ? context.playerId : null,
|
||||||
|
token: context.token.trim() || null,
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<title>WPP Angular Shell</title>
|
||||||
|
<base href="/" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<app-root></app-root>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { bootstrapApplication } from '@angular/platform-browser';
|
||||||
|
import { AppComponent } from './app/app.component';
|
||||||
|
import { appConfig } from './app/app.config';
|
||||||
|
|
||||||
|
bootstrapApplication(AppComponent, appConfig).catch((error) => {
|
||||||
|
console.error(error);
|
||||||
|
});
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
html, body {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
import '@angular/compiler';
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"outDir": "./out-tsc/app",
|
||||||
|
"types": []
|
||||||
|
},
|
||||||
|
"files": ["src/main.ts"],
|
||||||
|
"include": ["src/**/*.d.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"compileOnSave": false,
|
||||||
|
"compilerOptions": {
|
||||||
|
"strict": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"sourceMap": true,
|
||||||
|
"declaration": false,
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"importHelpers": true,
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "ES2022",
|
||||||
|
"lib": ["ES2022", "dom"]
|
||||||
|
},
|
||||||
|
"angularCompilerOptions": {
|
||||||
|
"strictInjectionParameters": true,
|
||||||
|
"strictInputAccessModifiers": true,
|
||||||
|
"strictTemplates": true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { defineConfig } from 'vitest/config';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
include: ['src/**/*.spec.ts'],
|
||||||
|
setupFiles: ['src/test-setup.ts'],
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -1,4 +1,37 @@
|
|||||||
import type { ApiFailure, ApiResult, HealthResponse, SessionDetailResponse } from './types';
|
import {
|
||||||
|
mapCalculateScoresResponse,
|
||||||
|
mapFinishGameResponse,
|
||||||
|
mapHealthResponse,
|
||||||
|
mapJoinSessionResponse,
|
||||||
|
mapMixAnswersResponse,
|
||||||
|
mapScoreboardResponse,
|
||||||
|
mapSessionDetailResponse,
|
||||||
|
mapShowQuestionResponse,
|
||||||
|
mapStartNextRoundResponse,
|
||||||
|
mapStartRoundResponse,
|
||||||
|
mapSubmitGuessResponse,
|
||||||
|
mapSubmitLieResponse
|
||||||
|
} from './mappers';
|
||||||
|
import type {
|
||||||
|
ApiFailure,
|
||||||
|
ApiResult,
|
||||||
|
CalculateScoresResponse,
|
||||||
|
FinishGameResponse,
|
||||||
|
HealthResponse,
|
||||||
|
JoinSessionRequest,
|
||||||
|
JoinSessionResponse,
|
||||||
|
MixAnswersResponse,
|
||||||
|
ScoreboardResponse,
|
||||||
|
SessionDetailResponse,
|
||||||
|
ShowQuestionResponse,
|
||||||
|
StartNextRoundResponse,
|
||||||
|
StartRoundRequest,
|
||||||
|
StartRoundResponse,
|
||||||
|
SubmitGuessRequest,
|
||||||
|
SubmitGuessResponse,
|
||||||
|
SubmitLieRequest,
|
||||||
|
SubmitLieResponse
|
||||||
|
} from './types';
|
||||||
|
|
||||||
export interface AngularHttpError {
|
export interface AngularHttpError {
|
||||||
status?: number;
|
status?: number;
|
||||||
@@ -8,11 +41,26 @@ export interface AngularHttpError {
|
|||||||
|
|
||||||
export interface AngularHttpClientLike {
|
export interface AngularHttpClientLike {
|
||||||
get<T>(url: string, options?: { withCredentials?: boolean }): Promise<T>;
|
get<T>(url: string, options?: { withCredentials?: boolean }): Promise<T>;
|
||||||
|
post<T>(url: string, body: unknown, options?: { withCredentials?: boolean }): Promise<T>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AngularApiClient {
|
export interface AngularApiClient {
|
||||||
health(): Promise<ApiResult<HealthResponse>>;
|
health(): Promise<ApiResult<HealthResponse>>;
|
||||||
getSession(code: string): Promise<ApiResult<SessionDetailResponse>>;
|
getSession(code: string): Promise<ApiResult<SessionDetailResponse>>;
|
||||||
|
joinSession(payload: JoinSessionRequest): Promise<ApiResult<JoinSessionResponse>>;
|
||||||
|
startRound(code: string, payload: StartRoundRequest): Promise<ApiResult<StartRoundResponse>>;
|
||||||
|
showQuestion(code: string): Promise<ApiResult<ShowQuestionResponse>>;
|
||||||
|
mixAnswers(code: string, roundQuestionId: number): Promise<ApiResult<MixAnswersResponse>>;
|
||||||
|
calculateScores(code: string, roundQuestionId: number): Promise<ApiResult<CalculateScoresResponse>>;
|
||||||
|
getScoreboard(code: string): Promise<ApiResult<ScoreboardResponse>>;
|
||||||
|
startNextRound(code: string): Promise<ApiResult<StartNextRoundResponse>>;
|
||||||
|
finishGame(code: string): Promise<ApiResult<FinishGameResponse>>;
|
||||||
|
submitLie(code: string, roundQuestionId: number, payload: SubmitLieRequest): Promise<ApiResult<SubmitLieResponse>>;
|
||||||
|
submitGuess(
|
||||||
|
code: string,
|
||||||
|
roundQuestionId: number,
|
||||||
|
payload: SubmitGuessRequest
|
||||||
|
): Promise<ApiResult<SubmitGuessResponse>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function toFailure(error: unknown): ApiFailure {
|
function toFailure(error: unknown): ApiFailure {
|
||||||
@@ -40,23 +88,175 @@ function normalizeCode(code: string): string {
|
|||||||
return code.trim().toUpperCase();
|
return code.trim().toUpperCase();
|
||||||
}
|
}
|
||||||
|
|
||||||
async function wrapGet<T>(call: () => Promise<T>): Promise<ApiResult<T>> {
|
function normalizeBaseUrl(baseUrl: string): string {
|
||||||
|
return baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildUrl(baseUrl: string, path: string): string {
|
||||||
|
return `${normalizeBaseUrl(baseUrl)}${path}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function wrap<T>(call: () => Promise<unknown>, mapper: (payload: unknown) => T): Promise<ApiResult<T>> {
|
||||||
|
let payload: unknown;
|
||||||
try {
|
try {
|
||||||
const data = await call();
|
payload = await call();
|
||||||
return { ok: true, status: 200, data };
|
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
return { ok: false, status: typeof (error as AngularHttpError)?.status === 'number' ? (error as AngularHttpError).status! : 0, error: toFailure(error) };
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: typeof (error as AngularHttpError)?.status === 'number' ? (error as AngularHttpError).status! : 0,
|
||||||
|
error: toFailure(error)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
return { ok: true, status: 200, data: mapper(payload) };
|
||||||
|
} catch (error: unknown) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 200,
|
||||||
|
error: {
|
||||||
|
kind: 'parse',
|
||||||
|
status: 200,
|
||||||
|
message: error instanceof Error ? error.message : 'Invalid API response contract',
|
||||||
|
payload
|
||||||
|
}
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createAngularApiClient(http: AngularHttpClientLike, baseUrl = ''): AngularApiClient {
|
export function createAngularApiClient(http: AngularHttpClientLike, baseUrl = ''): AngularApiClient {
|
||||||
return {
|
return {
|
||||||
health: () => wrapGet(() => http.get<HealthResponse>(`${baseUrl}/healthz`, { withCredentials: true })),
|
health: () =>
|
||||||
|
wrap(() => http.get<HealthResponse>(buildUrl(baseUrl, '/healthz'), { withCredentials: true }), mapHealthResponse),
|
||||||
getSession: (code: string) =>
|
getSession: (code: string) =>
|
||||||
wrapGet(() =>
|
wrap(
|
||||||
http.get<SessionDetailResponse>(`${baseUrl}/lobby/sessions/${encodeURIComponent(normalizeCode(code))}`, {
|
() =>
|
||||||
|
http.get<SessionDetailResponse>(buildUrl(baseUrl, `/lobby/sessions/${encodeURIComponent(normalizeCode(code))}`), {
|
||||||
withCredentials: true
|
withCredentials: true
|
||||||
})
|
}),
|
||||||
|
mapSessionDetailResponse
|
||||||
|
),
|
||||||
|
joinSession: (payload: JoinSessionRequest) =>
|
||||||
|
wrap(
|
||||||
|
() =>
|
||||||
|
http.post<JoinSessionResponse>(
|
||||||
|
buildUrl(baseUrl, '/lobby/sessions/join'),
|
||||||
|
{
|
||||||
|
code: normalizeCode(payload.code),
|
||||||
|
nickname: payload.nickname.trim()
|
||||||
|
},
|
||||||
|
{ withCredentials: true }
|
||||||
|
),
|
||||||
|
mapJoinSessionResponse
|
||||||
|
),
|
||||||
|
startRound: (code: string, payload: StartRoundRequest) =>
|
||||||
|
wrap(
|
||||||
|
() =>
|
||||||
|
http.post<StartRoundResponse>(
|
||||||
|
buildUrl(baseUrl, `/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/rounds/start`),
|
||||||
|
payload,
|
||||||
|
{ withCredentials: true }
|
||||||
|
),
|
||||||
|
mapStartRoundResponse
|
||||||
|
),
|
||||||
|
showQuestion: (code: string) =>
|
||||||
|
wrap(
|
||||||
|
() =>
|
||||||
|
http.post<ShowQuestionResponse>(
|
||||||
|
buildUrl(baseUrl, `/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/questions/show`),
|
||||||
|
{},
|
||||||
|
{ withCredentials: true }
|
||||||
|
),
|
||||||
|
mapShowQuestionResponse
|
||||||
|
),
|
||||||
|
mixAnswers: (code: string, roundQuestionId: number) =>
|
||||||
|
wrap(
|
||||||
|
() =>
|
||||||
|
http.post<MixAnswersResponse>(
|
||||||
|
buildUrl(
|
||||||
|
baseUrl,
|
||||||
|
`/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/questions/${roundQuestionId}/answers/mix`
|
||||||
|
),
|
||||||
|
{},
|
||||||
|
{ withCredentials: true }
|
||||||
|
),
|
||||||
|
mapMixAnswersResponse
|
||||||
|
),
|
||||||
|
calculateScores: (code: string, roundQuestionId: number) =>
|
||||||
|
wrap(
|
||||||
|
() =>
|
||||||
|
http.post<CalculateScoresResponse>(
|
||||||
|
buildUrl(
|
||||||
|
baseUrl,
|
||||||
|
`/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/questions/${roundQuestionId}/scores/calculate`
|
||||||
|
),
|
||||||
|
{},
|
||||||
|
{ withCredentials: true }
|
||||||
|
),
|
||||||
|
mapCalculateScoresResponse
|
||||||
|
),
|
||||||
|
getScoreboard: (code: string) =>
|
||||||
|
wrap(
|
||||||
|
() =>
|
||||||
|
http.get<ScoreboardResponse>(
|
||||||
|
buildUrl(baseUrl, `/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/scoreboard`),
|
||||||
|
{ withCredentials: true }
|
||||||
|
),
|
||||||
|
mapScoreboardResponse
|
||||||
|
),
|
||||||
|
startNextRound: (code: string) =>
|
||||||
|
wrap(
|
||||||
|
() =>
|
||||||
|
http.post<StartNextRoundResponse>(
|
||||||
|
buildUrl(baseUrl, `/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/rounds/next`),
|
||||||
|
{},
|
||||||
|
{ withCredentials: true }
|
||||||
|
),
|
||||||
|
mapStartNextRoundResponse
|
||||||
|
),
|
||||||
|
finishGame: (code: string) =>
|
||||||
|
wrap(
|
||||||
|
() =>
|
||||||
|
http.post<FinishGameResponse>(
|
||||||
|
buildUrl(baseUrl, `/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/finish`),
|
||||||
|
{},
|
||||||
|
{ withCredentials: true }
|
||||||
|
),
|
||||||
|
mapFinishGameResponse
|
||||||
|
),
|
||||||
|
submitLie: (code: string, roundQuestionId: number, payload: SubmitLieRequest) =>
|
||||||
|
wrap(
|
||||||
|
() =>
|
||||||
|
http.post<SubmitLieResponse>(
|
||||||
|
buildUrl(
|
||||||
|
baseUrl,
|
||||||
|
`/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/questions/${roundQuestionId}/lies/submit`
|
||||||
|
),
|
||||||
|
{
|
||||||
|
player_id: payload.player_id,
|
||||||
|
session_token: payload.session_token,
|
||||||
|
text: payload.text
|
||||||
|
},
|
||||||
|
{ withCredentials: true }
|
||||||
|
),
|
||||||
|
mapSubmitLieResponse
|
||||||
|
),
|
||||||
|
submitGuess: (code: string, roundQuestionId: number, payload: SubmitGuessRequest) =>
|
||||||
|
wrap(
|
||||||
|
() =>
|
||||||
|
http.post<SubmitGuessResponse>(
|
||||||
|
buildUrl(
|
||||||
|
baseUrl,
|
||||||
|
`/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/questions/${roundQuestionId}/guesses/submit`
|
||||||
|
),
|
||||||
|
{
|
||||||
|
player_id: payload.player_id,
|
||||||
|
session_token: payload.session_token,
|
||||||
|
selected_text: payload.selected_text
|
||||||
|
},
|
||||||
|
{ withCredentials: true }
|
||||||
|
),
|
||||||
|
mapSubmitGuessResponse
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
+126
-9
@@ -1,11 +1,35 @@
|
|||||||
|
import {
|
||||||
|
mapCalculateScoresResponse,
|
||||||
|
mapFinishGameResponse,
|
||||||
|
mapHealthResponse,
|
||||||
|
mapJoinSessionResponse,
|
||||||
|
mapMixAnswersResponse,
|
||||||
|
mapNextRoundResponse,
|
||||||
|
mapScoreboardResponse,
|
||||||
|
mapSessionDetailResponse,
|
||||||
|
mapShowQuestionResponse,
|
||||||
|
mapStartRoundResponse,
|
||||||
|
mapSubmitGuessResponse,
|
||||||
|
mapSubmitLieResponse
|
||||||
|
} from './mappers';
|
||||||
import type {
|
import type {
|
||||||
ApiResult,
|
ApiResult,
|
||||||
|
CalculateScoresResponse,
|
||||||
|
FinishGameResponse,
|
||||||
HealthResponse,
|
HealthResponse,
|
||||||
JoinSessionRequest,
|
JoinSessionRequest,
|
||||||
JoinSessionResponse,
|
JoinSessionResponse,
|
||||||
|
MixAnswersResponse,
|
||||||
|
NextRoundResponse,
|
||||||
|
ScoreboardResponse,
|
||||||
SessionDetailResponse,
|
SessionDetailResponse,
|
||||||
|
ShowQuestionResponse,
|
||||||
StartRoundRequest,
|
StartRoundRequest,
|
||||||
StartRoundResponse
|
StartRoundResponse,
|
||||||
|
SubmitGuessRequest,
|
||||||
|
SubmitGuessResponse,
|
||||||
|
SubmitLieRequest,
|
||||||
|
SubmitLieResponse
|
||||||
} from './types';
|
} from './types';
|
||||||
|
|
||||||
export interface ApiClient {
|
export interface ApiClient {
|
||||||
@@ -13,10 +37,23 @@ export interface ApiClient {
|
|||||||
getSession(code: string): Promise<ApiResult<SessionDetailResponse>>;
|
getSession(code: string): Promise<ApiResult<SessionDetailResponse>>;
|
||||||
joinSession(payload: JoinSessionRequest): Promise<ApiResult<JoinSessionResponse>>;
|
joinSession(payload: JoinSessionRequest): Promise<ApiResult<JoinSessionResponse>>;
|
||||||
startRound(code: string, payload: StartRoundRequest): Promise<ApiResult<StartRoundResponse>>;
|
startRound(code: string, payload: StartRoundRequest): Promise<ApiResult<StartRoundResponse>>;
|
||||||
|
showQuestion(code: string): Promise<ApiResult<ShowQuestionResponse>>;
|
||||||
|
mixAnswers(code: string, roundQuestionId: number): Promise<ApiResult<MixAnswersResponse>>;
|
||||||
|
calculateScores(code: string, roundQuestionId: number): Promise<ApiResult<CalculateScoresResponse>>;
|
||||||
|
getScoreboard(code: string): Promise<ApiResult<ScoreboardResponse>>;
|
||||||
|
startNextRound(code: string): Promise<ApiResult<NextRoundResponse>>;
|
||||||
|
finishGame(code: string): Promise<ApiResult<FinishGameResponse>>;
|
||||||
|
submitLie(code: string, roundQuestionId: number, payload: SubmitLieRequest): Promise<ApiResult<SubmitLieResponse>>;
|
||||||
|
submitGuess(code: string, roundQuestionId: number, payload: SubmitGuessRequest): Promise<ApiResult<SubmitGuessResponse>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createApiClient(baseUrl = '', fetchImpl: typeof fetch = fetch): ApiClient {
|
export function createApiClient(baseUrl = '', fetchImpl: typeof fetch = fetch): ApiClient {
|
||||||
async function request<T>(path: string, method: 'GET' | 'POST', payload?: unknown): Promise<ApiResult<T>> {
|
async function request<T>(
|
||||||
|
path: string,
|
||||||
|
method: 'GET' | 'POST',
|
||||||
|
mapper: (payload: unknown) => T,
|
||||||
|
payload?: unknown
|
||||||
|
): Promise<ApiResult<T>> {
|
||||||
let response: Response;
|
let response: Response;
|
||||||
try {
|
try {
|
||||||
response = await fetchImpl(`${baseUrl}${path}`, {
|
response = await fetchImpl(`${baseUrl}${path}`, {
|
||||||
@@ -59,22 +96,102 @@ export function createApiClient(baseUrl = '', fetchImpl: typeof fetch = fetch):
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
return { ok: true, status: response.status, data: responsePayload as T };
|
try {
|
||||||
|
return { ok: true, status: response.status, data: mapper(responsePayload) };
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: response.status,
|
||||||
|
error: {
|
||||||
|
kind: 'parse',
|
||||||
|
status: response.status,
|
||||||
|
message: error instanceof Error ? error.message : 'Invalid API response contract',
|
||||||
|
payload: responsePayload
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const normalizeCode = (value: string): string => value.trim().toUpperCase();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
health: () => request<HealthResponse>('/healthz', 'GET'),
|
health: () => request<HealthResponse>('/healthz', 'GET', mapHealthResponse),
|
||||||
getSession: (code: string) =>
|
getSession: (code: string) =>
|
||||||
request<SessionDetailResponse>(`/lobby/sessions/${encodeURIComponent(code.trim().toUpperCase())}`, 'GET'),
|
request<SessionDetailResponse>(
|
||||||
|
`/lobby/sessions/${encodeURIComponent(normalizeCode(code))}`,
|
||||||
|
'GET',
|
||||||
|
mapSessionDetailResponse
|
||||||
|
),
|
||||||
joinSession: (payload: JoinSessionRequest) =>
|
joinSession: (payload: JoinSessionRequest) =>
|
||||||
request<JoinSessionResponse>('/lobby/sessions/join', 'POST', {
|
request<JoinSessionResponse>(
|
||||||
code: payload.code.trim().toUpperCase(),
|
'/lobby/sessions/join',
|
||||||
|
'POST',
|
||||||
|
mapJoinSessionResponse,
|
||||||
|
{
|
||||||
|
code: normalizeCode(payload.code),
|
||||||
nickname: payload.nickname.trim()
|
nickname: payload.nickname.trim()
|
||||||
}),
|
}
|
||||||
|
),
|
||||||
startRound: (code: string, payload: StartRoundRequest) =>
|
startRound: (code: string, payload: StartRoundRequest) =>
|
||||||
request<StartRoundResponse>(
|
request<StartRoundResponse>(
|
||||||
`/lobby/sessions/${encodeURIComponent(code.trim().toUpperCase())}/rounds/start`,
|
`/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/rounds/start`,
|
||||||
'POST',
|
'POST',
|
||||||
|
mapStartRoundResponse,
|
||||||
|
payload
|
||||||
|
),
|
||||||
|
showQuestion: (code: string) =>
|
||||||
|
request<ShowQuestionResponse>(
|
||||||
|
`/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/questions/show`,
|
||||||
|
'POST',
|
||||||
|
mapShowQuestionResponse,
|
||||||
|
{}
|
||||||
|
),
|
||||||
|
mixAnswers: (code: string, roundQuestionId: number) =>
|
||||||
|
request<MixAnswersResponse>(
|
||||||
|
`/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/questions/${roundQuestionId}/answers/mix`,
|
||||||
|
'POST',
|
||||||
|
mapMixAnswersResponse,
|
||||||
|
{}
|
||||||
|
),
|
||||||
|
calculateScores: (code: string, roundQuestionId: number) =>
|
||||||
|
request<CalculateScoresResponse>(
|
||||||
|
`/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/questions/${roundQuestionId}/scores/calculate`,
|
||||||
|
'POST',
|
||||||
|
mapCalculateScoresResponse,
|
||||||
|
{}
|
||||||
|
),
|
||||||
|
getScoreboard: (code: string) =>
|
||||||
|
request<ScoreboardResponse>(
|
||||||
|
`/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/scoreboard`,
|
||||||
|
'GET',
|
||||||
|
mapScoreboardResponse
|
||||||
|
),
|
||||||
|
startNextRound: (code: string) =>
|
||||||
|
request<NextRoundResponse>(
|
||||||
|
`/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/rounds/next`,
|
||||||
|
'POST',
|
||||||
|
mapNextRoundResponse,
|
||||||
|
{}
|
||||||
|
),
|
||||||
|
finishGame: (code: string) =>
|
||||||
|
request<FinishGameResponse>(
|
||||||
|
`/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/finish`,
|
||||||
|
'POST',
|
||||||
|
mapFinishGameResponse,
|
||||||
|
{}
|
||||||
|
),
|
||||||
|
submitLie: (code: string, roundQuestionId: number, payload: SubmitLieRequest) =>
|
||||||
|
request<SubmitLieResponse>(
|
||||||
|
`/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/questions/${roundQuestionId}/lies/submit`,
|
||||||
|
'POST',
|
||||||
|
mapSubmitLieResponse,
|
||||||
|
payload
|
||||||
|
),
|
||||||
|
submitGuess: (code: string, roundQuestionId: number, payload: SubmitGuessRequest) =>
|
||||||
|
request<SubmitGuessResponse>(
|
||||||
|
`/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/questions/${roundQuestionId}/guesses/submit`,
|
||||||
|
'POST',
|
||||||
|
mapSubmitGuessResponse,
|
||||||
payload
|
payload
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,359 @@
|
|||||||
|
import type {
|
||||||
|
CalculateScoresResponse,
|
||||||
|
FinishGameResponse,
|
||||||
|
HealthResponse,
|
||||||
|
JoinSessionResponse,
|
||||||
|
MixAnswersResponse,
|
||||||
|
ScoreboardResponse,
|
||||||
|
SessionDetailResponse,
|
||||||
|
ShowQuestionResponse,
|
||||||
|
StartNextRoundResponse,
|
||||||
|
StartRoundResponse,
|
||||||
|
SubmitGuessResponse,
|
||||||
|
SubmitLieResponse
|
||||||
|
} from './types';
|
||||||
|
|
||||||
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
return typeof value === 'object' && value !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isBoolean(value: unknown): value is boolean {
|
||||||
|
return typeof value === 'boolean';
|
||||||
|
}
|
||||||
|
|
||||||
|
function isNumber(value: unknown): value is number {
|
||||||
|
return typeof value === 'number' && Number.isFinite(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isString(value: unknown): value is string {
|
||||||
|
return typeof value === 'string';
|
||||||
|
}
|
||||||
|
|
||||||
|
function asRecord(value: unknown, path: string): Record<string, unknown> {
|
||||||
|
if (!isRecord(value)) {
|
||||||
|
throw new Error(`Invalid API contract: expected object at ${path}`);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readString(record: Record<string, unknown>, key: string, path: string): string {
|
||||||
|
const value = record[key];
|
||||||
|
if (!isString(value)) {
|
||||||
|
throw new Error(`Invalid API contract: expected string at ${path}.${key}`);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readNumber(record: Record<string, unknown>, key: string, path: string): number {
|
||||||
|
const value = record[key];
|
||||||
|
if (!isNumber(value)) {
|
||||||
|
throw new Error(`Invalid API contract: expected number at ${path}.${key}`);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readBoolean(record: Record<string, unknown>, key: string, path: string): boolean {
|
||||||
|
const value = record[key];
|
||||||
|
if (!isBoolean(value)) {
|
||||||
|
throw new Error(`Invalid API contract: expected boolean at ${path}.${key}`);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapHealthResponse(payload: unknown): HealthResponse {
|
||||||
|
const root = asRecord(payload, 'health');
|
||||||
|
return {
|
||||||
|
ok: readBoolean(root, 'ok', 'health'),
|
||||||
|
service: readString(root, 'service', 'health')
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapSessionDetail(payload: unknown): SessionDetailResponse {
|
||||||
|
const root = asRecord(payload, 'session_detail');
|
||||||
|
const session = asRecord(root.session, 'session_detail.session');
|
||||||
|
const players = root.players;
|
||||||
|
if (!Array.isArray(players)) {
|
||||||
|
throw new Error('Invalid API contract: expected array at session_detail.players');
|
||||||
|
}
|
||||||
|
|
||||||
|
const roundQuestionRaw = root.round_question;
|
||||||
|
let roundQuestion: SessionDetailResponse['round_question'] = null;
|
||||||
|
if (roundQuestionRaw !== null) {
|
||||||
|
const roundQuestionRecord = asRecord(roundQuestionRaw, 'session_detail.round_question');
|
||||||
|
const answersRaw = roundQuestionRecord.answers;
|
||||||
|
if (!Array.isArray(answersRaw)) {
|
||||||
|
throw new Error('Invalid API contract: expected array at session_detail.round_question.answers');
|
||||||
|
}
|
||||||
|
|
||||||
|
roundQuestion = {
|
||||||
|
id: readNumber(roundQuestionRecord, 'id', 'session_detail.round_question'),
|
||||||
|
round_number: readNumber(roundQuestionRecord, 'round_number', 'session_detail.round_question'),
|
||||||
|
prompt: readString(roundQuestionRecord, 'prompt', 'session_detail.round_question'),
|
||||||
|
shown_at: readString(roundQuestionRecord, 'shown_at', 'session_detail.round_question'),
|
||||||
|
answers: answersRaw.map((answer, index) => {
|
||||||
|
const answerRecord = asRecord(answer, `session_detail.round_question.answers[${index}]`);
|
||||||
|
return { text: readString(answerRecord, 'text', `session_detail.round_question.answers[${index}]`) };
|
||||||
|
})
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const phase = asRecord(root.phase_view_model, 'session_detail.phase_view_model');
|
||||||
|
const constraints = asRecord(phase.constraints, 'session_detail.phase_view_model.constraints');
|
||||||
|
const host = asRecord(phase.host, 'session_detail.phase_view_model.host');
|
||||||
|
const player = asRecord(phase.player, 'session_detail.phase_view_model.player');
|
||||||
|
|
||||||
|
return {
|
||||||
|
session: {
|
||||||
|
code: readString(session, 'code', 'session_detail.session'),
|
||||||
|
status: readString(session, 'status', 'session_detail.session'),
|
||||||
|
host_id: (() => {
|
||||||
|
const hostId = session.host_id;
|
||||||
|
if (hostId === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!isNumber(hostId)) {
|
||||||
|
throw new Error('Invalid API contract: expected number|null at session_detail.session.host_id');
|
||||||
|
}
|
||||||
|
return hostId;
|
||||||
|
})(),
|
||||||
|
current_round: readNumber(session, 'current_round', 'session_detail.session'),
|
||||||
|
players_count: readNumber(session, 'players_count', 'session_detail.session')
|
||||||
|
},
|
||||||
|
players: players.map((item, index) => {
|
||||||
|
const record = asRecord(item, `session_detail.players[${index}]`);
|
||||||
|
return {
|
||||||
|
id: readNumber(record, 'id', `session_detail.players[${index}]`),
|
||||||
|
nickname: readString(record, 'nickname', `session_detail.players[${index}]`),
|
||||||
|
score: readNumber(record, 'score', `session_detail.players[${index}]`),
|
||||||
|
is_connected: readBoolean(record, 'is_connected', `session_detail.players[${index}]`)
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
round_question: roundQuestion,
|
||||||
|
phase_view_model: {
|
||||||
|
status: readString(phase, 'status', 'session_detail.phase_view_model'),
|
||||||
|
round_number: readNumber(phase, 'round_number', 'session_detail.phase_view_model'),
|
||||||
|
players_count: readNumber(phase, 'players_count', 'session_detail.phase_view_model'),
|
||||||
|
constraints: {
|
||||||
|
min_players_to_start: readNumber(constraints, 'min_players_to_start', 'session_detail.phase_view_model.constraints'),
|
||||||
|
max_players_mvp: readNumber(constraints, 'max_players_mvp', 'session_detail.phase_view_model.constraints'),
|
||||||
|
min_players_reached: readBoolean(constraints, 'min_players_reached', 'session_detail.phase_view_model.constraints'),
|
||||||
|
max_players_allowed: readBoolean(constraints, 'max_players_allowed', 'session_detail.phase_view_model.constraints')
|
||||||
|
},
|
||||||
|
host: {
|
||||||
|
can_start_round: readBoolean(host, 'can_start_round', 'session_detail.phase_view_model.host'),
|
||||||
|
can_show_question: readBoolean(host, 'can_show_question', 'session_detail.phase_view_model.host'),
|
||||||
|
can_mix_answers: readBoolean(host, 'can_mix_answers', 'session_detail.phase_view_model.host'),
|
||||||
|
can_calculate_scores: readBoolean(host, 'can_calculate_scores', 'session_detail.phase_view_model.host'),
|
||||||
|
can_reveal_scoreboard: readBoolean(host, 'can_reveal_scoreboard', 'session_detail.phase_view_model.host'),
|
||||||
|
can_start_next_round: readBoolean(host, 'can_start_next_round', 'session_detail.phase_view_model.host'),
|
||||||
|
can_finish_game: readBoolean(host, 'can_finish_game', 'session_detail.phase_view_model.host')
|
||||||
|
},
|
||||||
|
player: {
|
||||||
|
can_join: readBoolean(player, 'can_join', 'session_detail.phase_view_model.player'),
|
||||||
|
can_submit_lie: readBoolean(player, 'can_submit_lie', 'session_detail.phase_view_model.player'),
|
||||||
|
can_submit_guess: readBoolean(player, 'can_submit_guess', 'session_detail.phase_view_model.player'),
|
||||||
|
can_view_final_result: readBoolean(player, 'can_view_final_result', 'session_detail.phase_view_model.player')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapSessionDetailResponse(payload: unknown): SessionDetailResponse {
|
||||||
|
return mapSessionDetail(payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapJoinSessionResponse(payload: unknown): JoinSessionResponse {
|
||||||
|
const root = asRecord(payload, 'join_session');
|
||||||
|
const player = asRecord(root.player, 'join_session.player');
|
||||||
|
const session = asRecord(root.session, 'join_session.session');
|
||||||
|
|
||||||
|
return {
|
||||||
|
player: {
|
||||||
|
id: readNumber(player, 'id', 'join_session.player'),
|
||||||
|
nickname: readString(player, 'nickname', 'join_session.player'),
|
||||||
|
session_token: readString(player, 'session_token', 'join_session.player'),
|
||||||
|
score: readNumber(player, 'score', 'join_session.player')
|
||||||
|
},
|
||||||
|
session: {
|
||||||
|
code: readString(session, 'code', 'join_session.session'),
|
||||||
|
status: readString(session, 'status', 'join_session.session')
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapStartRoundResponse(payload: unknown): StartRoundResponse {
|
||||||
|
const root = asRecord(payload, 'start_round');
|
||||||
|
const session = asRecord(root.session, 'start_round.session');
|
||||||
|
const round = asRecord(root.round, 'start_round.round');
|
||||||
|
const category = asRecord(round.category, 'start_round.round.category');
|
||||||
|
|
||||||
|
return {
|
||||||
|
session: {
|
||||||
|
code: readString(session, 'code', 'start_round.session'),
|
||||||
|
status: readString(session, 'status', 'start_round.session'),
|
||||||
|
current_round: readNumber(session, 'current_round', 'start_round.session')
|
||||||
|
},
|
||||||
|
round: {
|
||||||
|
number: readNumber(round, 'number', 'start_round.round'),
|
||||||
|
category: {
|
||||||
|
slug: readString(category, 'slug', 'start_round.round.category'),
|
||||||
|
name: readString(category, 'name', 'start_round.round.category')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapLeaderboardEntry(payload: unknown, path: string): { id: number; nickname: string; score: number } {
|
||||||
|
const record = asRecord(payload, path);
|
||||||
|
return {
|
||||||
|
id: readNumber(record, 'id', path),
|
||||||
|
nickname: readString(record, 'nickname', path),
|
||||||
|
score: readNumber(record, 'score', path)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapSessionState(payload: unknown, path: string): { code: string; status: string; current_round: number } {
|
||||||
|
const session = asRecord(payload, path);
|
||||||
|
return {
|
||||||
|
code: readString(session, 'code', path),
|
||||||
|
status: readString(session, 'status', path),
|
||||||
|
current_round: readNumber(session, 'current_round', path)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapShowQuestionResponse(payload: unknown): ShowQuestionResponse {
|
||||||
|
const root = asRecord(payload, 'show_question');
|
||||||
|
const roundQuestion = asRecord(root.round_question, 'show_question.round_question');
|
||||||
|
const config = asRecord(root.config, 'show_question.config');
|
||||||
|
|
||||||
|
return {
|
||||||
|
round_question: {
|
||||||
|
id: readNumber(roundQuestion, 'id', 'show_question.round_question'),
|
||||||
|
prompt: readString(roundQuestion, 'prompt', 'show_question.round_question'),
|
||||||
|
round_number: readNumber(roundQuestion, 'round_number', 'show_question.round_question'),
|
||||||
|
shown_at: readString(roundQuestion, 'shown_at', 'show_question.round_question'),
|
||||||
|
lie_deadline_at: readString(roundQuestion, 'lie_deadline_at', 'show_question.round_question')
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
lie_seconds: readNumber(config, 'lie_seconds', 'show_question.config')
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapMixAnswersResponse(payload: unknown): MixAnswersResponse {
|
||||||
|
const root = asRecord(payload, 'mix_answers');
|
||||||
|
const roundQuestion = asRecord(root.round_question, 'mix_answers.round_question');
|
||||||
|
const answersRaw = root.answers;
|
||||||
|
if (!Array.isArray(answersRaw)) {
|
||||||
|
throw new Error('Invalid API contract: expected array at mix_answers.answers');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
session: mapSessionState(root.session, 'mix_answers.session'),
|
||||||
|
round_question: {
|
||||||
|
id: readNumber(roundQuestion, 'id', 'mix_answers.round_question'),
|
||||||
|
round_number: readNumber(roundQuestion, 'round_number', 'mix_answers.round_question')
|
||||||
|
},
|
||||||
|
answers: answersRaw.map((answer, index) => {
|
||||||
|
const record = asRecord(answer, `mix_answers.answers[${index}]`);
|
||||||
|
return { text: readString(record, 'text', `mix_answers.answers[${index}]`) };
|
||||||
|
})
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapCalculateScoresResponse(payload: unknown): CalculateScoresResponse {
|
||||||
|
const root = asRecord(payload, 'calculate_scores');
|
||||||
|
const roundQuestion = asRecord(root.round_question, 'calculate_scores.round_question');
|
||||||
|
const leaderboardRaw = root.leaderboard;
|
||||||
|
if (!Array.isArray(leaderboardRaw)) {
|
||||||
|
throw new Error('Invalid API contract: expected array at calculate_scores.leaderboard');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
session: mapSessionState(root.session, 'calculate_scores.session'),
|
||||||
|
round_question: {
|
||||||
|
id: readNumber(roundQuestion, 'id', 'calculate_scores.round_question'),
|
||||||
|
round_number: readNumber(roundQuestion, 'round_number', 'calculate_scores.round_question')
|
||||||
|
},
|
||||||
|
events_created: readNumber(root, 'events_created', 'calculate_scores'),
|
||||||
|
leaderboard: leaderboardRaw.map((entry, index) => mapLeaderboardEntry(entry, `calculate_scores.leaderboard[${index}]`))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapScoreboardResponse(payload: unknown): ScoreboardResponse {
|
||||||
|
const root = asRecord(payload, 'scoreboard');
|
||||||
|
const leaderboardRaw = root.leaderboard;
|
||||||
|
if (!Array.isArray(leaderboardRaw)) {
|
||||||
|
throw new Error('Invalid API contract: expected array at scoreboard.leaderboard');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
session: mapSessionState(root.session, 'scoreboard.session'),
|
||||||
|
leaderboard: leaderboardRaw.map((entry, index) => mapLeaderboardEntry(entry, `scoreboard.leaderboard[${index}]`))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapStartNextRoundResponse(payload: unknown): StartNextRoundResponse {
|
||||||
|
const root = asRecord(payload, 'start_next_round');
|
||||||
|
return { session: mapSessionState(root.session, 'start_next_round.session') };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapFinishGameResponse(payload: unknown): FinishGameResponse {
|
||||||
|
const root = asRecord(payload, 'finish_game');
|
||||||
|
const leaderboardRaw = root.leaderboard;
|
||||||
|
if (!Array.isArray(leaderboardRaw)) {
|
||||||
|
throw new Error('Invalid API contract: expected array at finish_game.leaderboard');
|
||||||
|
}
|
||||||
|
|
||||||
|
const winnerRaw = root.winner;
|
||||||
|
|
||||||
|
return {
|
||||||
|
session: mapSessionState(root.session, 'finish_game.session'),
|
||||||
|
winner: winnerRaw === null ? null : mapLeaderboardEntry(winnerRaw, 'finish_game.winner'),
|
||||||
|
leaderboard: leaderboardRaw.map((entry, index) => mapLeaderboardEntry(entry, `finish_game.leaderboard[${index}]`))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapSubmitLieResponse(payload: unknown): SubmitLieResponse {
|
||||||
|
const root = asRecord(payload, 'submit_lie');
|
||||||
|
const lie = asRecord(root.lie, 'submit_lie.lie');
|
||||||
|
const window = asRecord(root.window, 'submit_lie.window');
|
||||||
|
|
||||||
|
return {
|
||||||
|
lie: {
|
||||||
|
id: readNumber(lie, 'id', 'submit_lie.lie'),
|
||||||
|
player_id: readNumber(lie, 'player_id', 'submit_lie.lie'),
|
||||||
|
round_question_id: readNumber(lie, 'round_question_id', 'submit_lie.lie'),
|
||||||
|
text: readString(lie, 'text', 'submit_lie.lie'),
|
||||||
|
created_at: readString(lie, 'created_at', 'submit_lie.lie')
|
||||||
|
},
|
||||||
|
window: {
|
||||||
|
lie_deadline_at: readString(window, 'lie_deadline_at', 'submit_lie.window')
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapSubmitGuessResponse(payload: unknown): SubmitGuessResponse {
|
||||||
|
const root = asRecord(payload, 'submit_guess');
|
||||||
|
const guess = asRecord(root.guess, 'submit_guess.guess');
|
||||||
|
const window = asRecord(root.window, 'submit_guess.window');
|
||||||
|
const fooledPlayerId = guess.fooled_player_id;
|
||||||
|
if (fooledPlayerId !== null && !isNumber(fooledPlayerId)) {
|
||||||
|
throw new Error('Invalid API contract: expected number|null at submit_guess.guess.fooled_player_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
guess: {
|
||||||
|
id: readNumber(guess, 'id', 'submit_guess.guess'),
|
||||||
|
player_id: readNumber(guess, 'player_id', 'submit_guess.guess'),
|
||||||
|
round_question_id: readNumber(guess, 'round_question_id', 'submit_guess.guess'),
|
||||||
|
selected_text: readString(guess, 'selected_text', 'submit_guess.guess'),
|
||||||
|
is_correct: readBoolean(guess, 'is_correct', 'submit_guess.guess'),
|
||||||
|
fooled_player_id: fooledPlayerId,
|
||||||
|
created_at: readString(guess, 'created_at', 'submit_guess.guess')
|
||||||
|
},
|
||||||
|
window: {
|
||||||
|
guess_deadline_at: readString(window, 'guess_deadline_at', 'submit_guess.window')
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -101,6 +101,113 @@ export interface StartRoundResponse {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ShowQuestionResponse {
|
||||||
|
round_question: {
|
||||||
|
id: number;
|
||||||
|
prompt: string;
|
||||||
|
round_number: number;
|
||||||
|
shown_at: string;
|
||||||
|
lie_deadline_at: string;
|
||||||
|
};
|
||||||
|
config: {
|
||||||
|
lie_seconds: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MixAnswersResponse {
|
||||||
|
session: {
|
||||||
|
code: string;
|
||||||
|
status: string;
|
||||||
|
current_round: number;
|
||||||
|
};
|
||||||
|
round_question: {
|
||||||
|
id: number;
|
||||||
|
round_number: number;
|
||||||
|
};
|
||||||
|
answers: Array<{ text: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CalculateScoresResponse {
|
||||||
|
session: {
|
||||||
|
code: string;
|
||||||
|
status: string;
|
||||||
|
current_round: number;
|
||||||
|
};
|
||||||
|
round_question: {
|
||||||
|
id: number;
|
||||||
|
round_number: number;
|
||||||
|
};
|
||||||
|
events_created: number;
|
||||||
|
leaderboard: Array<{ id: number; nickname: string; score: number }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ScoreboardResponse {
|
||||||
|
session: {
|
||||||
|
code: string;
|
||||||
|
status: string;
|
||||||
|
current_round: number;
|
||||||
|
};
|
||||||
|
leaderboard: Array<{ id: number; nickname: string; score: number }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StartNextRoundResponse {
|
||||||
|
session: {
|
||||||
|
code: string;
|
||||||
|
status: string;
|
||||||
|
current_round: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FinishGameResponse {
|
||||||
|
session: {
|
||||||
|
code: string;
|
||||||
|
status: string;
|
||||||
|
current_round: number;
|
||||||
|
};
|
||||||
|
winner: { id: number; nickname: string; score: number } | null;
|
||||||
|
leaderboard: Array<{ id: number; nickname: string; score: number }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SubmitLieRequest {
|
||||||
|
player_id: number;
|
||||||
|
session_token: string;
|
||||||
|
text: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SubmitLieResponse {
|
||||||
|
lie: {
|
||||||
|
id: number;
|
||||||
|
player_id: number;
|
||||||
|
round_question_id: number;
|
||||||
|
text: string;
|
||||||
|
created_at: string;
|
||||||
|
};
|
||||||
|
window: {
|
||||||
|
lie_deadline_at: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SubmitGuessRequest {
|
||||||
|
player_id: number;
|
||||||
|
session_token: string;
|
||||||
|
selected_text: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SubmitGuessResponse {
|
||||||
|
guess: {
|
||||||
|
id: number;
|
||||||
|
player_id: number;
|
||||||
|
round_question_id: number;
|
||||||
|
selected_text: string;
|
||||||
|
is_correct: boolean;
|
||||||
|
fooled_player_id: number | null;
|
||||||
|
created_at: string;
|
||||||
|
};
|
||||||
|
window: {
|
||||||
|
guess_deadline_at: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export type ApiErrorKind = 'network' | 'http' | 'parse';
|
export type ApiErrorKind = 'network' | 'http' | 'parse';
|
||||||
|
|
||||||
export interface ApiFailure {
|
export interface ApiFailure {
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import type { SessionDetailResponse } from '../api/types';
|
||||||
|
|
||||||
|
export type GameplayPhase = 'lie' | 'guess' | 'reveal' | 'scoreboard';
|
||||||
|
|
||||||
|
export type GameplayPhaseEvent =
|
||||||
|
| 'LIES_LOCKED'
|
||||||
|
| 'GUESSES_LOCKED'
|
||||||
|
| 'SCOREBOARD_READY'
|
||||||
|
| 'NEXT_ROUND';
|
||||||
|
|
||||||
|
export interface GameplayTransitionResult {
|
||||||
|
phase: GameplayPhase;
|
||||||
|
changed: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const TRANSITIONS: Record<GameplayPhase, Partial<Record<GameplayPhaseEvent, GameplayPhase>>> = {
|
||||||
|
lie: {
|
||||||
|
LIES_LOCKED: 'guess'
|
||||||
|
},
|
||||||
|
guess: {
|
||||||
|
GUESSES_LOCKED: 'reveal'
|
||||||
|
},
|
||||||
|
reveal: {
|
||||||
|
SCOREBOARD_READY: 'scoreboard'
|
||||||
|
},
|
||||||
|
scoreboard: {
|
||||||
|
NEXT_ROUND: 'lie'
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export function transitionGameplayPhase(phase: GameplayPhase, event: GameplayPhaseEvent): GameplayTransitionResult {
|
||||||
|
const next = TRANSITIONS[phase][event] ?? phase;
|
||||||
|
return {
|
||||||
|
phase: next,
|
||||||
|
changed: next !== phase
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function allowedGameplayEvents(phase: GameplayPhase): GameplayPhaseEvent[] {
|
||||||
|
return Object.keys(TRANSITIONS[phase]) as GameplayPhaseEvent[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deriveGameplayPhase(session: SessionDetailResponse | null): GameplayPhase | null {
|
||||||
|
const status = session?.session.status;
|
||||||
|
if (!status) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (status === 'lie' || status === 'guess' || status === 'reveal') {
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (status === 'finished') {
|
||||||
|
return 'scoreboard';
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import lobbyCatalog from '../../../shared/i18n/lobby.json';
|
||||||
|
|
||||||
|
type FrontendErrorKey = keyof typeof lobbyCatalog.frontend.errors;
|
||||||
|
|
||||||
|
const frontendErrors = lobbyCatalog.frontend.errors;
|
||||||
|
|
||||||
|
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'
|
||||||
|
};
|
||||||
|
|
||||||
|
export function lobbyMessage(key: FrontendErrorKey): string {
|
||||||
|
return frontendErrors[key] ?? frontendErrors.unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function lobbyMessageFromApiPayload(payload: unknown, fallbackKey: FrontendErrorKey): string {
|
||||||
|
if (!payload || typeof payload !== 'object') {
|
||||||
|
return lobbyMessage(fallbackKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
const record = payload as Record<string, unknown>;
|
||||||
|
const code = typeof record.error_code === 'string' ? record.error_code : '';
|
||||||
|
const mappedKey = apiErrorMap[code];
|
||||||
|
if (!mappedKey) {
|
||||||
|
return lobbyMessage(fallbackKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
return lobbyMessage(mappedKey);
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
export interface SessionContext {
|
||||||
|
sessionCode: string;
|
||||||
|
playerId: number;
|
||||||
|
token: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SessionContextInput {
|
||||||
|
sessionCode: string;
|
||||||
|
playerId: number;
|
||||||
|
token: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SessionContextStore {
|
||||||
|
get(): SessionContext | null;
|
||||||
|
set(input: SessionContextInput): SessionContext;
|
||||||
|
clear(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StorageLike {
|
||||||
|
getItem(key: string): string | null;
|
||||||
|
setItem(key: string, value: string): void;
|
||||||
|
removeItem(key: string): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_STORAGE_KEY = 'wpp.session-context';
|
||||||
|
|
||||||
|
function normalizeSessionCode(value: string): string {
|
||||||
|
return value.trim().toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeToken(value: string): string {
|
||||||
|
return value.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function toContext(input: SessionContextInput): SessionContext {
|
||||||
|
const sessionCode = normalizeSessionCode(input.sessionCode);
|
||||||
|
const token = normalizeToken(input.token);
|
||||||
|
|
||||||
|
if (!sessionCode) {
|
||||||
|
throw new Error('sessionCode is required');
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(input.playerId) || input.playerId <= 0) {
|
||||||
|
throw new Error('playerId must be a positive integer');
|
||||||
|
}
|
||||||
|
if (!token) {
|
||||||
|
throw new Error('token is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
sessionCode,
|
||||||
|
playerId: input.playerId,
|
||||||
|
token
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeParse(raw: string): SessionContext | null {
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(raw) as Partial<SessionContextInput>;
|
||||||
|
if (typeof data.sessionCode !== 'string' || typeof data.playerId !== 'number' || typeof data.token !== 'string') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return toContext({
|
||||||
|
sessionCode: data.sessionCode,
|
||||||
|
playerId: data.playerId,
|
||||||
|
token: data.token
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createSessionContextStore(storage?: StorageLike, storageKey = DEFAULT_STORAGE_KEY): SessionContextStore {
|
||||||
|
let current: SessionContext | null = null;
|
||||||
|
|
||||||
|
function getFromStorage(): SessionContext | null {
|
||||||
|
if (!storage) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const raw = storage.getItem(storageKey);
|
||||||
|
if (!raw) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = safeParse(raw);
|
||||||
|
if (!parsed) {
|
||||||
|
storage.removeItem(storageKey);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
get(): SessionContext | null {
|
||||||
|
if (current) {
|
||||||
|
return { ...current };
|
||||||
|
}
|
||||||
|
|
||||||
|
const fromStorage = getFromStorage();
|
||||||
|
if (fromStorage) {
|
||||||
|
current = fromStorage;
|
||||||
|
return { ...current };
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
set(input: SessionContextInput): SessionContext {
|
||||||
|
const normalized = toContext(input);
|
||||||
|
current = normalized;
|
||||||
|
if (storage) {
|
||||||
|
storage.setItem(storageKey, JSON.stringify(normalized));
|
||||||
|
}
|
||||||
|
return { ...normalized };
|
||||||
|
},
|
||||||
|
clear(): void {
|
||||||
|
current = null;
|
||||||
|
if (storage) {
|
||||||
|
storage.removeItem(storageKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,11 +1,22 @@
|
|||||||
import type { ApiClient } from '../api/client';
|
import type { ApiClient } from '../api/client';
|
||||||
import type { SessionDetailResponse } from '../api/types';
|
import type { SessionDetailResponse } from '../api/types';
|
||||||
|
import {
|
||||||
|
createSessionContextStore,
|
||||||
|
type SessionContext,
|
||||||
|
type SessionContextInput,
|
||||||
|
type SessionContextStore as PersistedSessionContextStore
|
||||||
|
} from './session-context-store';
|
||||||
|
import { deriveGameplayPhase, type GameplayPhase } from './gameplay-phase-machine';
|
||||||
|
import { lobbyMessage, lobbyMessageFromApiPayload } from './lobby-i18n';
|
||||||
|
|
||||||
export type AsyncState = 'idle' | 'loading' | 'success' | 'error';
|
export type AsyncState = 'idle' | 'loading' | 'success' | 'error';
|
||||||
|
|
||||||
|
export type SessionContextStore = Pick<PersistedSessionContextStore, 'get' | 'set'>;
|
||||||
|
|
||||||
export interface VerticalSliceState {
|
export interface VerticalSliceState {
|
||||||
sessionCode: string;
|
sessionCode: string;
|
||||||
session: SessionDetailResponse | null;
|
session: SessionDetailResponse | null;
|
||||||
|
gameplayPhase: GameplayPhase | null;
|
||||||
joinState: AsyncState;
|
joinState: AsyncState;
|
||||||
startRoundState: AsyncState;
|
startRoundState: AsyncState;
|
||||||
loadingSession: boolean;
|
loadingSession: boolean;
|
||||||
@@ -19,10 +30,16 @@ export interface VerticalSliceController {
|
|||||||
startRound(sessionCode: string, categorySlug: string): Promise<VerticalSliceState>;
|
startRound(sessionCode: string, categorySlug: string): Promise<VerticalSliceState>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createVerticalSliceController(api: ApiClient): VerticalSliceController {
|
export function createVerticalSliceController(
|
||||||
|
api: ApiClient,
|
||||||
|
sessionContextStore: SessionContextStore = createSessionContextStore()
|
||||||
|
): VerticalSliceController {
|
||||||
|
const persistedContext = sessionContextStore.get();
|
||||||
|
|
||||||
const state: VerticalSliceState = {
|
const state: VerticalSliceState = {
|
||||||
sessionCode: '',
|
sessionCode: persistedContext?.sessionCode ?? '',
|
||||||
session: null,
|
session: null,
|
||||||
|
gameplayPhase: null,
|
||||||
joinState: 'idle',
|
joinState: 'idle',
|
||||||
startRoundState: 'idle',
|
startRoundState: 'idle',
|
||||||
loadingSession: false,
|
loadingSession: false,
|
||||||
@@ -34,17 +51,34 @@ export function createVerticalSliceController(api: ApiClient): VerticalSliceCont
|
|||||||
async function hydrateLobby(sessionCode: string): Promise<VerticalSliceState> {
|
async function hydrateLobby(sessionCode: string): Promise<VerticalSliceState> {
|
||||||
state.loadingSession = true;
|
state.loadingSession = true;
|
||||||
state.errorMessage = null;
|
state.errorMessage = null;
|
||||||
state.sessionCode = normalizeCode(sessionCode);
|
|
||||||
|
const normalizedRequestedCode = normalizeCode(sessionCode);
|
||||||
|
const fallbackCode = normalizeCode(state.sessionCode || persistedContext?.sessionCode || '');
|
||||||
|
state.sessionCode = normalizedRequestedCode || fallbackCode;
|
||||||
|
|
||||||
|
if (!state.sessionCode) {
|
||||||
|
state.loadingSession = false;
|
||||||
|
state.errorMessage = lobbyMessage('session_code_required');
|
||||||
|
return { ...state };
|
||||||
|
}
|
||||||
|
|
||||||
const result = await api.getSession(state.sessionCode);
|
const result = await api.getSession(state.sessionCode);
|
||||||
state.loadingSession = false;
|
state.loadingSession = false;
|
||||||
|
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
state.errorMessage = 'Kunne ikke hente lobby-status.';
|
state.errorMessage = lobbyMessageFromApiPayload(result.error.payload, 'session_fetch_failed');
|
||||||
|
state.gameplayPhase = null;
|
||||||
return { ...state };
|
return { ...state };
|
||||||
}
|
}
|
||||||
|
|
||||||
state.session = result.data;
|
state.session = result.data;
|
||||||
|
state.gameplayPhase = deriveGameplayPhase(result.data);
|
||||||
|
state.sessionCode = normalizeCode(result.data.session.code);
|
||||||
|
|
||||||
|
if (persistedContext && state.sessionCode === normalizeCode(persistedContext.sessionCode)) {
|
||||||
|
sessionContextStore.set({ ...persistedContext, sessionCode: state.sessionCode });
|
||||||
|
}
|
||||||
|
|
||||||
return { ...state };
|
return { ...state };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,30 +86,53 @@ export function createVerticalSliceController(api: ApiClient): VerticalSliceCont
|
|||||||
state.joinState = 'loading';
|
state.joinState = 'loading';
|
||||||
state.errorMessage = null;
|
state.errorMessage = null;
|
||||||
|
|
||||||
const join = await api.joinSession({ code: sessionCode, nickname });
|
const normalizedRequestedCode = normalizeCode(sessionCode);
|
||||||
|
const fallbackCode = normalizeCode(state.sessionCode || persistedContext?.sessionCode || '');
|
||||||
|
const requestCode = normalizedRequestedCode || fallbackCode;
|
||||||
|
|
||||||
|
const join = await api.joinSession({ code: requestCode, nickname });
|
||||||
if (!join.ok) {
|
if (!join.ok) {
|
||||||
state.joinState = 'error';
|
state.joinState = 'error';
|
||||||
state.errorMessage = 'Join fejlede. Tjek kode eller nickname og prøv igen.';
|
state.errorMessage = lobbyMessageFromApiPayload(join.error.payload, 'join_failed');
|
||||||
return { ...state };
|
return { ...state };
|
||||||
}
|
}
|
||||||
|
|
||||||
state.joinState = 'success';
|
state.joinState = 'success';
|
||||||
return hydrateLobby(sessionCode);
|
state.sessionCode = normalizeCode(join.data.session.code || requestCode);
|
||||||
|
|
||||||
|
const nextContext: SessionContextInput = {
|
||||||
|
sessionCode: state.sessionCode,
|
||||||
|
playerId: join.data.player.id,
|
||||||
|
token: join.data.player.session_token
|
||||||
|
};
|
||||||
|
sessionContextStore.set(nextContext);
|
||||||
|
|
||||||
|
return hydrateLobby(state.sessionCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function startRound(sessionCode: string, categorySlug: string): Promise<VerticalSliceState> {
|
async function startRound(sessionCode: string, categorySlug: string): Promise<VerticalSliceState> {
|
||||||
state.startRoundState = 'loading';
|
state.startRoundState = 'loading';
|
||||||
state.errorMessage = null;
|
state.errorMessage = null;
|
||||||
|
|
||||||
const start = await api.startRound(sessionCode, { category_slug: categorySlug });
|
const normalizedRequestedCode = normalizeCode(sessionCode);
|
||||||
|
const fallbackCode = normalizeCode(state.sessionCode || persistedContext?.sessionCode || '');
|
||||||
|
const codeToUse = normalizedRequestedCode || fallbackCode;
|
||||||
|
|
||||||
|
if (!codeToUse) {
|
||||||
|
state.startRoundState = 'error';
|
||||||
|
state.errorMessage = lobbyMessage('session_code_required');
|
||||||
|
return { ...state };
|
||||||
|
}
|
||||||
|
|
||||||
|
const start = await api.startRound(codeToUse, { category_slug: categorySlug });
|
||||||
if (!start.ok) {
|
if (!start.ok) {
|
||||||
state.startRoundState = 'error';
|
state.startRoundState = 'error';
|
||||||
state.errorMessage = 'Kunne ikke starte runden. Opdatér lobbyen og prøv igen.';
|
state.errorMessage = lobbyMessageFromApiPayload(start.error.payload, 'start_round_failed');
|
||||||
return { ...state };
|
return { ...state };
|
||||||
}
|
}
|
||||||
|
|
||||||
state.startRoundState = 'success';
|
state.startRoundState = 'success';
|
||||||
return hydrateLobby(sessionCode);
|
return hydrateLobby(codeToUse);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -85,3 +142,5 @@ export function createVerticalSliceController(api: ApiClient): VerticalSliceCont
|
|||||||
startRound
|
startRound
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type { SessionContext };
|
||||||
|
|||||||
@@ -49,7 +49,27 @@ describe('createAngularApiClient', () => {
|
|||||||
throw { status: 404, error: { error: 'Not found' } };
|
throw { status: 404, error: { error: 'Not found' } };
|
||||||
});
|
});
|
||||||
|
|
||||||
const http = { get };
|
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: '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;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw { status: 404, error: { error: 'Not found' } };
|
||||||
|
});
|
||||||
|
|
||||||
|
const http = { get, post };
|
||||||
const client = createAngularApiClient(http as AngularHttpClientLike);
|
const client = createAngularApiClient(http as AngularHttpClientLike);
|
||||||
|
|
||||||
const health = await client.health();
|
const health = await client.health();
|
||||||
@@ -67,26 +87,272 @@ describe('createAngularApiClient', () => {
|
|||||||
expect(session.data.phase_view_model.host.can_start_round).toBe(true);
|
expect(session.data.phase_view_model.host.can_start_round).toBe(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const join = await client.joinSession({ code: ' abcd12 ', nickname: ' Maja ' });
|
||||||
|
expect(join.ok).toBe(true);
|
||||||
|
|
||||||
|
const start = await client.startRound(' abcd12 ', { category_slug: 'history' });
|
||||||
|
expect(start.ok).toBe(true);
|
||||||
|
|
||||||
expect(get).toHaveBeenNthCalledWith(1, '/healthz', { withCredentials: true });
|
expect(get).toHaveBeenNthCalledWith(1, '/healthz', { withCredentials: true });
|
||||||
expect(get).toHaveBeenNthCalledWith(2, '/lobby/sessions/ABCD12', { withCredentials: true });
|
expect(get).toHaveBeenNthCalledWith(2, '/lobby/sessions/ABCD12', { 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 }
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('normalizes baseUrl with trailing slash to keep Django endpoint paths canonical', async () => {
|
||||||
|
const get = vi.fn<AngularHttpClientLike['get']>(async <T>(url: string) => {
|
||||||
|
if (url === '/api/healthz') {
|
||||||
|
return { ok: true, service: 'partyhub' } as T;
|
||||||
|
}
|
||||||
|
if (url === '/api/lobby/sessions/ABCD12') {
|
||||||
|
return {
|
||||||
|
session: { code: 'ABCD12', status: 'lobby', host_id: 1, current_round: 1, players_count: 2 },
|
||||||
|
players: [],
|
||||||
|
round_question: null,
|
||||||
|
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: 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: true,
|
||||||
|
can_submit_lie: false,
|
||||||
|
can_submit_guess: false,
|
||||||
|
can_view_final_result: false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} as T;
|
||||||
|
}
|
||||||
|
throw { status: 404, error: { error: 'Not found' } };
|
||||||
|
});
|
||||||
|
|
||||||
|
const post = vi.fn<AngularHttpClientLike['post']>(async <T>(url: string) => {
|
||||||
|
if (url === '/api/lobby/sessions/join') {
|
||||||
|
return {
|
||||||
|
player: { id: 9, nickname: 'Maja', session_token: 'token-1', score: 0 },
|
||||||
|
session: { code: 'ABCD12', status: 'lobby' }
|
||||||
|
} as T;
|
||||||
|
}
|
||||||
|
if (url === '/api/lobby/sessions/ABCD12/rounds/start') {
|
||||||
|
return {
|
||||||
|
session: { code: 'ABCD12', status: 'lie', current_round: 1 },
|
||||||
|
round: { number: 1, category: { slug: 'history', name: 'History' } }
|
||||||
|
} as T;
|
||||||
|
}
|
||||||
|
throw { status: 404, error: { error: 'Not found' } };
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = createAngularApiClient({ get, post } as AngularHttpClientLike, '/api/');
|
||||||
|
|
||||||
|
await client.health();
|
||||||
|
await client.getSession('abcd12');
|
||||||
|
await client.joinSession({ code: 'abcd12', nickname: 'Maja' });
|
||||||
|
await client.startRound('abcd12', { category_slug: 'history' });
|
||||||
|
|
||||||
|
expect(get).toHaveBeenNthCalledWith(1, '/api/healthz', { withCredentials: true });
|
||||||
|
expect(get).toHaveBeenNthCalledWith(2, '/api/lobby/sessions/ABCD12', { withCredentials: true });
|
||||||
|
expect(post).toHaveBeenNthCalledWith(
|
||||||
|
1,
|
||||||
|
'/api/lobby/sessions/join',
|
||||||
|
{ code: 'ABCD12', nickname: 'Maja' },
|
||||||
|
{ withCredentials: true }
|
||||||
|
);
|
||||||
|
expect(post).toHaveBeenNthCalledWith(
|
||||||
|
2,
|
||||||
|
'/api/lobby/sessions/ABCD12/rounds/start',
|
||||||
|
{ category_slug: 'history' },
|
||||||
|
{ withCredentials: true }
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns parse error when successful payload breaks typed contract', async () => {
|
||||||
|
const http = {
|
||||||
|
get: vi.fn<AngularHttpClientLike['get']>(async <T>() => ({ ok: true } as T)),
|
||||||
|
post: vi.fn<AngularHttpClientLike['post']>(async <T>() => ({ ok: true } as T))
|
||||||
|
};
|
||||||
|
|
||||||
|
const client = createAngularApiClient(http as AngularHttpClientLike);
|
||||||
|
const session = await client.getSession('ABCD12');
|
||||||
|
|
||||||
|
expect(session.ok).toBe(false);
|
||||||
|
if (!session.ok) {
|
||||||
|
expect(session.status).toBe(200);
|
||||||
|
expect(session.error.kind).toBe('parse');
|
||||||
|
expect(session.error.message).toContain('Invalid API contract');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('maps host/player gameplay endpoints through typed response mappers', async () => {
|
||||||
|
const get = vi.fn<AngularHttpClientLike['get']>(async <T>(url: string) => {
|
||||||
|
if (url === '/lobby/sessions/ABCD12/scoreboard') {
|
||||||
|
return {
|
||||||
|
session: { code: 'ABCD12', status: 'reveal', current_round: 1 },
|
||||||
|
leaderboard: [
|
||||||
|
{ id: 2, nickname: 'Maja', score: 11 },
|
||||||
|
{ id: 3, nickname: 'Bo', score: 7 }
|
||||||
|
]
|
||||||
|
} 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/ABCD12/questions/show') {
|
||||||
|
expect(body).toEqual({});
|
||||||
|
return {
|
||||||
|
round_question: {
|
||||||
|
id: 77,
|
||||||
|
prompt: 'Prompt?',
|
||||||
|
round_number: 1,
|
||||||
|
shown_at: '2026-03-01T16:00:00Z',
|
||||||
|
lie_deadline_at: '2026-03-01T16: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: 3,
|
||||||
|
leaderboard: [{ id: 2, nickname: 'Maja', score: 11 }]
|
||||||
|
} as T;
|
||||||
|
}
|
||||||
|
if (url === '/lobby/sessions/ABCD12/rounds/next') {
|
||||||
|
expect(body).toEqual({});
|
||||||
|
return { session: { code: 'ABCD12', status: 'lobby', 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: 2, nickname: 'Maja', score: 15 },
|
||||||
|
leaderboard: [{ id: 2, nickname: 'Maja', score: 15 }]
|
||||||
|
} as T;
|
||||||
|
}
|
||||||
|
if (url === '/lobby/sessions/ABCD12/questions/77/lies/submit') {
|
||||||
|
expect(body).toEqual({ player_id: 9, session_token: 'tok', text: 'my lie' });
|
||||||
|
return {
|
||||||
|
lie: {
|
||||||
|
id: 100,
|
||||||
|
player_id: 9,
|
||||||
|
round_question_id: 77,
|
||||||
|
text: 'my lie',
|
||||||
|
created_at: '2026-03-01T16:00:10Z'
|
||||||
|
},
|
||||||
|
window: { lie_deadline_at: '2026-03-01T16:00:30Z' }
|
||||||
|
} as T;
|
||||||
|
}
|
||||||
|
if (url === '/lobby/sessions/ABCD12/questions/77/guesses/submit') {
|
||||||
|
expect(body).toEqual({ player_id: 9, session_token: 'tok', selected_text: 'A' });
|
||||||
|
return {
|
||||||
|
guess: {
|
||||||
|
id: 200,
|
||||||
|
player_id: 9,
|
||||||
|
round_question_id: 77,
|
||||||
|
selected_text: 'A',
|
||||||
|
is_correct: false,
|
||||||
|
fooled_player_id: 3,
|
||||||
|
created_at: '2026-03-01T16:01:00Z'
|
||||||
|
},
|
||||||
|
window: { guess_deadline_at: '2026-03-01T16:01:30Z' }
|
||||||
|
} as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw { status: 404, error: { error: 'Not found' } };
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = createAngularApiClient({ get, post } as AngularHttpClientLike);
|
||||||
|
|
||||||
|
const showQuestion = await client.showQuestion('abcd12');
|
||||||
|
expect(showQuestion.ok).toBe(true);
|
||||||
|
|
||||||
|
const mixAnswers = await client.mixAnswers('abcd12', 77);
|
||||||
|
expect(mixAnswers.ok).toBe(true);
|
||||||
|
|
||||||
|
const calculateScores = await client.calculateScores('abcd12', 77);
|
||||||
|
expect(calculateScores.ok).toBe(true);
|
||||||
|
|
||||||
|
const scoreboard = await client.getScoreboard('abcd12');
|
||||||
|
expect(scoreboard.ok).toBe(true);
|
||||||
|
|
||||||
|
const nextRound = await client.startNextRound('abcd12');
|
||||||
|
expect(nextRound.ok).toBe(true);
|
||||||
|
|
||||||
|
const finish = await client.finishGame('abcd12');
|
||||||
|
expect(finish.ok).toBe(true);
|
||||||
|
|
||||||
|
const submitLie = await client.submitLie('abcd12', 77, { player_id: 9, session_token: 'tok', text: 'my lie' });
|
||||||
|
expect(submitLie.ok).toBe(true);
|
||||||
|
|
||||||
|
const submitGuess = await client.submitGuess('abcd12', 77, {
|
||||||
|
player_id: 9,
|
||||||
|
session_token: 'tok',
|
||||||
|
selected_text: 'A'
|
||||||
|
});
|
||||||
|
expect(submitGuess.ok).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('maps HttpErrorResponse-style failures to ApiResult errors', async () => {
|
it('maps HttpErrorResponse-style failures to ApiResult errors', async () => {
|
||||||
const http = {
|
const http = {
|
||||||
get: vi.fn<AngularHttpClientLike['get']>(async () => {
|
get: vi.fn<AngularHttpClientLike['get']>(async () => {
|
||||||
throw { status: 503, message: 'Service unavailable', error: { error: 'maintenance' } };
|
throw { status: 503, message: 'Service unavailable', error: { error: 'maintenance' } };
|
||||||
|
}),
|
||||||
|
post: vi.fn<AngularHttpClientLike['post']>(async () => {
|
||||||
|
throw { status: 403, message: 'Forbidden', error: { error: 'Only host can start round' } };
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
|
|
||||||
const client = createAngularApiClient(http as AngularHttpClientLike);
|
const client = createAngularApiClient(http as AngularHttpClientLike);
|
||||||
const result = await client.health();
|
const health = await client.health();
|
||||||
|
|
||||||
expect(result.ok).toBe(false);
|
expect(health.ok).toBe(false);
|
||||||
if (!result.ok) {
|
if (!health.ok) {
|
||||||
expect(result.status).toBe(503);
|
expect(health.status).toBe(503);
|
||||||
expect(result.error.kind).toBe('http');
|
expect(health.error.kind).toBe('http');
|
||||||
expect(result.error.payload).toEqual({ error: 'maintenance' });
|
expect(health.error.payload).toEqual({ error: 'maintenance' });
|
||||||
expect(result.error.message).toContain('Service unavailable');
|
expect(health.error.message).toContain('Service unavailable');
|
||||||
|
}
|
||||||
|
|
||||||
|
const start = await client.startRound('ABCD12', { category_slug: 'history' });
|
||||||
|
expect(start.ok).toBe(false);
|
||||||
|
if (!start.ok) {
|
||||||
|
expect(start.status).toBe(403);
|
||||||
|
expect(start.error.kind).toBe('http');
|
||||||
|
expect(start.error.payload).toEqual({ error: 'Only host can start round' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -74,6 +74,12 @@ beforeAll(async () => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (req.url === '/lobby/sessions/BADMAP' && req.method === 'GET') {
|
||||||
|
res.writeHead(200, { 'content-type': 'application/json' });
|
||||||
|
res.end(JSON.stringify({ session: { code: 'BADMAP' } }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (req.url?.startsWith('/lobby/sessions/')) {
|
if (req.url?.startsWith('/lobby/sessions/')) {
|
||||||
res.writeHead(404, { 'content-type': 'application/json' });
|
res.writeHead(404, { 'content-type': 'application/json' });
|
||||||
res.end(JSON.stringify({ error: 'Session not found' }));
|
res.end(JSON.stringify({ error: 'Session not found' }));
|
||||||
@@ -123,6 +129,18 @@ describe('createApiClient', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('returns parse error when response violates typed contract', async () => {
|
||||||
|
const client = createApiClient(baseUrl);
|
||||||
|
|
||||||
|
const invalid = await client.getSession('badmap');
|
||||||
|
expect(invalid.ok).toBe(false);
|
||||||
|
if (!invalid.ok) {
|
||||||
|
expect(invalid.status).toBe(200);
|
||||||
|
expect(invalid.error.kind).toBe('parse');
|
||||||
|
expect(invalid.error.message).toContain('Invalid API contract');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
it('returns consistent HTTP error shape for 4xx/5xx', async () => {
|
it('returns consistent HTTP error shape for 4xx/5xx', async () => {
|
||||||
const client = createApiClient(baseUrl);
|
const client = createApiClient(baseUrl);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import {
|
||||||
|
allowedGameplayEvents,
|
||||||
|
deriveGameplayPhase,
|
||||||
|
transitionGameplayPhase,
|
||||||
|
type GameplayPhase
|
||||||
|
} from '../src/spa/gameplay-phase-machine';
|
||||||
|
|
||||||
|
describe('gameplay phase machine skeleton', () => {
|
||||||
|
it('supports canonical phase progression lie -> guess -> reveal -> scoreboard -> lie', () => {
|
||||||
|
let phase: GameplayPhase = 'lie';
|
||||||
|
|
||||||
|
phase = transitionGameplayPhase(phase, 'LIES_LOCKED').phase;
|
||||||
|
expect(phase).toBe('guess');
|
||||||
|
|
||||||
|
phase = transitionGameplayPhase(phase, 'GUESSES_LOCKED').phase;
|
||||||
|
expect(phase).toBe('reveal');
|
||||||
|
|
||||||
|
phase = transitionGameplayPhase(phase, 'SCOREBOARD_READY').phase;
|
||||||
|
expect(phase).toBe('scoreboard');
|
||||||
|
|
||||||
|
phase = transitionGameplayPhase(phase, 'NEXT_ROUND').phase;
|
||||||
|
expect(phase).toBe('lie');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps state unchanged for invalid transition events', () => {
|
||||||
|
const transition = transitionGameplayPhase('lie', 'NEXT_ROUND');
|
||||||
|
expect(transition.phase).toBe('lie');
|
||||||
|
expect(transition.changed).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('exposes allowed events per phase', () => {
|
||||||
|
expect(allowedGameplayEvents('guess')).toEqual(['GUESSES_LOCKED']);
|
||||||
|
expect(allowedGameplayEvents('scoreboard')).toEqual(['NEXT_ROUND']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('derives gameplay phase from session detail status', () => {
|
||||||
|
expect(
|
||||||
|
deriveGameplayPhase({
|
||||||
|
session: { code: 'ABCD12', status: 'lie', host_id: 1, current_round: 1, players_count: 3 },
|
||||||
|
players: [],
|
||||||
|
round_question: null,
|
||||||
|
phase_view_model: {
|
||||||
|
status: 'lie',
|
||||||
|
round_number: 1,
|
||||||
|
players_count: 3,
|
||||||
|
constraints: {
|
||||||
|
min_players_to_start: 3,
|
||||||
|
max_players_mvp: 5,
|
||||||
|
min_players_reached: true,
|
||||||
|
max_players_allowed: true
|
||||||
|
},
|
||||||
|
host: {
|
||||||
|
can_start_round: false,
|
||||||
|
can_show_question: true,
|
||||||
|
can_mix_answers: true,
|
||||||
|
can_calculate_scores: false,
|
||||||
|
can_reveal_scoreboard: false,
|
||||||
|
can_start_next_round: false,
|
||||||
|
can_finish_game: false
|
||||||
|
},
|
||||||
|
player: {
|
||||||
|
can_join: false,
|
||||||
|
can_submit_lie: true,
|
||||||
|
can_submit_guess: false,
|
||||||
|
can_view_final_result: false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
).toBe('lie');
|
||||||
|
|
||||||
|
expect(
|
||||||
|
deriveGameplayPhase({
|
||||||
|
session: { code: 'ABCD12', status: 'finished', host_id: 1, current_round: 1, players_count: 3 },
|
||||||
|
players: [],
|
||||||
|
round_question: null,
|
||||||
|
phase_view_model: {
|
||||||
|
status: 'finished',
|
||||||
|
round_number: 1,
|
||||||
|
players_count: 3,
|
||||||
|
constraints: {
|
||||||
|
min_players_to_start: 3,
|
||||||
|
max_players_mvp: 5,
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
).toBe('scoreboard');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { createSessionContextStore, type StorageLike } from '../src/spa/session-context-store';
|
||||||
|
|
||||||
|
function makeMemoryStorage(seed?: Record<string, string>): StorageLike {
|
||||||
|
const memory = new Map<string, string>(Object.entries(seed ?? {}));
|
||||||
|
return {
|
||||||
|
getItem: (key: string) => memory.get(key) ?? null,
|
||||||
|
setItem: (key: string, value: string) => {
|
||||||
|
memory.set(key, value);
|
||||||
|
},
|
||||||
|
removeItem: (key: string) => {
|
||||||
|
memory.delete(key);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('session context store', () => {
|
||||||
|
it('normalizes and persists sessionCode/playerId/token', () => {
|
||||||
|
const storage = makeMemoryStorage();
|
||||||
|
const store = createSessionContextStore(storage, 'ctx');
|
||||||
|
|
||||||
|
const value = store.set({ sessionCode: ' abcd12 ', playerId: 12, token: ' token-1 ' });
|
||||||
|
expect(value).toEqual({ sessionCode: 'ABCD12', playerId: 12, token: 'token-1' });
|
||||||
|
|
||||||
|
expect(store.get()).toEqual({ sessionCode: 'ABCD12', playerId: 12, token: 'token-1' });
|
||||||
|
expect(storage.getItem('ctx')).toBe('{"sessionCode":"ABCD12","playerId":12,"token":"token-1"}');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('loads from storage and clears invalid payloads', () => {
|
||||||
|
const storage = makeMemoryStorage({ ctx: '{"sessionCode":"","playerId":0,"token":""}' });
|
||||||
|
const store = createSessionContextStore(storage, 'ctx');
|
||||||
|
|
||||||
|
expect(store.get()).toBeNull();
|
||||||
|
expect(storage.getItem('ctx')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('supports clear()', () => {
|
||||||
|
const storage = makeMemoryStorage();
|
||||||
|
const store = createSessionContextStore(storage, 'ctx');
|
||||||
|
|
||||||
|
store.set({ sessionCode: 'ABCD12', playerId: 3, token: 'token-3' });
|
||||||
|
store.clear();
|
||||||
|
|
||||||
|
expect(store.get()).toBeNull();
|
||||||
|
expect(storage.getItem('ctx')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects invalid context writes', () => {
|
||||||
|
const store = createSessionContextStore();
|
||||||
|
expect(() => store.set({ sessionCode: '', playerId: 1, token: 'token-1' })).toThrow('sessionCode is required');
|
||||||
|
expect(() => store.set({ sessionCode: 'ABCD12', playerId: 0, token: 'token-1' })).toThrow(
|
||||||
|
'playerId must be a positive integer'
|
||||||
|
);
|
||||||
|
expect(() => store.set({ sessionCode: 'ABCD12', playerId: 2, token: ' ' })).toThrow('token is required');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,5 +1,9 @@
|
|||||||
import { describe, expect, it, vi } from 'vitest';
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
import { createVerticalSliceController } from '../src/spa/vertical-slice';
|
import {
|
||||||
|
createVerticalSliceController,
|
||||||
|
type SessionContext,
|
||||||
|
type SessionContextStore
|
||||||
|
} from '../src/spa/vertical-slice';
|
||||||
import type { ApiClient } from '../src/api/client';
|
import type { ApiClient } from '../src/api/client';
|
||||||
|
|
||||||
function makeApiMock(overrides?: Partial<ApiClient>): ApiClient {
|
function makeApiMock(overrides?: Partial<ApiClient>): ApiClient {
|
||||||
@@ -58,7 +62,50 @@ function makeApiMock(overrides?: Partial<ApiClient>): ApiClient {
|
|||||||
return { ...base, ...overrides };
|
return { ...base, ...overrides };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function makeSessionContextStore(initial: SessionContext | null = null): SessionContextStore {
|
||||||
|
let value = initial;
|
||||||
|
return {
|
||||||
|
get: vi.fn(() => value),
|
||||||
|
set: vi.fn((next: SessionContext) => {
|
||||||
|
value = next;
|
||||||
|
return next;
|
||||||
|
})
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
describe('vertical slice controller: lobby -> join -> start round', () => {
|
describe('vertical slice controller: lobby -> join -> start round', () => {
|
||||||
|
it('uses createSessionContextStore by default (no manual injection)', async () => {
|
||||||
|
vi.resetModules();
|
||||||
|
const defaultStore = {
|
||||||
|
get: vi.fn(() => null),
|
||||||
|
set: vi.fn((next: SessionContext) => next),
|
||||||
|
clear: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
vi.doMock('../src/spa/session-context-store', async () => {
|
||||||
|
const actual = await vi.importActual<typeof import('../src/spa/session-context-store')>('../src/spa/session-context-store');
|
||||||
|
return {
|
||||||
|
...actual,
|
||||||
|
createSessionContextStore: vi.fn(() => defaultStore)
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const { createVerticalSliceController: createControllerWithMock } = await import('../src/spa/vertical-slice');
|
||||||
|
const api = makeApiMock();
|
||||||
|
const controller = createControllerWithMock(api);
|
||||||
|
|
||||||
|
await controller.joinLobby('ABCD12', 'Maja');
|
||||||
|
|
||||||
|
expect(defaultStore.set).toHaveBeenCalledWith({
|
||||||
|
sessionCode: 'ABCD12',
|
||||||
|
playerId: 9,
|
||||||
|
token: 'token-1'
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.doUnmock('../src/spa/session-context-store');
|
||||||
|
vi.resetModules();
|
||||||
|
});
|
||||||
|
|
||||||
it('tracks loading and success state for join + start flow', async () => {
|
it('tracks loading and success state for join + start flow', async () => {
|
||||||
const api = makeApiMock();
|
const api = makeApiMock();
|
||||||
const controller = createVerticalSliceController(api);
|
const controller = createVerticalSliceController(api);
|
||||||
@@ -79,12 +126,42 @@ describe('vertical slice controller: lobby -> join -> start round', () => {
|
|||||||
expect(postStart.startRoundState).toBe('success');
|
expect(postStart.startRoundState).toBe('success');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('persists session context after join and syncs normalized session code', async () => {
|
||||||
|
const api = makeApiMock();
|
||||||
|
const sessionContextStore = makeSessionContextStore();
|
||||||
|
const controller = createVerticalSliceController(api, sessionContextStore);
|
||||||
|
|
||||||
|
await controller.joinLobby('abcd12', 'Maja');
|
||||||
|
|
||||||
|
expect(sessionContextStore.set).toHaveBeenCalledWith({
|
||||||
|
sessionCode: 'ABCD12',
|
||||||
|
playerId: 9,
|
||||||
|
token: 'token-1'
|
||||||
|
});
|
||||||
|
expect(controller.getState().sessionCode).toBe('ABCD12');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses stored session code as fallback for join + hydrate flow when input code is empty', async () => {
|
||||||
|
const api = makeApiMock();
|
||||||
|
const sessionContextStore = makeSessionContextStore({
|
||||||
|
sessionCode: 'wxyz99',
|
||||||
|
playerId: 5,
|
||||||
|
token: 'token-old'
|
||||||
|
});
|
||||||
|
const controller = createVerticalSliceController(api, sessionContextStore);
|
||||||
|
|
||||||
|
await controller.joinLobby(' ', 'Maja');
|
||||||
|
|
||||||
|
expect(api.joinSession).toHaveBeenCalledWith({ code: 'WXYZ99', nickname: 'Maja' });
|
||||||
|
expect(api.getSession).toHaveBeenCalledWith('ABCD12');
|
||||||
|
});
|
||||||
|
|
||||||
it('surfaces a friendly error when join fails', async () => {
|
it('surfaces a friendly error when join fails', async () => {
|
||||||
const api = makeApiMock({
|
const api = makeApiMock({
|
||||||
joinSession: vi.fn().mockResolvedValue({
|
joinSession: vi.fn().mockResolvedValue({
|
||||||
ok: false,
|
ok: false,
|
||||||
status: 404,
|
status: 404,
|
||||||
error: { kind: 'http', status: 404, message: 'HTTP 404', payload: { error: 'Session not found' } }
|
error: { kind: 'http', status: 404, message: 'HTTP 404', payload: { error: 'Session not found', error_code: 'session_not_found' } }
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -93,7 +170,7 @@ describe('vertical slice controller: lobby -> join -> start round', () => {
|
|||||||
|
|
||||||
const state = controller.getState();
|
const state = controller.getState();
|
||||||
expect(state.joinState).toBe('error');
|
expect(state.joinState).toBe('error');
|
||||||
expect(state.errorMessage).toContain('Join fejlede');
|
expect(state.errorMessage).toBe('Session code is invalid or the session no longer exists.');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('surfaces a friendly error when round start fails', async () => {
|
it('surfaces a friendly error when round start fails', async () => {
|
||||||
@@ -101,7 +178,7 @@ describe('vertical slice controller: lobby -> join -> start round', () => {
|
|||||||
startRound: vi.fn().mockResolvedValue({
|
startRound: vi.fn().mockResolvedValue({
|
||||||
ok: false,
|
ok: false,
|
||||||
status: 400,
|
status: 400,
|
||||||
error: { kind: 'http', status: 400, message: 'HTTP 400', payload: { error: 'Round can only be started from lobby' } }
|
error: { kind: 'http', status: 400, message: 'HTTP 400', payload: { error: 'Round can only be started from lobby', error_code: 'round_start_invalid_phase' } }
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -110,6 +187,41 @@ describe('vertical slice controller: lobby -> join -> start round', () => {
|
|||||||
|
|
||||||
const state = controller.getState();
|
const state = controller.getState();
|
||||||
expect(state.startRoundState).toBe('error');
|
expect(state.startRoundState).toBe('error');
|
||||||
expect(state.errorMessage).toContain('Kunne ikke starte runden');
|
expect(state.errorMessage).toBe('Could not start round. Refresh the lobby and try again.');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows local validation error and avoids API call when hydrating without any session code', async () => {
|
||||||
|
const api = makeApiMock();
|
||||||
|
const controller = createVerticalSliceController(api, makeSessionContextStore(null));
|
||||||
|
|
||||||
|
await controller.hydrateLobby(' ');
|
||||||
|
|
||||||
|
const state = controller.getState();
|
||||||
|
expect(state.errorMessage).toBe('Session code is required.');
|
||||||
|
expect(state.loadingSession).toBe(false);
|
||||||
|
expect(api.getSession).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows local validation error and avoids API call when starting round without any session code', async () => {
|
||||||
|
const api = makeApiMock();
|
||||||
|
const controller = createVerticalSliceController(api, makeSessionContextStore(null));
|
||||||
|
|
||||||
|
await controller.startRound(' ', 'history');
|
||||||
|
|
||||||
|
const state = controller.getState();
|
||||||
|
expect(state.startRoundState).toBe('error');
|
||||||
|
expect(state.errorMessage).toBe('Session code is required.');
|
||||||
|
expect(api.startRound).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses joined session code when starting round without a reload', async () => {
|
||||||
|
const api = makeApiMock();
|
||||||
|
const controller = createVerticalSliceController(api);
|
||||||
|
|
||||||
|
await controller.joinLobby(' abcd12 ', 'Maja');
|
||||||
|
await controller.startRound('', 'history');
|
||||||
|
|
||||||
|
expect(api.startRound).toHaveBeenCalledWith('ABCD12', { category_slug: 'history' });
|
||||||
|
expect(controller.getState().sessionCode).toBe('ABCD12');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,10 +3,11 @@
|
|||||||
"target": "ES2022",
|
"target": "ES2022",
|
||||||
"module": "ES2022",
|
"module": "ES2022",
|
||||||
"moduleResolution": "bundler",
|
"moduleResolution": "bundler",
|
||||||
|
"resolveJsonModule": true,
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"lib": ["ES2022", "DOM"],
|
"lib": ["ES2022", "DOM"],
|
||||||
"types": ["vitest/globals", "node"]
|
"types": ["vitest/globals", "node"]
|
||||||
},
|
},
|
||||||
"include": ["src", "tests"]
|
"include": ["src", "tests", "../shared/i18n/*.json"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import json
|
||||||
|
from functools import lru_cache
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from django.http import JsonResponse
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def lobby_i18n_catalog() -> dict:
|
||||||
|
catalog_path = Path(__file__).resolve().parents[1] / "shared" / "i18n" / "lobby.json"
|
||||||
|
with catalog_path.open(encoding="utf-8") as handle:
|
||||||
|
return json.load(handle)
|
||||||
|
|
||||||
|
|
||||||
|
def lobby_i18n_errors() -> dict:
|
||||||
|
return lobby_i18n_catalog().get("backend", {}).get("error_codes", {})
|
||||||
|
|
||||||
|
|
||||||
|
def api_error(*, code: str, message: str, status: int) -> JsonResponse:
|
||||||
|
return JsonResponse({"error": message, "error_code": code}, status=status)
|
||||||
@@ -1,5 +1,16 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="da"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>WPP Host</title></head>
|
<html lang="da"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>WPP Host</title>
|
||||||
|
<style>
|
||||||
|
.critical-card { margin: 10px 0 12px; padding: 10px; border-radius: 10px; border: 1px solid #cbd5e1; background: #f8fafc; }
|
||||||
|
.critical-card h2 { margin: 0 0 6px; font-size: 1rem; }
|
||||||
|
.critical-card p { margin: 0; color: #334155; }
|
||||||
|
.skeleton-line { position: relative; overflow: hidden; height: 12px; border-radius: 999px; margin-top: 8px; background: #e2e8f0; }
|
||||||
|
.skeleton-line:first-of-type { margin-top: 4px; }
|
||||||
|
.skeleton-line.short { width: 60%; }
|
||||||
|
.skeleton-line::after { content: ""; position: absolute; inset: 0; transform: translateX(-100%); background: linear-gradient(90deg, rgba(226,232,240,0) 0%, rgba(255,255,255,0.85) 45%, rgba(226,232,240,0) 100%); animation: wppShimmer 1.2s infinite; }
|
||||||
|
@keyframes wppShimmer { to { transform: translateX(100%); } }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h1>Host panel (MVP)</h1>
|
<h1>Host panel (MVP)</h1>
|
||||||
<p>Kræver login som host-bruger.</p>
|
<p>Kræver login som host-bruger.</p>
|
||||||
@@ -32,6 +43,18 @@
|
|||||||
<button id="hostRecoverRetryBtn" type="button" onclick="recoverHostShell('retry')">Prøv gendan</button>
|
<button id="hostRecoverRetryBtn" type="button" onclick="recoverHostShell('retry')">Prøv gendan</button>
|
||||||
<button id="hostRecoverReloadBtn" type="button" onclick="recoverHostShell('reload')">Genindlæs siden</button>
|
<button id="hostRecoverReloadBtn" type="button" onclick="recoverHostShell('reload')">Genindlæs siden</button>
|
||||||
</div>
|
</div>
|
||||||
|
<section id="hostCriticalSkeleton" class="critical-card" aria-live="polite">
|
||||||
|
<h2>Indlæser host-overblik…</h2>
|
||||||
|
<div class="skeleton-line"></div>
|
||||||
|
<div class="skeleton-line"></div>
|
||||||
|
<div class="skeleton-line short"></div>
|
||||||
|
</section>
|
||||||
|
<section id="hostCriticalView" class="critical-card" style="display:none" aria-live="polite">
|
||||||
|
<h2>Host-overblik</h2>
|
||||||
|
<p id="hostCriticalPhase">Fase: afventer</p>
|
||||||
|
<p id="hostCriticalPlayers">Spillere: afventer</p>
|
||||||
|
<p id="hostCriticalRound">Aktiv round question: afventer</p>
|
||||||
|
</section>
|
||||||
<pre id="out">Klar.</pre>
|
<pre id="out">Klar.</pre>
|
||||||
<script>
|
<script>
|
||||||
var currentSessionStatus="";
|
var currentSessionStatus="";
|
||||||
@@ -45,6 +68,14 @@ var hostShellRouteHint="";
|
|||||||
var HOST_SHELL_ROUTES={lobby:"lobby",lie:"lie",guess:"guess",reveal:"reveal",finished:"finished"};
|
var HOST_SHELL_ROUTES={lobby:"lobby",lie:"lie",guess:"guess",reveal:"reveal",finished:"finished"};
|
||||||
var hostShellFatalError=false;
|
var hostShellFatalError=false;
|
||||||
var hostShellRecoverInFlight=false;
|
var hostShellRecoverInFlight=false;
|
||||||
|
var hostCriticalHydrated=false;
|
||||||
|
function setHostCriticalLoading(isLoading){var skeleton=document.getElementById("hostCriticalSkeleton");var view=document.getElementById("hostCriticalView");if(!skeleton||!view){return;}skeleton.style.display=isLoading?"block":"none";view.style.display=isLoading?"none":"block";}
|
||||||
|
function hydrateHostCriticalView(data){var session=(data&&data.session)||{};var phaseEl=document.getElementById("hostCriticalPhase");var playersEl=document.getElementById("hostCriticalPlayers");var roundEl=document.getElementById("hostCriticalRound");if(phaseEl){phaseEl.textContent="Fase: "+phaseLabel(currentSessionStatus||session.status||"");}
|
||||||
|
if(playersEl){playersEl.textContent="Spillere: "+(typeof session.players_count==="number"?session.players_count:"ukendt");}
|
||||||
|
if(roundEl){roundEl.textContent="Aktiv round question: "+(rq()||"ikke valgt");}
|
||||||
|
hostCriticalHydrated=true;
|
||||||
|
setHostCriticalLoading(false);
|
||||||
|
}
|
||||||
function csrf(){var m=document.cookie.match(/csrftoken=([^;]+)/);return m?m[1]:"";}
|
function csrf(){var m=document.cookie.match(/csrftoken=([^;]+)/);return m?m[1]:"";}
|
||||||
function updateHostShellErrorBoundary(){var panel=document.getElementById("hostShellErrorBoundary");var retryBtn=document.getElementById("hostRecoverRetryBtn");var reloadBtn=document.getElementById("hostRecoverReloadBtn");if(!panel||!retryBtn||!reloadBtn){return;}panel.style.display=hostShellFatalError?"block":"none";retryBtn.disabled=hostShellRecoverInFlight||sessionDetailInFlight||!code();reloadBtn.disabled=hostShellRecoverInFlight;}
|
function updateHostShellErrorBoundary(){var panel=document.getElementById("hostShellErrorBoundary");var retryBtn=document.getElementById("hostRecoverRetryBtn");var reloadBtn=document.getElementById("hostRecoverReloadBtn");if(!panel||!retryBtn||!reloadBtn){return;}panel.style.display=hostShellFatalError?"block":"none";retryBtn.disabled=hostShellRecoverInFlight||sessionDetailInFlight||!code();reloadBtn.disabled=hostShellRecoverInFlight;}
|
||||||
function setHostShellFatalError(detail){hostShellFatalError=true;var out=document.getElementById("out");if(out){out.textContent=JSON.stringify({status:0,data:{error:"host_shell_runtime_error",detail:detail||"Ukendt runtime-fejl"}},null,2);}var hint=document.getElementById("hostErrorHint");if(hint){hint.textContent="Fejl: Kritisk app-fejl. Brug recover-handlingerne for at fortsætte.";}updateHostShellErrorBoundary();}
|
function setHostShellFatalError(detail){hostShellFatalError=true;var out=document.getElementById("out");if(out){out.textContent=JSON.stringify({status:0,data:{error:"host_shell_runtime_error",detail:detail||"Ukendt runtime-fejl"}},null,2);}var hint=document.getElementById("hostErrorHint");if(hint){hint.textContent="Fejl: Kritisk app-fejl. Brug recover-handlingerne for at fortsætte.";}updateHostShellErrorBoundary();}
|
||||||
@@ -74,7 +105,7 @@ function updatePhaseStatus(){var el=document.getElementById("phaseStatus");syncH
|
|||||||
function syncStartRoundGuard(data){var btn=document.getElementById("startRoundBtn");var hint=document.getElementById("startRoundHint");var status=document.getElementById("playerCountStatus");if(!btn||!hint||!status){return;}var count=(data&&data.session&&typeof data.session.players_count==="number")?data.session.players_count:null;var phase=currentSessionStatus||"";if(phase&&phase!=="lobby"){btn.disabled=true;status.textContent=count===null?"Spillere i session: ukendt":"Spillere i session: "+count;hint.textContent="Start runde er kun tilladt i lobby-fasen.";return;}if(count===null){btn.disabled=true;status.textContent="Spillere i session: ukendt";hint.textContent="Opdatér session-status for at validere 3-5 spillere.";return;}status.textContent="Spillere i session: "+count;if(count<3){btn.disabled=true;hint.textContent="Mangler spillere: kræver mindst 3 for at starte runde.";return;}if(count>5){btn.disabled=true;hint.textContent="For mange spillere: maks 5 i MVP før runde-start.";return;}btn.disabled=false;hint.textContent="Klar: spillerantal er indenfor 3-5 til runde-start.";}
|
function syncStartRoundGuard(data){var btn=document.getElementById("startRoundBtn");var hint=document.getElementById("startRoundHint");var status=document.getElementById("playerCountStatus");if(!btn||!hint||!status){return;}var count=(data&&data.session&&typeof data.session.players_count==="number")?data.session.players_count:null;var phase=currentSessionStatus||"";if(phase&&phase!=="lobby"){btn.disabled=true;status.textContent=count===null?"Spillere i session: ukendt":"Spillere i session: "+count;hint.textContent="Start runde er kun tilladt i lobby-fasen.";return;}if(count===null){btn.disabled=true;status.textContent="Spillere i session: ukendt";hint.textContent="Opdatér session-status for at validere 3-5 spillere.";return;}status.textContent="Spillere i session: "+count;if(count<3){btn.disabled=true;hint.textContent="Mangler spillere: kræver mindst 3 for at starte runde.";return;}if(count>5){btn.disabled=true;hint.textContent="For mange spillere: maks 5 i MVP før runde-start.";return;}btn.disabled=false;hint.textContent="Klar: spillerantal er indenfor 3-5 til runde-start.";}
|
||||||
|
|
||||||
function updateHostActionState(){updateCreateSessionState();var hasCode=!!code();var hasRound=!!rq();var phase=currentSessionStatus||"";var showQuestionBtn=document.getElementById("showQuestionBtn");var mixAnswersBtn=document.getElementById("mixAnswersBtn");var calcScoresBtn=document.getElementById("calcScoresBtn");var showScoreboardBtn=document.getElementById("showScoreboardBtn");var nextRoundBtn=document.getElementById("nextRoundBtn");var finishGameBtn=document.getElementById("finishGameBtn");var roundQuestionInput=document.getElementById("roundQuestionId");var roundQuestionGuardHint=document.getElementById("roundQuestionGuardHint");var categorySelect=document.getElementById("category");var categoryGuardHint=document.getElementById("categoryGuardHint");var hint=document.getElementById("hostActionHint");if(showQuestionBtn){showQuestionBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="lie";}if(showScoreboardBtn){showScoreboardBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="reveal";}if(nextRoundBtn){nextRoundBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="reveal";}if(finishGameBtn){finishGameBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="reveal";}if(mixAnswersBtn){mixAnswersBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||!hasRound||(phase!=="lie"&&phase!=="guess");}if(calcScoresBtn){calcScoresBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||!hasRound||phase!=="guess";}var canEditRoundQuestion=!!hasCode&&(phase==="lie"||phase==="guess"||phase==="reveal");if(roundQuestionInput){roundQuestionInput.disabled=hostActionInFlight||sessionDetailInFlight||!canEditRoundQuestion;}if(roundQuestionGuardHint){if(hostActionInFlight){roundQuestionGuardHint.textContent="Round question-id er låst mens en handling kører.";}else if(sessionDetailInFlight){roundQuestionGuardHint.textContent="Round question-id er låst mens session-opdatering kører.";}else if(!hasCode){roundQuestionGuardHint.textContent="Angiv sessionkode for at redigere round question-id.";}else if(!phase){roundQuestionGuardHint.textContent="Opdatér session-status for round question-id.";}else if(canEditRoundQuestion){roundQuestionGuardHint.textContent="Round question-id kan redigeres i fase: "+phaseLabel(phase)+".";}else{roundQuestionGuardHint.textContent="Round question-id er låst i fase: "+phaseLabel(phase)+".";}}if(categorySelect){categorySelect.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="lobby";}if(categoryGuardHint){if(hostActionInFlight){categoryGuardHint.textContent="Kategori er midlertidigt låst mens en handling kører.";}else if(sessionDetailInFlight){categoryGuardHint.textContent="Kategori er låst mens session-opdatering kører.";}else if(!hasCode){categoryGuardHint.textContent="Angiv sessionkode for at låse kategori til lobby-fasen.";}else if(phase==="lobby"){categoryGuardHint.textContent="Kategori kan vælges i lobby-fasen.";}else if(!phase){categoryGuardHint.textContent="Opdatér session-status for at validere kategori-lås.";}else{categoryGuardHint.textContent="Kategori er låst udenfor lobby-fasen.";}}if(!hint){return;}if(hostActionInFlight){hint.textContent="Handling kører… afvent svar før næste klik.";return;}if(sessionDetailInFlight){hint.textContent="Host-actions er låst mens session-opdatering kører.";return;}if(!hasCode){hint.textContent="Angiv sessionkode for at aktivere host-actions.";return;}if(!phase){hint.textContent="Opdatér session-status for fasebaserede host-actions.";return;}if(phase==="finished"){hint.textContent="Spillet er afsluttet: gameplay-actions er låst.";return;}if((phase==="lie"||phase==="guess")&&!hasRound){hint.textContent="Round question id mangler: mix/beregn score er låst.";return;}if(hostShellRouteHint){hint.textContent=hostShellRouteHint;return;}hint.textContent="Host-actions er klar for fase: "+phaseLabel(phase)+".";}
|
function updateHostActionState(){updateCreateSessionState();var hasCode=!!code();var hasRound=!!rq();var phase=currentSessionStatus||"";var showQuestionBtn=document.getElementById("showQuestionBtn");var mixAnswersBtn=document.getElementById("mixAnswersBtn");var calcScoresBtn=document.getElementById("calcScoresBtn");var showScoreboardBtn=document.getElementById("showScoreboardBtn");var nextRoundBtn=document.getElementById("nextRoundBtn");var finishGameBtn=document.getElementById("finishGameBtn");var roundQuestionInput=document.getElementById("roundQuestionId");var roundQuestionGuardHint=document.getElementById("roundQuestionGuardHint");var categorySelect=document.getElementById("category");var categoryGuardHint=document.getElementById("categoryGuardHint");var hint=document.getElementById("hostActionHint");if(showQuestionBtn){showQuestionBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="lie";}if(showScoreboardBtn){showScoreboardBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="reveal";}if(nextRoundBtn){nextRoundBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="reveal";}if(finishGameBtn){finishGameBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="reveal";}if(mixAnswersBtn){mixAnswersBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||!hasRound||(phase!=="lie"&&phase!=="guess");}if(calcScoresBtn){calcScoresBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||!hasRound||phase!=="guess";}var canEditRoundQuestion=!!hasCode&&(phase==="lie"||phase==="guess"||phase==="reveal");if(roundQuestionInput){roundQuestionInput.disabled=hostActionInFlight||sessionDetailInFlight||!canEditRoundQuestion;}if(roundQuestionGuardHint){if(hostActionInFlight){roundQuestionGuardHint.textContent="Round question-id er låst mens en handling kører.";}else if(sessionDetailInFlight){roundQuestionGuardHint.textContent="Round question-id er låst mens session-opdatering kører.";}else if(!hasCode){roundQuestionGuardHint.textContent="Angiv sessionkode for at redigere round question-id.";}else if(!phase){roundQuestionGuardHint.textContent="Opdatér session-status for round question-id.";}else if(canEditRoundQuestion){roundQuestionGuardHint.textContent="Round question-id kan redigeres i fase: "+phaseLabel(phase)+".";}else{roundQuestionGuardHint.textContent="Round question-id er låst i fase: "+phaseLabel(phase)+".";}}if(categorySelect){categorySelect.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="lobby";}if(categoryGuardHint){if(hostActionInFlight){categoryGuardHint.textContent="Kategori er midlertidigt låst mens en handling kører.";}else if(sessionDetailInFlight){categoryGuardHint.textContent="Kategori er låst mens session-opdatering kører.";}else if(!hasCode){categoryGuardHint.textContent="Angiv sessionkode for at låse kategori til lobby-fasen.";}else if(phase==="lobby"){categoryGuardHint.textContent="Kategori kan vælges i lobby-fasen.";}else if(!phase){categoryGuardHint.textContent="Opdatér session-status for at validere kategori-lås.";}else{categoryGuardHint.textContent="Kategori er låst udenfor lobby-fasen.";}}if(!hint){return;}if(hostActionInFlight){hint.textContent="Handling kører… afvent svar før næste klik.";return;}if(sessionDetailInFlight){hint.textContent="Host-actions er låst mens session-opdatering kører.";return;}if(!hasCode){hint.textContent="Angiv sessionkode for at aktivere host-actions.";return;}if(!phase){hint.textContent="Opdatér session-status for fasebaserede host-actions.";return;}if(phase==="finished"){hint.textContent="Spillet er afsluttet: gameplay-actions er låst.";return;}if((phase==="lie"||phase==="guess")&&!hasRound){hint.textContent="Round question id mangler: mix/beregn score er låst.";return;}if(hostShellRouteHint){hint.textContent=hostShellRouteHint;return;}hint.textContent="Host-actions er klar for fase: "+phaseLabel(phase)+".";}
|
||||||
async function api(path,method,payload){var o={method:method||"GET",headers:{"Accept":"application/json"}};if(payload!==null){o.headers["Content-Type"]="application/json";o.headers["X-CSRFToken"]=csrf();o.body=JSON.stringify(payload);}var r=await fetch(path,o);var d=await r.json().catch(function(){return {};});var isSessionDetailRead=(method||"GET")==="GET"&&/^\/lobby\/sessions\/[A-Z0-9]+$/.test(path);if(isSessionDetailRead){markSessionRefresh(r.status);}document.getElementById("out").textContent=JSON.stringify({status:r.status,data:d},null,2);if(d.session&&d.session.code){document.getElementById("code").value=d.session.code;}if(d.session&&d.session.status){currentSessionStatus=d.session.status;}if(d.round_question&&d.round_question.id){document.getElementById("roundQuestionId").value=d.round_question.id;}updateErrorHint(r.status,d);updatePhaseStatus();syncStartRoundGuard(d);updateHostActionState();if(currentSessionStatus==="finished"&&autoRefreshEnabled){stopAutoRefresh("Auto-refresh stoppet: spillet er afsluttet.");}else{updateAutoRefreshUi();}if(hostShellFatalError){clearHostShellFatalError();}saveHostContext();return d;}
|
async function api(path,method,payload){var o={method:method||"GET",headers:{"Accept":"application/json"}};if(payload!==null){o.headers["Content-Type"]="application/json";o.headers["X-CSRFToken"]=csrf();o.body=JSON.stringify(payload);}var r=await fetch(path,o);var d=await r.json().catch(function(){return {};});var isSessionDetailRead=(method||"GET")==="GET"&&/^\/lobby\/sessions\/[A-Z0-9]+$/.test(path);if(isSessionDetailRead){markSessionRefresh(r.status);}document.getElementById("out").textContent=JSON.stringify({status:r.status,data:d},null,2);if(d.session&&d.session.code){document.getElementById("code").value=d.session.code;}if(d.session&&d.session.status){currentSessionStatus=d.session.status;}if(d.round_question&&d.round_question.id){document.getElementById("roundQuestionId").value=d.round_question.id;}if(d.session){hydrateHostCriticalView(d);}updateErrorHint(r.status,d);updatePhaseStatus();syncStartRoundGuard(d);updateHostActionState();if(currentSessionStatus==="finished"&&autoRefreshEnabled){stopAutoRefresh("Auto-refresh stoppet: spillet er afsluttet.");}else{updateAutoRefreshUi();}if(hostShellFatalError){clearHostShellFatalError();}saveHostContext();return d;}
|
||||||
|
|
||||||
function withHostActionLock(fn){if(hostActionInFlight){return Promise.resolve({error:"host_action_in_flight"});}hostActionInFlight=true;updateHostActionState();return Promise.resolve().then(fn).finally(function(){hostActionInFlight=false;updateHostActionState();});}
|
function withHostActionLock(fn){if(hostActionInFlight){return Promise.resolve({error:"host_action_in_flight"});}hostActionInFlight=true;updateHostActionState();return Promise.resolve().then(fn).finally(function(){hostActionInFlight=false;updateHostActionState();});}
|
||||||
function createSession(){return withHostActionLock(function(){return api("/lobby/sessions/create","POST",{});});}
|
function createSession(){return withHostActionLock(function(){return api("/lobby/sessions/create","POST",{});});}
|
||||||
@@ -90,7 +121,8 @@ function finishGame(){return withHostActionLock(function(){return api("/lobby/se
|
|||||||
|
|
||||||
window.addEventListener("error",function(event){setHostShellFatalError((event&&event.message)||"Ukendt runtime-fejl");});
|
window.addEventListener("error",function(event){setHostShellFatalError((event&&event.message)||"Ukendt runtime-fejl");});
|
||||||
window.addEventListener("unhandledrejection",function(event){var reason=event&&event.reason;var detail=(reason&&reason.message)||String(reason||"Unhandled promise rejection");setHostShellFatalError(detail);});
|
window.addEventListener("unhandledrejection",function(event){var reason=event&&event.reason;var detail=(reason&&reason.message)||String(reason||"Unhandled promise rejection");setHostShellFatalError(detail);});
|
||||||
|
setHostCriticalLoading(true);
|
||||||
updatePhaseStatus();syncHostShellRoute();syncStartRoundGuard(null);updateHostActionState();updateCreateSessionState();updateSessionDetailState();updateAutoRefreshUi();updateLastRefreshStatus();updateHostShellErrorBoundary();
|
updatePhaseStatus();syncHostShellRoute();syncStartRoundGuard(null);updateHostActionState();updateCreateSessionState();updateSessionDetailState();updateAutoRefreshUi();updateLastRefreshStatus();updateHostShellErrorBoundary();
|
||||||
if(restoreHostContext()){updatePhaseStatus();syncHostShellRoute();if(autoRefreshEnabled){startAutoRefresh();}sessionDetail();}else{saveHostContext();}
|
if(restoreHostContext()){updatePhaseStatus();syncHostShellRoute();if(autoRefreshEnabled){startAutoRefresh();}sessionDetail();}else{saveHostContext();setTimeout(function(){if(!hostCriticalHydrated){hydrateHostCriticalView({session:{status:currentSessionStatus,players_count:null}});}},350);}
|
||||||
</script>
|
</script>
|
||||||
</body></html>
|
</body></html>
|
||||||
|
|||||||
@@ -17,6 +17,14 @@
|
|||||||
#playerShellErrorBoundary button[disabled] { opacity: 0.55; cursor: not-allowed; }
|
#playerShellErrorBoundary button[disabled] { opacity: 0.55; cursor: not-allowed; }
|
||||||
#lieStatus.locked { color: #0a5f2d; font-weight: 600; }
|
#lieStatus.locked { color: #0a5f2d; font-weight: 600; }
|
||||||
#guessStatus.locked { color: #0a5f2d; font-weight: 600; }
|
#guessStatus.locked { color: #0a5f2d; font-weight: 600; }
|
||||||
|
.critical-card { margin: 10px 0 12px; padding: 10px; border-radius: 10px; border: 1px solid #cbd5e1; background: #f8fafc; }
|
||||||
|
.critical-card h2 { margin: 0 0 6px; font-size: 1rem; }
|
||||||
|
.critical-card p { margin: 0; color: #334155; }
|
||||||
|
.skeleton-line { position: relative; overflow: hidden; height: 12px; border-radius: 999px; margin-top: 8px; background: #e2e8f0; }
|
||||||
|
.skeleton-line:first-of-type { margin-top: 4px; }
|
||||||
|
.skeleton-line.short { width: 60%; }
|
||||||
|
.skeleton-line::after { content: ""; position: absolute; inset: 0; transform: translateX(-100%); background: linear-gradient(90deg, rgba(226,232,240,0) 0%, rgba(255,255,255,0.85) 45%, rgba(226,232,240,0) 100%); animation: wppShimmer 1.2s infinite; }
|
||||||
|
@keyframes wppShimmer { to { transform: translateX(100%); } }
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
@@ -49,6 +57,18 @@
|
|||||||
<button id="playerRecoverRetryBtn" type="button" onclick="recoverPlayerShell('retry')">Prøv gendan</button>
|
<button id="playerRecoverRetryBtn" type="button" onclick="recoverPlayerShell('retry')">Prøv gendan</button>
|
||||||
<button id="playerRecoverReloadBtn" type="button" onclick="recoverPlayerShell('reload')">Genindlæs siden</button>
|
<button id="playerRecoverReloadBtn" type="button" onclick="recoverPlayerShell('reload')">Genindlæs siden</button>
|
||||||
</div>
|
</div>
|
||||||
|
<section id="playerCriticalSkeleton" class="critical-card" aria-live="polite">
|
||||||
|
<h2>Indlæser spiller-overblik…</h2>
|
||||||
|
<div class="skeleton-line"></div>
|
||||||
|
<div class="skeleton-line"></div>
|
||||||
|
<div class="skeleton-line short"></div>
|
||||||
|
</section>
|
||||||
|
<section id="playerCriticalView" class="critical-card" style="display:none" aria-live="polite">
|
||||||
|
<h2>Spiller-overblik</h2>
|
||||||
|
<p id="playerCriticalPhase">Fase: afventer</p>
|
||||||
|
<p id="playerCriticalRound">Round question: afventer</p>
|
||||||
|
<p id="playerCriticalJoin">Join-status: afventer</p>
|
||||||
|
</section>
|
||||||
<pre id="out">Klar.</pre>
|
<pre id="out">Klar.</pre>
|
||||||
<script>
|
<script>
|
||||||
var availableAnswers=[];
|
var availableAnswers=[];
|
||||||
@@ -68,6 +88,14 @@ var connectionLost=false;
|
|||||||
var connectionRetryInFlight=false;
|
var connectionRetryInFlight=false;
|
||||||
var playerShellFatalError=false;
|
var playerShellFatalError=false;
|
||||||
var playerShellRecoverInFlight=false;
|
var playerShellRecoverInFlight=false;
|
||||||
|
var playerCriticalHydrated=false;
|
||||||
|
function setPlayerCriticalLoading(isLoading){var skeleton=document.getElementById("playerCriticalSkeleton");var view=document.getElementById("playerCriticalView");if(!skeleton||!view){return;}skeleton.style.display=isLoading?"block":"none";view.style.display=isLoading?"none":"block";}
|
||||||
|
function hydratePlayerCriticalView(data){var phaseEl=document.getElementById("playerCriticalPhase");var roundEl=document.getElementById("playerCriticalRound");var joinEl=document.getElementById("playerCriticalJoin");if(phaseEl){phaseEl.textContent="Fase: "+phaseLabel(currentSessionStatus||((data&&data.session&&data.session.status)||""));}
|
||||||
|
if(roundEl){roundEl.textContent="Round question: "+(rq()||"afventer");}
|
||||||
|
if(joinEl){joinEl.textContent="Join-status: "+(isPlayerContextLocked()?"låst/aktiv":"ikke låst");}
|
||||||
|
playerCriticalHydrated=true;
|
||||||
|
setPlayerCriticalLoading(false);
|
||||||
|
}
|
||||||
function code(){return document.getElementById("code").value.trim().toUpperCase();}
|
function code(){return document.getElementById("code").value.trim().toUpperCase();}
|
||||||
function updatePlayerShellErrorBoundary(){var panel=document.getElementById("playerShellErrorBoundary");var retryBtn=document.getElementById("playerRecoverRetryBtn");var reloadBtn=document.getElementById("playerRecoverReloadBtn");if(!panel||!retryBtn||!reloadBtn){return;}panel.style.display=playerShellFatalError?"block":"none";retryBtn.disabled=playerShellRecoverInFlight||sessionDetailInFlight||joinInFlight||!code();reloadBtn.disabled=playerShellRecoverInFlight;}
|
function updatePlayerShellErrorBoundary(){var panel=document.getElementById("playerShellErrorBoundary");var retryBtn=document.getElementById("playerRecoverRetryBtn");var reloadBtn=document.getElementById("playerRecoverReloadBtn");if(!panel||!retryBtn||!reloadBtn){return;}panel.style.display=playerShellFatalError?"block":"none";retryBtn.disabled=playerShellRecoverInFlight||sessionDetailInFlight||joinInFlight||!code();reloadBtn.disabled=playerShellRecoverInFlight;}
|
||||||
function setPlayerShellFatalError(detail){playerShellFatalError=true;var out=document.getElementById("out");if(out){out.textContent=JSON.stringify({status:0,data:{error:"player_shell_runtime_error",detail:detail||"Ukendt runtime-fejl"}},null,2);}var hint=document.getElementById("playerErrorHint");if(hint){hint.textContent="Fejl: Kritisk app-fejl. Brug recover-handlingerne for at fortsætte.";}updatePlayerShellErrorBoundary();}
|
function setPlayerShellFatalError(detail){playerShellFatalError=true;var out=document.getElementById("out");if(out){out.textContent=JSON.stringify({status:0,data:{error:"player_shell_runtime_error",detail:detail||"Ukendt runtime-fejl"}},null,2);}var hint=document.getElementById("playerErrorHint");if(hint){hint.textContent="Fejl: Kritisk app-fejl. Brug recover-handlingerne for at fortsætte.";}updatePlayerShellErrorBoundary();}
|
||||||
@@ -115,7 +143,7 @@ function updateGuessSubmitState(){var selected=document.getElementById("guessTex
|
|||||||
function setGuess(text,submitted){document.getElementById("guessText").value=text||"";if(typeof submitted==="boolean"){guessSubmitted=submitted;}var buttons=document.querySelectorAll("#answerOptions button");buttons.forEach(function(btn){btn.classList.toggle("active",btn.dataset.answer===text);});updateGuessSubmitState();
|
function setGuess(text,submitted){document.getElementById("guessText").value=text||"";if(typeof submitted==="boolean"){guessSubmitted=submitted;}var buttons=document.querySelectorAll("#answerOptions button");buttons.forEach(function(btn){btn.classList.toggle("active",btn.dataset.answer===text);});updateGuessSubmitState();
|
||||||
updateJoinState();}
|
updateJoinState();}
|
||||||
function renderAnswerOptions(roundQuestion){var wrap=document.getElementById("answerOptions");wrap.innerHTML="";availableAnswers=[];guessSubmitted=false;setGuess("",false);lieSubmitted=false;setLieState("",false);if(!roundQuestion||!Array.isArray(roundQuestion.answers)){updateGuessSubmitState();updateLieSubmitState();return;}roundQuestion.answers.forEach(function(item){if(!item||!item.text){return;}availableAnswers.push(item.text);var btn=document.createElement("button");btn.type="button";btn.dataset.answer=item.text;btn.textContent=item.text;btn.onclick=function(){if(guessSubmitted){return;}setGuess(item.text,false);persistGuessState(item.text,false);};wrap.appendChild(btn);});var saved=loadGuessState();if(saved&&availableAnswers.indexOf(saved.selected_text)!==-1){setGuess(saved.selected_text,!!saved.submitted);}updateGuessSubmitState();}
|
function renderAnswerOptions(roundQuestion){var wrap=document.getElementById("answerOptions");wrap.innerHTML="";availableAnswers=[];guessSubmitted=false;setGuess("",false);lieSubmitted=false;setLieState("",false);if(!roundQuestion||!Array.isArray(roundQuestion.answers)){updateGuessSubmitState();updateLieSubmitState();return;}roundQuestion.answers.forEach(function(item){if(!item||!item.text){return;}availableAnswers.push(item.text);var btn=document.createElement("button");btn.type="button";btn.dataset.answer=item.text;btn.textContent=item.text;btn.onclick=function(){if(guessSubmitted){return;}setGuess(item.text,false);persistGuessState(item.text,false);};wrap.appendChild(btn);});var saved=loadGuessState();if(saved&&availableAnswers.indexOf(saved.selected_text)!==-1){setGuess(saved.selected_text,!!saved.submitted);}updateGuessSubmitState();}
|
||||||
async function api(path,method,payload){var o={method:method||"GET",headers:{"Accept":"application/json"}};if(payload!==null){o.headers["Content-Type"]="application/json";o.body=JSON.stringify(payload);}try{var r=await fetch(path,o);var d=await r.json().catch(function(){return {};});var isSessionDetailRead=(method||"GET")==="GET"&&/^\/lobby\/sessions\/[A-Z0-9]+$/.test(path);if(isSessionDetailRead){markPlayerSessionRefresh(r.status);}document.getElementById("out").textContent=JSON.stringify({status:r.status,data:d},null,2);if(d.player&&d.player.id){document.getElementById("playerId").value=d.player.id;}if(d.player&&d.player.session_token){document.getElementById("sessionToken").value=d.player.session_token;}if(d.round_question&&d.round_question.id){document.getElementById("roundQuestionId").value=d.round_question.id;}if(d.session&&d.session.status){currentSessionStatus=d.session.status;}if(d.round_question){renderAnswerOptions(d.round_question);var savedLie=loadLieState();if(savedLie){setLieState(savedLie.text||"",!!savedLie.submitted);}}else{document.getElementById("roundQuestionId").value="";renderAnswerOptions(null);}if(d.guess&&d.guess.round_question_id){document.getElementById("roundQuestionId").value=d.guess.round_question_id;setGuess(d.guess.selected_text||"",true);persistGuessState(d.guess.selected_text||"",true);}updateRoundContextHint();updatePlayerErrorHint(r.status,d);updatePhaseStatus();updateLieSubmitState();updateGuessSubmitState();if(currentSessionStatus==="finished"&&playerAutoRefreshEnabled){stopPlayerAutoRefresh("Auto-refresh stoppet: spillet er afsluttet.");}else{updatePlayerAutoRefreshUi();}if(playerShellFatalError){clearPlayerShellFatalError();}savePlayerContext();return d;}catch(err){setConnectionLost(true);if((method||"GET")==="GET"&&/^\/lobby\/sessions\/[A-Z0-9]+$/.test(path)){markPlayerSessionRefresh(0);}document.getElementById("out").textContent=JSON.stringify({status:0,data:{error:"connection_lost",detail:"Kunne ikke kontakte serveren."}},null,2);document.getElementById("playerErrorHint").textContent="Fejl: Mistede forbindelsen til serveren. Prøv igen.";updateSessionDetailState();throw err;}}
|
async function api(path,method,payload){var o={method:method||"GET",headers:{"Accept":"application/json"}};if(payload!==null){o.headers["Content-Type"]="application/json";o.body=JSON.stringify(payload);}try{var r=await fetch(path,o);var d=await r.json().catch(function(){return {};});var isSessionDetailRead=(method||"GET")==="GET"&&/^\/lobby\/sessions\/[A-Z0-9]+$/.test(path);if(isSessionDetailRead){markPlayerSessionRefresh(r.status);}document.getElementById("out").textContent=JSON.stringify({status:r.status,data:d},null,2);if(d.player&&d.player.id){document.getElementById("playerId").value=d.player.id;}if(d.player&&d.player.session_token){document.getElementById("sessionToken").value=d.player.session_token;}if(d.round_question&&d.round_question.id){document.getElementById("roundQuestionId").value=d.round_question.id;}if(d.session&&d.session.status){currentSessionStatus=d.session.status;}if(d.round_question){renderAnswerOptions(d.round_question);var savedLie=loadLieState();if(savedLie){setLieState(savedLie.text||"",!!savedLie.submitted);}}else{document.getElementById("roundQuestionId").value="";renderAnswerOptions(null);}if(d.guess&&d.guess.round_question_id){document.getElementById("roundQuestionId").value=d.guess.round_question_id;setGuess(d.guess.selected_text||"",true);persistGuessState(d.guess.selected_text||"",true);}hydratePlayerCriticalView(d);updateRoundContextHint();updatePlayerErrorHint(r.status,d);updatePhaseStatus();updateLieSubmitState();updateGuessSubmitState();if(currentSessionStatus==="finished"&&playerAutoRefreshEnabled){stopPlayerAutoRefresh("Auto-refresh stoppet: spillet er afsluttet.");}else{updatePlayerAutoRefreshUi();}if(playerShellFatalError){clearPlayerShellFatalError();}savePlayerContext();return d;}catch(err){setConnectionLost(true);if((method||"GET")==="GET"&&/^\/lobby\/sessions\/[A-Z0-9]+$/.test(path)){markPlayerSessionRefresh(0);}document.getElementById("out").textContent=JSON.stringify({status:0,data:{error:"connection_lost",detail:"Kunne ikke kontakte serveren."}},null,2);document.getElementById("playerErrorHint").textContent="Fejl: Mistede forbindelsen til serveren. Prøv igen.";updateSessionDetailState();throw err;}}
|
||||||
function joinSession(){if(joinInFlight){return Promise.resolve({error:"join_in_flight"});}if(!canAttemptJoin()){updateJoinState();return Promise.resolve({error:"missing_join_input"});}if(pid()&&document.getElementById("sessionToken").value.trim()){updateJoinState();return Promise.resolve({error:"already_joined_client"});}joinInFlight=true;updateJoinState();updatePlayerAutoRefreshUi();return api("/lobby/sessions/join","POST",{code:code(),nickname:document.getElementById("nickname").value.trim()}).then(function(d){joinInFlight=false;if(d&&d.player&&d.player.id){updateJoinState();updatePlayerAutoRefreshUi();return d;}updateJoinState();updatePlayerAutoRefreshUi();document.getElementById("joinStatus").textContent="Join fejlede – prøv igen.";return d;}).catch(function(err){joinInFlight=false;updateJoinState();updatePlayerAutoRefreshUi();document.getElementById("joinStatus").textContent="Join fejlede – prøv igen.";throw err;});}
|
function joinSession(){if(joinInFlight){return Promise.resolve({error:"join_in_flight"});}if(!canAttemptJoin()){updateJoinState();return Promise.resolve({error:"missing_join_input"});}if(pid()&&document.getElementById("sessionToken").value.trim()){updateJoinState();return Promise.resolve({error:"already_joined_client"});}joinInFlight=true;updateJoinState();updatePlayerAutoRefreshUi();return api("/lobby/sessions/join","POST",{code:code(),nickname:document.getElementById("nickname").value.trim()}).then(function(d){joinInFlight=false;if(d&&d.player&&d.player.id){updateJoinState();updatePlayerAutoRefreshUi();return d;}updateJoinState();updatePlayerAutoRefreshUi();document.getElementById("joinStatus").textContent="Join fejlede – prøv igen.";return d;}).catch(function(err){joinInFlight=false;updateJoinState();updatePlayerAutoRefreshUi();document.getElementById("joinStatus").textContent="Join fejlede – prøv igen.";throw err;});}
|
||||||
function sessionDetail(){if(!code()){updateSessionDetailState();return Promise.resolve({error:"missing_session_code"});}if(sessionDetailInFlight){return Promise.resolve({error:"session_detail_in_flight"});}sessionDetailInFlight=true;updateSessionDetailState();return api("/lobby/sessions/"+code(),"GET",null).finally(function(){sessionDetailInFlight=false;updateSessionDetailState();});}
|
function sessionDetail(){if(!code()){updateSessionDetailState();return Promise.resolve({error:"missing_session_code"});}if(sessionDetailInFlight){return Promise.resolve({error:"session_detail_in_flight"});}sessionDetailInFlight=true;updateSessionDetailState();return api("/lobby/sessions/"+code(),"GET",null).finally(function(){sessionDetailInFlight=false;updateSessionDetailState();});}
|
||||||
function retryConnection(){if(connectionRetryInFlight||!code()){updateConnectionBanner();return Promise.resolve({error:"retry_unavailable"});}connectionRetryInFlight=true;updateConnectionBanner();return sessionDetail().then(function(result){setConnectionLost(false);return result;}).finally(function(){connectionRetryInFlight=false;updateConnectionBanner();});}
|
function retryConnection(){if(connectionRetryInFlight||!code()){updateConnectionBanner();return Promise.resolve({error:"retry_unavailable"});}connectionRetryInFlight=true;updateConnectionBanner();return sessionDetail().then(function(result){setConnectionLost(false);return result;}).finally(function(){connectionRetryInFlight=false;updateConnectionBanner();});}
|
||||||
@@ -125,6 +153,7 @@ function submitGuess(){if(guessSubmitted){return Promise.resolve({error:"guess_a
|
|||||||
["code","nickname","playerId","sessionToken","roundQuestionId"].forEach(function(fieldId){var field=document.getElementById(fieldId);if(!field){return;}field.addEventListener("input",function(){if(fieldId!=="roundQuestionId"){resetRoundContextForManualChange();}updateLieSubmitState();updateGuessSubmitState();updateJoinState();updateSessionDetailState();savePlayerContext();});field.addEventListener("change",function(){if(fieldId!=="roundQuestionId"){resetRoundContextForManualChange();}updateLieSubmitState();updateGuessSubmitState();updateJoinState();updateSessionDetailState();savePlayerContext();});});
|
["code","nickname","playerId","sessionToken","roundQuestionId"].forEach(function(fieldId){var field=document.getElementById(fieldId);if(!field){return;}field.addEventListener("input",function(){if(fieldId!=="roundQuestionId"){resetRoundContextForManualChange();}updateLieSubmitState();updateGuessSubmitState();updateJoinState();updateSessionDetailState();savePlayerContext();});field.addEventListener("change",function(){if(fieldId!=="roundQuestionId"){resetRoundContextForManualChange();}updateLieSubmitState();updateGuessSubmitState();updateJoinState();updateSessionDetailState();savePlayerContext();});});
|
||||||
window.addEventListener("error",function(event){setPlayerShellFatalError((event&&event.message)||"Ukendt runtime-fejl");});
|
window.addEventListener("error",function(event){setPlayerShellFatalError((event&&event.message)||"Ukendt runtime-fejl");});
|
||||||
window.addEventListener("unhandledrejection",function(event){var reason=event&&event.reason;var detail=(reason&&reason.message)||String(reason||"Unhandled promise rejection");setPlayerShellFatalError(detail);});
|
window.addEventListener("unhandledrejection",function(event){var reason=event&&event.reason;var detail=(reason&&reason.message)||String(reason||"Unhandled promise rejection");setPlayerShellFatalError(detail);});
|
||||||
|
setPlayerCriticalLoading(true);
|
||||||
updatePhaseStatus();
|
updatePhaseStatus();
|
||||||
updateGuessSubmitState();
|
updateGuessSubmitState();
|
||||||
updateJoinState();
|
updateJoinState();
|
||||||
@@ -133,6 +162,6 @@ updatePlayerLastRefreshStatus();
|
|||||||
updateRoundContextHint();
|
updateRoundContextHint();
|
||||||
updateConnectionBanner();
|
updateConnectionBanner();
|
||||||
updatePlayerShellErrorBoundary();
|
updatePlayerShellErrorBoundary();
|
||||||
if(restorePlayerContext()){if(playerAutoRefreshEnabled){startPlayerAutoRefresh();}sessionDetail().catch(function(){});}else{savePlayerContext();}
|
if(restorePlayerContext()){if(playerAutoRefreshEnabled){startPlayerAutoRefresh();}sessionDetail().catch(function(){});}else{savePlayerContext();setTimeout(function(){if(!playerCriticalHydrated){hydratePlayerCriticalView({session:{status:currentSessionStatus}});}},350);}
|
||||||
</script>
|
</script>
|
||||||
</body></html>
|
</body></html>
|
||||||
|
|||||||
@@ -3,10 +3,11 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>WPP SPA</title>
|
<title>WPP SPA Shell</title>
|
||||||
|
<link rel="stylesheet" href="{{ spa_asset_base }}/styles.css">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body data-wpp-shell-route="{{ shell_route }}" data-wpp-shell-kind="{{ shell_kind }}">
|
||||||
<app-root data-wpp-shell-route="{{ shell_route }}"></app-root>
|
<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"></script>
|
<script type="module" src="{{ spa_asset_base }}/main.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -994,8 +994,33 @@ class UiScreenTests(TestCase):
|
|||||||
self.assertEqual(response.status_code, 200)
|
self.assertEqual(response.status_code, 200)
|
||||||
self.assertContains(response, "<app-root")
|
self.assertContains(response, "<app-root")
|
||||||
self.assertContains(response, "data-wpp-shell-route=\"/host\"")
|
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")
|
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):
|
||||||
|
self.client.login(username="host_ui", password="secret123")
|
||||||
|
|
||||||
|
response = self.client.get(
|
||||||
|
reverse("lobby:host_screen_deeplink", kwargs={"spa_path": "guess/round-1"})
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertContains(response, "<app-root")
|
||||||
|
self.assertContains(response, "data-wpp-shell-route=\"/host/guess/round-1\"")
|
||||||
|
self.assertContains(response, "data-wpp-shell-kind=\"host\"")
|
||||||
|
|
||||||
|
@override_settings(USE_SPA_UI=True)
|
||||||
|
def test_host_screen_deeplink_normalizes_redundant_slashes_when_feature_flag_enabled(self):
|
||||||
|
self.client.login(username="host_ui", password="secret123")
|
||||||
|
|
||||||
|
response = self.client.get("/lobby/ui/host//guess///round-1//")
|
||||||
|
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertContains(response, "<app-root")
|
||||||
|
self.assertContains(response, "data-wpp-shell-route=\"/host/guess/round-1\"")
|
||||||
|
self.assertContains(response, "data-wpp-shell-kind=\"host\"")
|
||||||
|
|
||||||
@override_settings(USE_SPA_UI=True)
|
@override_settings(USE_SPA_UI=True)
|
||||||
def test_player_screen_can_render_angular_shell_when_feature_flag_enabled(self):
|
def test_player_screen_can_render_angular_shell_when_feature_flag_enabled(self):
|
||||||
response = self.client.get(reverse("lobby:player_screen"))
|
response = self.client.get(reverse("lobby:player_screen"))
|
||||||
@@ -1003,6 +1028,7 @@ class UiScreenTests(TestCase):
|
|||||||
self.assertEqual(response.status_code, 200)
|
self.assertEqual(response.status_code, 200)
|
||||||
self.assertContains(response, "<app-root")
|
self.assertContains(response, "<app-root")
|
||||||
self.assertContains(response, "data-wpp-shell-route=\"/player\"")
|
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")
|
self.assertContains(response, "/static/frontend/angular/browser/main.js")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+20
-5
@@ -5,15 +5,18 @@ from django.shortcuts import render
|
|||||||
from fupogfakta.models import Category
|
from fupogfakta.models import Category
|
||||||
|
|
||||||
from .feature_flags import use_spa_ui
|
from .feature_flags import use_spa_ui
|
||||||
|
from .i18n import lobby_i18n_catalog
|
||||||
|
|
||||||
|
|
||||||
def _render_spa_shell(request, shell_route: str):
|
def _render_spa_shell(request, shell_route: str, shell_kind: str):
|
||||||
return render(
|
return render(
|
||||||
request,
|
request,
|
||||||
"lobby/spa_shell.html",
|
"lobby/spa_shell.html",
|
||||||
{
|
{
|
||||||
"shell_route": shell_route,
|
"shell_route": shell_route,
|
||||||
|
"shell_kind": shell_kind,
|
||||||
"spa_asset_base": settings.WPP_SPA_ASSET_BASE,
|
"spa_asset_base": settings.WPP_SPA_ASSET_BASE,
|
||||||
|
"lobby_i18n": lobby_i18n_catalog(),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -21,14 +24,26 @@ def _render_spa_shell(request, shell_route: str):
|
|||||||
@login_required
|
@login_required
|
||||||
def host_screen(request, spa_path=None):
|
def host_screen(request, spa_path=None):
|
||||||
if use_spa_ui():
|
if use_spa_ui():
|
||||||
return _render_spa_shell(request, "/host")
|
host_route = "/host"
|
||||||
|
if spa_path:
|
||||||
|
normalized_spa_path = "/".join(segment for segment in spa_path.split("/") if segment)
|
||||||
|
if normalized_spa_path:
|
||||||
|
host_route = f"/host/{normalized_spa_path}"
|
||||||
|
return _render_spa_shell(request, host_route, "host")
|
||||||
|
|
||||||
categories = Category.objects.filter(is_active=True).order_by("name")
|
categories = Category.objects.filter(is_active=True).order_by("name")
|
||||||
return render(request, "lobby/host_screen.html", {"categories": categories})
|
return render(
|
||||||
|
request,
|
||||||
|
"lobby/host_screen.html",
|
||||||
|
{
|
||||||
|
"categories": categories,
|
||||||
|
"lobby_i18n": lobby_i18n_catalog(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def player_screen(request):
|
def player_screen(request):
|
||||||
if use_spa_ui():
|
if use_spa_ui():
|
||||||
return _render_spa_shell(request, "/player")
|
return _render_spa_shell(request, "/player", "player")
|
||||||
|
|
||||||
return render(request, "lobby/player_screen.html")
|
return render(request, "lobby/player_screen.html", {"lobby_i18n": lobby_i18n_catalog()})
|
||||||
|
|||||||
+63
-12
@@ -20,6 +20,8 @@ from fupogfakta.models import (
|
|||||||
ScoreEvent,
|
ScoreEvent,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
from .i18n import api_error, lobby_i18n_errors
|
||||||
|
|
||||||
SESSION_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
|
SESSION_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
|
||||||
SESSION_CODE_LENGTH = 6
|
SESSION_CODE_LENGTH = 6
|
||||||
MAX_CODE_GENERATION_ATTEMPTS = 20
|
MAX_CODE_GENERATION_ATTEMPTS = 20
|
||||||
@@ -29,6 +31,7 @@ JOINABLE_STATUSES = {
|
|||||||
GameSession.Status.GUESS,
|
GameSession.Status.GUESS,
|
||||||
GameSession.Status.REVEAL,
|
GameSession.Status.REVEAL,
|
||||||
}
|
}
|
||||||
|
ERROR_CODES = lobby_i18n_errors()
|
||||||
|
|
||||||
|
|
||||||
def _json_body(request: HttpRequest) -> dict:
|
def _json_body(request: HttpRequest) -> dict:
|
||||||
@@ -124,21 +127,41 @@ def join_session(request: HttpRequest) -> JsonResponse:
|
|||||||
nickname = str(payload.get("nickname", "")).strip()
|
nickname = str(payload.get("nickname", "")).strip()
|
||||||
|
|
||||||
if not code:
|
if not code:
|
||||||
return JsonResponse({"error": "Session code is required"}, status=400)
|
return api_error(
|
||||||
|
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:
|
if len(nickname) < 2 or len(nickname) > 40:
|
||||||
return JsonResponse({"error": "Nickname must be between 2 and 40 characters"}, status=400)
|
return api_error(
|
||||||
|
code=ERROR_CODES.get("nickname_invalid", "nickname_invalid"),
|
||||||
|
message="Nickname must be between 2 and 40 characters",
|
||||||
|
status=400,
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
session = GameSession.objects.get(code=code)
|
session = GameSession.objects.get(code=code)
|
||||||
except GameSession.DoesNotExist:
|
except GameSession.DoesNotExist:
|
||||||
return JsonResponse({"error": "Session not found"}, status=404)
|
return api_error(
|
||||||
|
code=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||||
|
message="Session not found",
|
||||||
|
status=404,
|
||||||
|
)
|
||||||
|
|
||||||
if session.status not in JOINABLE_STATUSES:
|
if session.status not in JOINABLE_STATUSES:
|
||||||
return JsonResponse({"error": "Session is not joinable"}, status=400)
|
return api_error(
|
||||||
|
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():
|
if Player.objects.filter(session=session, nickname__iexact=nickname).exists():
|
||||||
return JsonResponse({"error": "Nickname already taken"}, status=409)
|
return api_error(
|
||||||
|
code=ERROR_CODES.get("nickname_taken", "nickname_taken"),
|
||||||
|
message="Nickname already taken",
|
||||||
|
status=409,
|
||||||
|
)
|
||||||
|
|
||||||
player = Player.objects.create(session=session, nickname=nickname)
|
player = Player.objects.create(session=session, nickname=nickname)
|
||||||
|
|
||||||
@@ -166,7 +189,11 @@ def session_detail(request: HttpRequest, code: str) -> JsonResponse:
|
|||||||
try:
|
try:
|
||||||
session = GameSession.objects.get(code=session_code)
|
session = GameSession.objects.get(code=session_code)
|
||||||
except GameSession.DoesNotExist:
|
except GameSession.DoesNotExist:
|
||||||
return JsonResponse({"error": "Session not found"}, status=404)
|
return api_error(
|
||||||
|
code=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||||
|
message="Session not found",
|
||||||
|
status=404,
|
||||||
|
)
|
||||||
|
|
||||||
players = list(
|
players = list(
|
||||||
session.players.order_by("nickname").values(
|
session.players.order_by("nickname").values(
|
||||||
@@ -223,25 +250,41 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
|
|||||||
category_slug = str(payload.get("category_slug", "")).strip()
|
category_slug = str(payload.get("category_slug", "")).strip()
|
||||||
|
|
||||||
if not category_slug:
|
if not category_slug:
|
||||||
return JsonResponse({"error": "category_slug is required"}, status=400)
|
return api_error(
|
||||||
|
code=ERROR_CODES.get("category_slug_required", "category_slug_required"),
|
||||||
|
message="category_slug is required",
|
||||||
|
status=400,
|
||||||
|
)
|
||||||
|
|
||||||
session_code = _normalize_session_code(code)
|
session_code = _normalize_session_code(code)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
session = GameSession.objects.get(code=session_code)
|
session = GameSession.objects.get(code=session_code)
|
||||||
except GameSession.DoesNotExist:
|
except GameSession.DoesNotExist:
|
||||||
return JsonResponse({"error": "Session not found"}, status=404)
|
return api_error(
|
||||||
|
code=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||||
|
message="Session not found",
|
||||||
|
status=404,
|
||||||
|
)
|
||||||
|
|
||||||
if session.host_id != request.user.id:
|
if session.host_id != request.user.id:
|
||||||
return JsonResponse({"error": "Only host can start round"}, status=403)
|
return JsonResponse({"error": "Only host can start round"}, status=403)
|
||||||
|
|
||||||
if session.status != GameSession.Status.LOBBY:
|
if session.status != GameSession.Status.LOBBY:
|
||||||
return JsonResponse({"error": "Round can only be started from lobby"}, status=400)
|
return api_error(
|
||||||
|
code=ERROR_CODES.get("round_start_invalid_phase", "round_start_invalid_phase"),
|
||||||
|
message="Round can only be started from lobby",
|
||||||
|
status=400,
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
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 JsonResponse({"error": "Category not found"}, status=404)
|
return api_error(
|
||||||
|
code=ERROR_CODES.get("category_not_found", "category_not_found"),
|
||||||
|
message="Category not found",
|
||||||
|
status=404,
|
||||||
|
)
|
||||||
|
|
||||||
if not Question.objects.filter(category=category, is_active=True).exists():
|
if not Question.objects.filter(category=category, is_active=True).exists():
|
||||||
return JsonResponse({"error": "Category has no active questions"}, status=400)
|
return JsonResponse({"error": "Category has no active questions"}, status=400)
|
||||||
@@ -249,7 +292,11 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
|
|||||||
with transaction.atomic():
|
with transaction.atomic():
|
||||||
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 JsonResponse({"error": "Round can only be started from lobby"}, status=400)
|
return api_error(
|
||||||
|
code=ERROR_CODES.get("round_start_invalid_phase", "round_start_invalid_phase"),
|
||||||
|
message="Round can only be started from lobby",
|
||||||
|
status=400,
|
||||||
|
)
|
||||||
|
|
||||||
round_config, created = RoundConfig.objects.get_or_create(
|
round_config, created = RoundConfig.objects.get_or_create(
|
||||||
session=session,
|
session=session,
|
||||||
@@ -257,7 +304,11 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
|
|||||||
defaults={"category": category},
|
defaults={"category": category},
|
||||||
)
|
)
|
||||||
if not created:
|
if not created:
|
||||||
return JsonResponse({"error": "Round already configured"}, status=409)
|
return api_error(
|
||||||
|
code=ERROR_CODES.get("round_already_configured", "round_already_configured"),
|
||||||
|
message="Round already configured",
|
||||||
|
status=409,
|
||||||
|
)
|
||||||
|
|
||||||
session.status = GameSession.Status.LIE
|
session.status = GameSession.Status.LIE
|
||||||
session.save(update_fields=["status"])
|
session.save(update_fields=["status"])
|
||||||
|
|||||||
@@ -99,7 +99,6 @@ STATIC_ROOT = BASE_DIR / 'staticfiles'
|
|||||||
|
|
||||||
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
||||||
|
|
||||||
|
|
||||||
USE_SPA_UI_RAW = env('USE_SPA_UI')
|
USE_SPA_UI_RAW = env('USE_SPA_UI')
|
||||||
if USE_SPA_UI_RAW is None:
|
if USE_SPA_UI_RAW is None:
|
||||||
# Backward-compatible fallback while cutover is rolling out.
|
# Backward-compatible fallback while cutover is rolling out.
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
{
|
||||||
|
"frontend": {
|
||||||
|
"errors": {
|
||||||
|
"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": {
|
||||||
|
"error_codes": {
|
||||||
|
"session_code_required": "session_code_required",
|
||||||
|
"nickname_invalid": "nickname_invalid",
|
||||||
|
"session_not_found": "session_not_found",
|
||||||
|
"session_not_joinable": "session_not_joinable",
|
||||||
|
"nickname_taken": "nickname_taken",
|
||||||
|
"category_slug_required": "category_slug_required",
|
||||||
|
"category_not_found": "category_not_found",
|
||||||
|
"round_start_invalid_phase": "round_start_invalid_phase",
|
||||||
|
"round_already_configured": "round_already_configured"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user