Merge pull request '[READY][i18n][P18] Angular host+player i18n binding med simpel telefon-UX og nul client-audio' (#211) from dev/issue-206-angular-i18n-phone-ux-no-audio into main
All checks were successful
CI / test-and-quality (push) Successful in 2m29s

This commit was merged in pull request #211.
This commit is contained in:
2026-03-01 20:38:36 +01:00
8 changed files with 477 additions and 66 deletions

View File

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

View File

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

View File

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

View File

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

View File

@@ -5,6 +5,7 @@ import { FormsModule } from '@angular/forms';
import { createApiClient } from '../../../../../src/api/client'; import { createApiClient } from '../../../../../src/api/client';
import { createSessionContextStore } from '../../../../../src/spa/session-context-store'; import { createSessionContextStore } from '../../../../../src/spa/session-context-store';
import { createVerticalSliceController } from '../../../../../src/spa/vertical-slice'; import { createVerticalSliceController } from '../../../../../src/spa/vertical-slice';
import { clientHasNoAudioOutput, resolvePreferredLocale, subscribeToLocaleChanges, t } from '../../lobby-i18n';
interface SessionDetail { interface SessionDetail {
session: { code: string; status: string; current_round: number }; session: { code: string; status: string; current_round: number };
@@ -27,35 +28,35 @@ function resolveLocalStorage(): Storage | undefined {
standalone: true, standalone: true,
imports: [CommonModule, FormsModule], imports: [CommonModule, FormsModule],
template: ` template: `
<h2>Player SPA gameplay flow</h2> <h2>{{ copy('player.title') }}</h2>
<div class="panel"> <div class="panel" [attr.data-client-has-no-audio-output]="clientHasNoAudioOutput">
<label>Session code <input [(ngModel)]="sessionCode" /></label> <label>{{ copy('common.session_code') }} <input [(ngModel)]="sessionCode" /></label>
<label>Nickname <input [(ngModel)]="nickname" /></label> <label>{{ copy('player.nickname') }} <input [(ngModel)]="nickname" /></label>
<button (click)="refreshSession()" [disabled]="loading">Refresh</button> <button (click)="refreshSession()" [disabled]="loading">{{ copy('common.refresh') }}</button>
<button (click)="joinSession()" [disabled]="loading">Join</button> <button (click)="joinSession()" [disabled]="loading">{{ copy('player.join') }}</button>
</div> </div>
<p *ngIf="connectionState === 'reconnecting'" class="error"> <p *ngIf="connectionState === 'reconnecting'" class="error">
Reconnecting… trying to refresh session state. {{ copy('player.reconnecting_text') }}
<button type="button" (click)="retryReconnect()" [disabled]="loading">Retry now</button> <button type="button" (click)="retryReconnect()" [disabled]="loading">{{ copy('player.retry_now') }}</button>
<button type="button" (click)="returnToJoin()" [disabled]="loading">Back to join</button> <button type="button" (click)="returnToJoin()" [disabled]="loading">{{ copy('common.back_to_join') }}</button>
</p> </p>
<p *ngIf="connectionState === 'offline'" class="error"> <p *ngIf="connectionState === 'offline'" class="error">
You are offline. Reconnect to continue gameplay. {{ copy('player.offline_text') }}
<button type="button" (click)="retryReconnect()" [disabled]="loading">Retry now</button> <button type="button" (click)="retryReconnect()" [disabled]="loading">{{ copy('player.retry_now') }}</button>
<button type="button" (click)="returnToJoin()" [disabled]="loading">Back to join</button> <button type="button" (click)="returnToJoin()" [disabled]="loading">{{ copy('common.back_to_join') }}</button>
</p> </p>
<p *ngIf="loading" class="hint">{{ loadingMessage }}</p> <p *ngIf="loading" class="hint">{{ loadingMessage }}</p>
<div class="panel" *ngIf="session"> <div class="panel" *ngIf="session">
<p><strong>Status:</strong> {{ session.session.status }}</p> <p><strong>{{ copy('common.status') }}:</strong> {{ session.session.status }}</p>
<p *ngIf="session.round_question"><strong>Prompt:</strong> {{ session.round_question.prompt }}</p> <p *ngIf="session.round_question"><strong>{{ copy('common.prompt') }}:</strong> {{ session.round_question.prompt }}</p>
<label>Løgn <input [(ngModel)]="lieText" [disabled]="loading || session.session.status !== 'lie'" /></label> <label>{{ copy('player.lie_label') }} <input [(ngModel)]="lieText" [disabled]="loading || session.session.status !== 'lie'" /></label>
<button (click)="submitLie()" [disabled]="loading || session.session.status !== 'lie'">Submit lie</button> <button (click)="submitLie()" [disabled]="loading || session.session.status !== 'lie'">{{ copy('player.submit_lie') }}</button>
<button *ngIf="submitError?.kind === 'lie'" (click)="submitLie()" [disabled]="loading">Retry lie submit</button> <button *ngIf="submitError?.kind === 'lie'" (click)="submitLie()" [disabled]="loading">{{ copy('player.retry_lie_submit') }}</button>
<div class="answers" *ngIf="session.round_question?.answers?.length"> <div class="answers" *ngIf="session.round_question?.answers?.length">
<button <button
@@ -69,11 +70,11 @@ function resolveLocalStorage(): Storage | undefined {
</button> </button>
</div> </div>
<button (click)="submitGuess()" [disabled]="loading || session.session.status !== 'guess' || !selectedGuess">Submit guess</button> <button (click)="submitGuess()" [disabled]="loading || session.session.status !== 'guess' || !selectedGuess">{{ copy('player.submit_guess') }}</button>
<button *ngIf="submitError?.kind === 'guess'" (click)="submitGuess()" [disabled]="loading">Retry guess submit</button> <button *ngIf="submitError?.kind === 'guess'" (click)="submitGuess()" [disabled]="loading">{{ copy('player.retry_guess_submit') }}</button>
<div *ngIf="session.session.status === 'finished' && finalLeaderboard.length"> <div *ngIf="session.session.status === 'finished' && finalLeaderboard.length">
<h3>Final leaderboard</h3> <h3>{{ copy('player.final_leaderboard') }}</h3>
<ol> <ol>
<li *ngFor="let entry of finalLeaderboard">{{ entry.nickname }}: {{ entry.score }}</li> <li *ngFor="let entry of finalLeaderboard">{{ entry.nickname }}: {{ entry.score }}</li>
</ol> </ol>
@@ -84,12 +85,15 @@ function resolveLocalStorage(): Storage | undefined {
<p *ngIf="submitError" class="error">{{ submitError.message }}</p> <p *ngIf="submitError" class="error">{{ submitError.message }}</p>
<div class="panel" *ngIf="error || submitError"> <div class="panel" *ngIf="error || submitError">
<button type="button" (click)="retryReconnect()" [disabled]="loading">Retry</button> <button type="button" (click)="retryReconnect()" [disabled]="loading">{{ copy('common.retry') }}</button>
<button type="button" (click)="returnToJoin()" [disabled]="loading">Back to join</button> <button type="button" (click)="returnToJoin()" [disabled]="loading">{{ copy('common.back_to_join') }}</button>
</div> </div>
`, `,
}) })
export class PlayerShellComponent implements OnInit, OnDestroy { export class PlayerShellComponent implements OnInit, OnDestroy {
locale = resolvePreferredLocale();
readonly clientHasNoAudioOutput = clientHasNoAudioOutput;
sessionCode = ''; sessionCode = '';
nickname = ''; nickname = '';
playerId = 0; playerId = 0;
@@ -108,6 +112,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
private readonly controller = createVerticalSliceController(createApiClient(), this.sessionContextStore); private readonly controller = createVerticalSliceController(createApiClient(), this.sessionContextStore);
private reconnectTimer: ReturnType<typeof setTimeout> | null = null; private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private stateSyncTimer: ReturnType<typeof setTimeout> | null = null; private stateSyncTimer: ReturnType<typeof setTimeout> | null = null;
private unsubscribeLocale: (() => void) | null = null;
constructor() { constructor() {
if (typeof navigator !== 'undefined' && !navigator.onLine) { if (typeof navigator !== 'undefined' && !navigator.onLine) {
@@ -121,6 +126,10 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
} }
ngOnInit(): void { ngOnInit(): void {
this.unsubscribeLocale = subscribeToLocaleChanges((locale) => {
this.locale = locale;
});
const hashRoute = window.location.hash.replace(/^#\/?/, ''); const hashRoute = window.location.hash.replace(/^#\/?/, '');
const match = hashRoute.match(/^player(?:\/[^/]+)?(?:\/([^/?#]+))?/i); const match = hashRoute.match(/^player(?:\/[^/]+)?(?:\/([^/?#]+))?/i);
const codeFromRoute = match?.[1] ?? ''; const codeFromRoute = match?.[1] ?? '';
@@ -147,6 +156,8 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
} }
this.clearReconnectTimer(); this.clearReconnectTimer();
this.clearStateSyncTimer(); this.clearStateSyncTimer();
this.unsubscribeLocale?.();
this.unsubscribeLocale = null;
} }
private readonly handleOnline = (): void => { private readonly handleOnline = (): void => {
@@ -198,17 +209,21 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
get loadingMessage(): string { get loadingMessage(): string {
switch (this.loadingTransition) { switch (this.loadingTransition) {
case 'join': case 'join':
return 'Joining session… restoring your player state.'; return this.copy('player.loading_join');
case 'submit-lie': case 'submit-lie':
return 'Submitting lie… waiting for guess phase.'; return this.copy('player.loading_submit_lie');
case 'submit-guess': case 'submit-guess':
return 'Submitting guess… waiting for reveal.'; return this.copy('player.loading_submit_guess');
case 'refresh': case 'refresh':
default: default:
return 'Loading latest session state…'; return this.copy('player.loading_refresh');
} }
} }
copy(key: string): string {
return t(key, this.locale);
}
private normalizeCode(value: string): string { private normalizeCode(value: string): string {
return value.trim().toUpperCase(); return value.trim().toUpperCase();
} }
@@ -352,7 +367,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
this.syncRouteFromSession(); this.syncRouteFromSession();
this.markOnline(); this.markOnline();
} catch (error) { } catch (error) {
this.error = `Session refresh failed: ${this.toMessage(error)}`; this.error = `${this.copy('player.session_refresh_failed')}: ${this.toMessage(error)}`;
this.markConnectionIssue(error); this.markConnectionIssue(error);
} finally { } finally {
this.loading = false; this.loading = false;
@@ -382,7 +397,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
this.syncRouteFromSession(); this.syncRouteFromSession();
this.markOnline(); this.markOnline();
} catch (error) { } catch (error) {
this.error = `Join failed: ${this.toMessage(error)}`; this.error = `${this.copy('player.join_failed')}: ${this.toMessage(error)}`;
this.markConnectionIssue(error); this.markConnectionIssue(error);
} finally { } finally {
this.loading = false; this.loading = false;
@@ -410,7 +425,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
await this.refreshSession(); await this.refreshSession();
this.markOnline(); this.markOnline();
} catch (error) { } catch (error) {
this.submitError = { kind: 'lie', message: `Lie submit failed: ${this.toMessage(error)}` }; this.submitError = { kind: 'lie', message: `${this.copy('player.lie_submit_failed')}: ${this.toMessage(error)}` };
this.markConnectionIssue(error); this.markConnectionIssue(error);
} finally { } finally {
this.loading = false; this.loading = false;
@@ -438,7 +453,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
await this.refreshSession(); await this.refreshSession();
this.markOnline(); this.markOnline();
} catch (error) { } catch (error) {
this.submitError = { kind: 'guess', message: `Guess submit failed: ${this.toMessage(error)}` }; this.submitError = { kind: 'guess', message: `${this.copy('player.guess_submit_failed')}: ${this.toMessage(error)}` };
this.markConnectionIssue(error); this.markConnectionIssue(error);
} finally { } finally {
this.loading = false; this.loading = false;

View File

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

View File

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

View File

@@ -1,7 +1,10 @@
{ {
"locales": { "locales": {
"default": "en", "default": "en",
"supported": ["en", "da"] "supported": [
"en",
"da"
]
}, },
"frontend": { "frontend": {
"errors": { "errors": {
@@ -37,6 +40,227 @@
"en": "Action failed. Refresh status and try again.", "en": "Action failed. Refresh status and try again.",
"da": "Handlingen fejlede. Opdater status og prøv igen." "da": "Handlingen fejlede. Opdater status og prøv igen."
} }
},
"ui": {
"common": {
"refresh": {
"en": "Refresh",
"da": "Opdatér"
},
"retry": {
"en": "Retry",
"da": "Prøv igen"
},
"back_to_join": {
"en": "Back to join",
"da": "Tilbage til join"
},
"session_code": {
"en": "Session code",
"da": "Sessionskode"
},
"status": {
"en": "Status",
"da": "Status"
},
"prompt": {
"en": "Prompt",
"da": "Spørgsmål"
},
"round_question_id": {
"en": "Round question id",
"da": "Rundespørgsmål-id"
},
"round": {
"en": "round",
"da": "runde"
}
},
"app": {
"title": {
"en": "WPP Angular Shell",
"da": "WPP Angular Shell"
},
"host_nav": {
"en": "Host",
"da": "Vært"
},
"player_nav": {
"en": "Player",
"da": "Spiller"
},
"language_label": {
"en": "Language",
"da": "Sprog"
}
},
"host": {
"title": {
"en": "Host gameplay flow",
"da": "Vært gameplay-flow"
},
"category": {
"en": "Category",
"da": "Kategori"
},
"start_round": {
"en": "Start round",
"da": "Start runde"
},
"show_question": {
"en": "Show question",
"da": "Vis spørgsmål"
},
"mix_answers": {
"en": "Mix answers → guess",
"da": "Bland svar → gæt"
},
"calculate_scores": {
"en": "Calculate scores → reveal",
"da": "Udregn score → afslør"
},
"load_scoreboard": {
"en": "Load scoreboard",
"da": "Hent scoreboard"
},
"start_next_round": {
"en": "Start next round",
"da": "Start næste runde"
},
"finish_game": {
"en": "Finish game",
"da": "Afslut spil"
},
"retry_scoreboard": {
"en": "Retry scoreboard",
"da": "Prøv scoreboard igen"
},
"retry_next_round": {
"en": "Retry next round",
"da": "Prøv næste runde igen"
},
"retry_finish": {
"en": "Retry finish game",
"da": "Prøv afslutning igen"
},
"session_refresh_failed": {
"en": "Session refresh failed",
"da": "Kunne ikke opdatere session"
},
"scoreboard_failed": {
"en": "Scoreboard failed",
"da": "Scoreboard fejlede"
},
"next_round_failed": {
"en": "Next round failed",
"da": "Næste runde fejlede"
},
"finish_game_failed": {
"en": "Finish game failed",
"da": "Afslutning fejlede"
},
"session_code_required": {
"en": "Session code is required",
"da": "Sessionskode er påkrævet"
},
"final_leaderboard": {
"en": "Final leaderboard",
"da": "Finale leaderboard"
},
"winner": {
"en": "Winner",
"da": "Vinder"
},
"audio_locale_hint": {
"en": "Host locale for audio references",
"da": "Værtens locale for lydreferencer"
}
},
"player": {
"title": {
"en": "Player gameplay flow",
"da": "Spiller gameplay-flow"
},
"nickname": {
"en": "Nickname",
"da": "Kaldenavn"
},
"join": {
"en": "Join",
"da": "Join"
},
"lie_label": {
"en": "Lie",
"da": "Løgn"
},
"submit_lie": {
"en": "Submit lie",
"da": "Send løgn"
},
"retry_lie_submit": {
"en": "Retry lie submit",
"da": "Prøv løgn igen"
},
"submit_guess": {
"en": "Submit guess",
"da": "Send gæt"
},
"retry_guess_submit": {
"en": "Retry guess submit",
"da": "Prøv gæt igen"
},
"final_leaderboard": {
"en": "Final leaderboard",
"da": "Finale leaderboard"
},
"reconnecting_text": {
"en": "Reconnecting… trying to refresh session state.",
"da": "Forbinder igen… prøver at opdatere session."
},
"offline_text": {
"en": "You are offline. Reconnect to continue gameplay.",
"da": "Du er offline. Forbind igen for at fortsætte."
},
"retry_now": {
"en": "Retry now",
"da": "Prøv nu"
},
"loading_refresh": {
"en": "Loading latest session state…",
"da": "Indlæser seneste session-status…"
},
"loading_join": {
"en": "Joining session… restoring your player state.",
"da": "Joiner session… gendanner spillerstatus."
},
"loading_submit_lie": {
"en": "Submitting lie… waiting for guess phase.",
"da": "Sender løgn… venter på gættefase."
},
"loading_submit_guess": {
"en": "Submitting guess… waiting for reveal.",
"da": "Sender gæt… venter på afsløring."
},
"session_refresh_failed": {
"en": "Session refresh failed",
"da": "Kunne ikke opdatere session"
},
"join_failed": {
"en": "Join failed",
"da": "Join fejlede"
},
"lie_submit_failed": {
"en": "Lie submit failed",
"da": "Løgn-fejl"
},
"guess_submit_failed": {
"en": "Guess submit failed",
"da": "Gætte-fejl"
}
}
},
"capabilities": {
"client_has_no_audio_output": true
} }
}, },
"backend": { "backend": {
@@ -90,4 +314,4 @@
} }
} }
} }
} }