Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| acc3420a86 | |||
| 2f6a21de9c | |||
| 9e54aa0ab2 | |||
| 58f7f02af3 | |||
| c9c2ec23a2 | |||
| 749997a8fb | |||
| 85e970b90c | |||
| b52896d137 | |||
| 538368de99 | |||
| cab5c47759 | |||
| 68325944c1 | |||
| d1e1ef0fde | |||
| 07a8c9568d | |||
| 4a6acd79c1 | |||
| b647db2048 | |||
| 29ef754389 | |||
| 702ab6b9ee | |||
| 7294ad409c | |||
| 2f142aeb24 | |||
| 84438b2880 | |||
| ea82f920b1 | |||
| 5bdbdbd837 | |||
| 7180cc9b0d |
@@ -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,30 @@
|
|||||||
|
import { Routes } from '@angular/router';
|
||||||
|
|
||||||
|
export const routes: Routes = [
|
||||||
|
{
|
||||||
|
path: 'host',
|
||||||
|
loadComponent: () => import('./features/host/host-shell.component').then((m) => m.HostShellComponent),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'host/:phase',
|
||||||
|
loadComponent: () => import('./features/host/host-shell.component').then((m) => m.HostShellComponent),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'host/:phase/:context',
|
||||||
|
loadComponent: () => import('./features/host/host-shell.component').then((m) => m.HostShellComponent),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'player',
|
||||||
|
loadComponent: () => import('./features/player/player-shell.component').then((m) => m.PlayerShellComponent),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'player/:phase',
|
||||||
|
loadComponent: () => import('./features/player/player-shell.component').then((m) => m.PlayerShellComponent),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'player/:phase/:context',
|
||||||
|
loadComponent: () => import('./features/player/player-shell.component').then((m) => m.PlayerShellComponent),
|
||||||
|
},
|
||||||
|
{ path: '', pathMatch: 'full', redirectTo: 'player' },
|
||||||
|
{ path: '**', redirectTo: 'player' },
|
||||||
|
];
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('HostShellComponent gameplay wiring', () => {
|
||||||
|
afterEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('runs startRound transition and refreshes session details', async () => {
|
||||||
|
const fetchMock: FetchMock = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(jsonResponse(201, { ok: true }))
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
jsonResponse(200, {
|
||||||
|
session: { code: 'ABCD12', status: 'lie', current_round: 2 },
|
||||||
|
round_question: { id: 41, prompt: 'Q?', answers: [] },
|
||||||
|
players: [],
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component } from '@angular/core';
|
||||||
|
import { FormsModule } from '@angular/forms';
|
||||||
|
|
||||||
|
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 }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
@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 *ngIf="scoreboardError" (click)="loadScoreboard()" [disabled]="loading">Retry scoreboard</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p *ngIf="error" class="error">{{ error }}</p>
|
||||||
|
<p *ngIf="scoreboardError" class="error">{{ scoreboardError }}</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>
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class HostShellComponent {
|
||||||
|
sessionCode = '';
|
||||||
|
categorySlug = 'general';
|
||||||
|
roundQuestionId = '';
|
||||||
|
loading = false;
|
||||||
|
error = '';
|
||||||
|
scoreboardError = '';
|
||||||
|
scoreboardPayload = '';
|
||||||
|
session: SessionDetail | null = null;
|
||||||
|
|
||||||
|
private normalizeCode(value: string): string {
|
||||||
|
return value.trim().toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
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 = '';
|
||||||
|
try {
|
||||||
|
const code = this.normalizeCode(this.sessionCode);
|
||||||
|
this.session = await this.request<SessionDetail>(`/lobby/sessions/${encodeURIComponent(code)}`, 'GET');
|
||||||
|
this.sessionCode = this.session.session.code;
|
||||||
|
this.roundQuestionId = this.session.round_question?.id ? String(this.session.round_question.id) : '';
|
||||||
|
} catch (error) {
|
||||||
|
this.error = `Session refresh failed: ${(error as Error).message}`;
|
||||||
|
} finally {
|
||||||
|
this.loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async startRound(): Promise<void> {
|
||||||
|
await this.runAction(async () => {
|
||||||
|
const code = this.normalizeCode(this.sessionCode);
|
||||||
|
await this.request(`/lobby/sessions/${encodeURIComponent(code)}/rounds/start`, 'POST', {
|
||||||
|
category_slug: this.categorySlug.trim(),
|
||||||
|
});
|
||||||
|
await this.refreshSession();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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,78 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('PlayerShellComponent gameplay wiring', () => {
|
||||||
|
afterEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears selected guess when refreshed status is no longer guess', async () => {
|
||||||
|
const fetchMock: FetchMock = vi.fn().mockResolvedValue(
|
||||||
|
jsonResponse(200, {
|
||||||
|
session: { code: 'ABCD12', status: 'reveal', current_round: 1 },
|
||||||
|
round_question: { id: 11, prompt: 'Q?', answers: [{ text: '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(200, { ok: true }))
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
jsonResponse(200, {
|
||||||
|
session: { code: 'ABCD12', status: 'guess', current_round: 1 },
|
||||||
|
round_question: { id: 11, prompt: 'Q?', answers: [{ text: 'A' }, { text: '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: [] },
|
||||||
|
};
|
||||||
|
|
||||||
|
await component.submitLie();
|
||||||
|
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Component } from '@angular/core';
|
||||||
|
import { FormsModule } from '@angular/forms';
|
||||||
|
|
||||||
|
interface SessionDetail {
|
||||||
|
session: { code: string; status: string; current_round: number };
|
||||||
|
round_question: { id: number; prompt: string; answers: Array<{ text: string }> } | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@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>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<p *ngIf="error" class="error">{{ error }}</p>
|
||||||
|
<p *ngIf="submitError" class="error">{{ submitError.message }}</p>
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class PlayerShellComponent {
|
||||||
|
sessionCode = '';
|
||||||
|
nickname = '';
|
||||||
|
playerId = 0;
|
||||||
|
sessionToken = '';
|
||||||
|
lieText = '';
|
||||||
|
selectedGuess = '';
|
||||||
|
loading = false;
|
||||||
|
error = '';
|
||||||
|
submitError: { kind: 'lie' | 'guess'; message: string } | null = null;
|
||||||
|
session: SessionDetail | null = null;
|
||||||
|
|
||||||
|
private normalizeCode(value: string): string {
|
||||||
|
return value.trim().toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
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 = '';
|
||||||
|
try {
|
||||||
|
const code = this.normalizeCode(this.sessionCode);
|
||||||
|
this.session = await this.request<SessionDetail>(`/lobby/sessions/${encodeURIComponent(code)}`, 'GET');
|
||||||
|
this.sessionCode = this.session.session.code;
|
||||||
|
if (this.session.session.status !== 'guess') {
|
||||||
|
this.selectedGuess = '';
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
this.error = `Session refresh failed: ${(error as Error).message}`;
|
||||||
|
} finally {
|
||||||
|
this.loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async joinSession(): Promise<void> {
|
||||||
|
this.loading = true;
|
||||||
|
this.error = '';
|
||||||
|
try {
|
||||||
|
const payload = await this.request<{
|
||||||
|
player: { id: number; session_token: string };
|
||||||
|
session: { code: string };
|
||||||
|
}>('/lobby/sessions/join', 'POST', {
|
||||||
|
code: this.normalizeCode(this.sessionCode),
|
||||||
|
nickname: this.nickname.trim(),
|
||||||
|
});
|
||||||
|
this.playerId = payload.player.id;
|
||||||
|
this.sessionToken = payload.player.session_token;
|
||||||
|
this.sessionCode = payload.session.code;
|
||||||
|
await this.refreshSession();
|
||||||
|
} catch (error) {
|
||||||
|
this.error = `Join failed: ${(error as Error).message}`;
|
||||||
|
} finally {
|
||||||
|
this.loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async submitLie(): Promise<void> {
|
||||||
|
if (!this.session?.round_question?.id) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.loading = true;
|
||||||
|
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();
|
||||||
|
} catch (error) {
|
||||||
|
this.submitError = { kind: 'lie', message: `Lie submit failed: ${(error as Error).message}` };
|
||||||
|
} finally {
|
||||||
|
this.loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async submitGuess(): Promise<void> {
|
||||||
|
if (!this.session?.round_question?.id || !this.selectedGuess) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.loading = true;
|
||||||
|
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();
|
||||||
|
} catch (error) {
|
||||||
|
this.submitError = { kind: 'guess', message: `Guess submit failed: ${(error as Error).message}` };
|
||||||
|
} finally {
|
||||||
|
this.loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,13 @@
|
|||||||
import type { ApiFailure, ApiResult, HealthResponse, SessionDetailResponse } from './types';
|
import type {
|
||||||
|
ApiFailure,
|
||||||
|
ApiResult,
|
||||||
|
HealthResponse,
|
||||||
|
JoinSessionRequest,
|
||||||
|
JoinSessionResponse,
|
||||||
|
SessionDetailResponse,
|
||||||
|
StartRoundRequest,
|
||||||
|
StartRoundResponse
|
||||||
|
} from './types';
|
||||||
|
|
||||||
export interface AngularHttpError {
|
export interface AngularHttpError {
|
||||||
status?: number;
|
status?: number;
|
||||||
@@ -8,11 +17,14 @@ 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>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function toFailure(error: unknown): ApiFailure {
|
function toFailure(error: unknown): ApiFailure {
|
||||||
@@ -40,23 +52,54 @@ 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<T>): Promise<ApiResult<T>> {
|
||||||
try {
|
try {
|
||||||
const data = await call();
|
const data = await call();
|
||||||
return { ok: true, status: 200, data };
|
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)
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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 })),
|
||||||
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
|
||||||
})
|
})
|
||||||
|
),
|
||||||
|
joinSession: (payload: JoinSessionRequest) =>
|
||||||
|
wrap(() =>
|
||||||
|
http.post<JoinSessionResponse>(
|
||||||
|
buildUrl(baseUrl, '/lobby/sessions/join'),
|
||||||
|
{
|
||||||
|
code: normalizeCode(payload.code),
|
||||||
|
nickname: payload.nickname.trim()
|
||||||
|
},
|
||||||
|
{ withCredentials: true }
|
||||||
|
)
|
||||||
|
),
|
||||||
|
startRound: (code: string, payload: StartRoundRequest) =>
|
||||||
|
wrap(() =>
|
||||||
|
http.post<StartRoundResponse>(
|
||||||
|
buildUrl(baseUrl, `/lobby/sessions/${encodeURIComponent(normalizeCode(code))}/rounds/start`),
|
||||||
|
payload,
|
||||||
|
{ withCredentials: true }
|
||||||
|
)
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,8 +1,16 @@
|
|||||||
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';
|
||||||
|
|
||||||
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;
|
||||||
@@ -19,9 +27,14 @@ 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,
|
||||||
joinState: 'idle',
|
joinState: 'idle',
|
||||||
startRoundState: 'idle',
|
startRoundState: 'idle',
|
||||||
@@ -34,7 +47,16 @@ 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 = 'Session-kode mangler.';
|
||||||
|
return { ...state };
|
||||||
|
}
|
||||||
|
|
||||||
const result = await api.getSession(state.sessionCode);
|
const result = await api.getSession(state.sessionCode);
|
||||||
state.loadingSession = false;
|
state.loadingSession = false;
|
||||||
@@ -45,6 +67,12 @@ export function createVerticalSliceController(api: ApiClient): VerticalSliceCont
|
|||||||
}
|
}
|
||||||
|
|
||||||
state.session = result.data;
|
state.session = 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,7 +80,11 @@ 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 = 'Join fejlede. Tjek kode eller nickname og prøv igen.';
|
||||||
@@ -60,14 +92,33 @@ export function createVerticalSliceController(api: ApiClient): VerticalSliceCont
|
|||||||
}
|
}
|
||||||
|
|
||||||
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 = 'Session-kode mangler.';
|
||||||
|
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 = 'Kunne ikke starte runden. Opdatér lobbyen og prøv igen.';
|
||||||
@@ -75,7 +126,7 @@ export function createVerticalSliceController(api: ApiClient): VerticalSliceCont
|
|||||||
}
|
}
|
||||||
|
|
||||||
state.startRoundState = 'success';
|
state.startRoundState = 'success';
|
||||||
return hydrateLobby(sessionCode);
|
return hydrateLobby(codeToUse);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -85,3 +136,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,135 @@ 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('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' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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,49 @@ 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,6 +125,36 @@ 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({
|
||||||
@@ -112,4 +188,39 @@ describe('vertical slice controller: lobby -> join -> start round', () => {
|
|||||||
expect(state.startRoundState).toBe('error');
|
expect(state.startRoundState).toBe('error');
|
||||||
expect(state.errorMessage).toContain('Kunne ikke starte runden');
|
expect(state.errorMessage).toContain('Kunne ikke starte runden');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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-kode mangler.');
|
||||||
|
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-kode mangler.');
|
||||||
|
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');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+9
-3
@@ -7,12 +7,13 @@ from fupogfakta.models import Category
|
|||||||
from .feature_flags import use_spa_ui
|
from .feature_flags import use_spa_ui
|
||||||
|
|
||||||
|
|
||||||
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,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -21,7 +22,12 @@ 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})
|
||||||
@@ -29,6 +35,6 @@ def host_screen(request, spa_path=None):
|
|||||||
|
|
||||||
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")
|
||||||
|
|||||||
@@ -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.
|
||||||
|
|||||||
Reference in New Issue
Block a user