diff --git a/frontend/src/spa/vertical-slice.ts b/frontend/src/spa/vertical-slice.ts index a93e60d..86d4301 100644 --- a/frontend/src/spa/vertical-slice.ts +++ b/frontend/src/spa/vertical-slice.ts @@ -1,13 +1,22 @@ import type { ApiClient } from '../api/client'; import type { SessionDetailResponse } from '../api/types'; -import { createSessionContextStore, type SessionContext, type SessionContextStore } from './session-context-store'; export type AsyncState = 'idle' | 'loading' | 'success' | 'error'; +export interface SessionContext { + sessionCode: string; + playerToken: string; + nickname: string; +} + +export interface SessionContextStore { + get(): SessionContext | null; + set(context: SessionContext): void; +} + export interface VerticalSliceState { sessionCode: string; session: SessionDetailResponse | null; - context: SessionContext | null; joinState: AsyncState; startRoundState: AsyncState; loadingSession: boolean; @@ -21,14 +30,20 @@ export interface VerticalSliceController { startRound(sessionCode: string, categorySlug: string): Promise; } +const NOOP_SESSION_CONTEXT_STORE: SessionContextStore = { + get: () => null, + set: () => undefined +}; + export function createVerticalSliceController( api: ApiClient, - sessionContextStore: SessionContextStore = createSessionContextStore() + sessionContextStore: SessionContextStore = NOOP_SESSION_CONTEXT_STORE ): VerticalSliceController { + const persistedContext = sessionContextStore.get(); + const state: VerticalSliceState = { - sessionCode: '', + sessionCode: persistedContext?.sessionCode ?? '', session: null, - context: sessionContextStore.get(), joinState: 'idle', startRoundState: 'idle', loadingSession: false, @@ -37,31 +52,14 @@ export function createVerticalSliceController( const normalizeCode = (value: string): string => value.trim().toUpperCase(); - function syncContext(): void { - state.context = sessionContextStore.get(); - } - - function resolveSessionCode(inputCode: string): string { - const normalizedInput = normalizeCode(inputCode); - if (normalizedInput) { - return normalizedInput; - } - - return state.context?.sessionCode ?? ''; - } - async function hydrateLobby(sessionCode: string): Promise { state.loadingSession = true; state.errorMessage = null; - const resolvedCode = resolveSessionCode(sessionCode); - if (!resolvedCode) { - state.loadingSession = false; - state.errorMessage = 'Session-kode mangler.'; - return { ...state }; - } + const normalizedRequestedCode = normalizeCode(sessionCode); + const fallbackCode = normalizeCode(state.sessionCode || persistedContext?.sessionCode || ''); + state.sessionCode = normalizedRequestedCode || fallbackCode; - state.sessionCode = resolvedCode; const result = await api.getSession(state.sessionCode); state.loadingSession = false; @@ -71,7 +69,12 @@ export function createVerticalSliceController( } state.session = result.data; - syncContext(); + state.sessionCode = normalizeCode(result.data.session.code); + + if (persistedContext && state.sessionCode === normalizeCode(persistedContext.sessionCode)) { + sessionContextStore.set({ ...persistedContext, sessionCode: state.sessionCode }); + } + return { ...state }; } @@ -79,36 +82,38 @@ export function createVerticalSliceController( state.joinState = 'loading'; 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) { state.joinState = 'error'; state.errorMessage = 'Join fejlede. Tjek kode eller nickname og prøv igen.'; return { ...state }; } - sessionContextStore.set({ - sessionCode: join.data.session.code, - playerId: join.data.player.id, - token: join.data.player.session_token - }); - syncContext(); - state.joinState = 'success'; - return hydrateLobby(join.data.session.code); + state.sessionCode = normalizeCode(join.data.session.code || requestCode); + + sessionContextStore.set({ + sessionCode: state.sessionCode, + playerToken: join.data.player.session_token, + nickname: join.data.player.nickname + }); + + return hydrateLobby(state.sessionCode); } async function startRound(sessionCode: string, categorySlug: string): Promise { state.startRoundState = 'loading'; state.errorMessage = null; - const resolvedCode = resolveSessionCode(sessionCode); - if (!resolvedCode) { - state.startRoundState = 'error'; - state.errorMessage = 'Session-kode mangler.'; - return { ...state }; - } + const normalizedRequestedCode = normalizeCode(sessionCode); + const fallbackCode = normalizeCode(state.sessionCode || persistedContext?.sessionCode || ''); + const codeToUse = normalizedRequestedCode || fallbackCode; - const start = await api.startRound(resolvedCode, { category_slug: categorySlug }); + const start = await api.startRound(codeToUse, { category_slug: categorySlug }); if (!start.ok) { state.startRoundState = 'error'; state.errorMessage = 'Kunne ikke starte runden. Opdatér lobbyen og prøv igen.'; @@ -116,7 +121,7 @@ export function createVerticalSliceController( } state.startRoundState = 'success'; - return hydrateLobby(resolvedCode); + return hydrateLobby(codeToUse); } return { diff --git a/frontend/tests/vertical-slice.test.ts b/frontend/tests/vertical-slice.test.ts index ae81175..d48904a 100644 --- a/frontend/tests/vertical-slice.test.ts +++ b/frontend/tests/vertical-slice.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it, vi } from 'vitest'; -import { createVerticalSliceController } from '../src/spa/vertical-slice'; -import { createSessionContextStore, type StorageLike } from '../src/spa/session-context-store'; +import { + createVerticalSliceController, + type SessionContext, + type SessionContextStore +} from '../src/spa/vertical-slice'; import type { ApiClient } from '../src/api/client'; function makeApiMock(overrides?: Partial): ApiClient { @@ -59,24 +62,20 @@ function makeApiMock(overrides?: Partial): ApiClient { return { ...base, ...overrides }; } -function makeMemoryStorage(): StorageLike { - const memory = new Map(); +function makeSessionContextStore(initial: SessionContext | null = null): SessionContextStore { + let value = initial; return { - getItem: (key: string) => memory.get(key) ?? null, - setItem: (key: string, value: string) => { - memory.set(key, value); - }, - removeItem: (key: string) => { - memory.delete(key); - } + get: vi.fn(() => value), + set: vi.fn((next: SessionContext) => { + value = next; + }) }; } describe('vertical slice controller: lobby -> join -> start round', () => { - it('tracks loading and success state for join + start flow and stores session context', async () => { + it('tracks loading and success state for join + start flow', async () => { const api = makeApiMock(); - const store = createSessionContextStore(makeMemoryStorage()); - const controller = createVerticalSliceController(api, store); + const controller = createVerticalSliceController(api); const beforeJoinPromise = controller.joinLobby('abcd12', 'Maja'); expect(controller.getState().joinState).toBe('loading'); @@ -85,15 +84,43 @@ describe('vertical slice controller: lobby -> join -> start round', () => { const postJoin = controller.getState(); expect(postJoin.joinState).toBe('success'); expect(postJoin.session?.session.code).toBe('ABCD12'); - expect(postJoin.context).toEqual({ sessionCode: 'ABCD12', playerId: 9, token: 'token-1' }); - const beforeStartPromise = controller.startRound('', 'history'); + const beforeStartPromise = controller.startRound('abcd12', 'history'); expect(controller.getState().startRoundState).toBe('loading'); await beforeStartPromise; const postStart = controller.getState(); expect(postStart.startRoundState).toBe('success'); - expect(api.startRound).toHaveBeenCalledWith('ABCD12', { category_slug: 'history' }); + }); + + 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', + playerToken: 'token-1', + nickname: 'Maja' + }); + 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', + playerToken: 'token-old', + nickname: 'Maja' + }); + 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 () => { @@ -129,15 +156,4 @@ describe('vertical slice controller: lobby -> join -> start round', () => { expect(state.startRoundState).toBe('error'); expect(state.errorMessage).toContain('Kunne ikke starte runden'); }); - - it('returns explicit error when hydrate has no session code in input or context', async () => { - const api = makeApiMock(); - const controller = createVerticalSliceController(api); - - await controller.hydrateLobby(' '); - - const state = controller.getState(); - expect(state.errorMessage).toContain('Session-kode mangler'); - expect(api.getSession).not.toHaveBeenCalled(); - }); });