feat(ui): single-URL game app-shell (in-memory screens/views) #35

Merged
developer merged 8 commits from feature/ui-app-shell into development 2026-05-23 20:18:09 +00:00
17 changed files with 453 additions and 262 deletions
Showing only changes of commit e31fb2c17a - Show all commits
+135 -67
View File
@@ -18,6 +18,22 @@ module is a pure compute boundary on every platform.
> realistic multi-turn projection, and the cross-platform acceptance > realistic multi-turn projection, and the cross-platform acceptance
> pass in [ROADMAP.md](ROADMAP.md). This file is retained as the staged > pass in [ROADMAP.md](ROADMAP.md). This file is retained as the staged
> record of how the MVP was built. > record of how the MVP was built.
>
> **Routing — superseded by the app-shell.** After the MVP, the
> URL-based routing the per-phase artifacts below describe was refactored
> into a single-URL **app-shell**: the game UI is one SvelteKit route at
> `/game/`, the screen and the in-game view are in-memory rune state
> (`lib/app-nav.svelte.ts`), the `routes/games/[id]/` subtree and the
> per-view `+page.svelte` wrappers were removed, the in-game layout
> became `lib/game/game-shell.svelte`, and the login / lobby /
> lobby-create screens moved under `lib/screens/`. Browser Back/Forward
> move between screens via shallow routing without changing the URL — a
> model that also suits the bundled standalone targets (Wails /
> Capacitor / gomobile) that have no URLs. The current navigation model
> is described in [docs/navigation.md](docs/navigation.md) and in the
> reframed `Information Architecture and Navigation` section and Phase 10
> decisions below; the per-phase `routes/games/[id]/…` artifact paths are
> left as the historical record of what each phase delivered at the time.
The existing Fyne client in `client/` is deprecated and is not modified The existing Fyne client in `client/` is deprecated and is not modified
or imported by the new code. The architectural overview is mirrored into or imported by the new code. The architectural overview is mirrored into
@@ -130,38 +146,55 @@ The intended v1 architecture is:
## Information Architecture and Navigation ## Information Architecture and Navigation
The client is a single-page application with **one active view at a The client is a single-page **app-shell** with **one active view at a
time**. Navigation is mobile-first: floating panels never overlap the time**. It is served at a single URL (`/game/`) that never changes:
map, the main area never splits into multiple visible panels on small the visible screen and view are in-memory state, not routes. Navigation
screens. Desktop and mobile share the same model; on desktop, the is mobile-first: floating panels never overlap the map, the main area
sidebar sits beside the active view, on mobile it lives behind a never splits into multiple visible panels on small screens. Desktop
bottom-tab bar. and mobile share the same model; on desktop, the sidebar sits beside
the active view, on mobile it lives behind a bottom-tab bar.
### View model ### Screen and view model
Two pieces of in-memory state (rune singletons in
`lib/app-nav.svelte.ts`) replace what URLs used to encode — `appScreen`
(the top-level screen plus the active game id) and `activeView` (the
in-game view plus its sub-parameters):
```text ```text
ActiveView ∈ { appScreen.screen ∈ {
/login, (anonymous only) login, (anonymous only)
/lobby, (auth required) lobby, (auth required)
/games/:id/map, (default in-game view) lobby-create, (auth required)
/games/:id/table/:entity, (entity ∈ game, (auth required; carries appScreen.gameId)
planets | ship-classes | }
ship-groups | fleets |
sciences | races) activeView.view ∈ { (meaningful only while screen === game)
/games/:id/report, map, (default in-game view)
/games/:id/battle/:battleId, table, (+ tableEntity ∈ planets | ship-classes |
/games/:id/mail, ship-groups | fleets | sciences | races)
/games/:id/designer/ship-class/:id?, report,
/games/:id/designer/science/:id?, battle, (+ battleId, turn)
mail,
designer-science, (+ scienceId; absent = new-science form)
} }
``` ```
The top-level screen is chosen by the single-route dispatcher
(`routes/+page.svelte`) from `session.status` + `appScreen.screen`;
the in-game shell (`lib/game/game-shell.svelte`) renders the active
view from `activeView`. Browser Back/Forward move between screens
(Back from a game → lobby) via SvelteKit shallow routing, without
changing the URL; in-game view switches do not create history entries.
Switching between views happens through the header dropdown (desktop) Switching between views happens through the header dropdown (desktop)
or hamburger menu (mobile). Double-tapping a row in a `table:` view or hamburger menu (mobile), driven by `activeView.select(...)`.
returns to `/map` with `focus=<objectId>`. Some views can push a Double-tapping a row in a table view returns to the map focused on the
transient map overlay with a back affordance (for example, ship-class object. Some views can push a transient map overlay with a back
designer pushes a range-preview overlay onto the map). The transient affordance (for example, ship-class designer pushes a range-preview
overlay clears when the user navigates to any other view. overlay onto the map). The transient overlay clears when the user
selects any other view. The implementation is documented in
[docs/navigation.md](docs/navigation.md).
### Layout per breakpoint ### Layout per breakpoint
@@ -257,12 +290,20 @@ turn current` action.
- The account menu (top-right on desktop, last hamburger entry on - The account menu (top-right on desktop, last hamburger entry on
mobile) holds Settings, Sessions, Theme, Language, Logout. mobile) holds Settings, Sessions, Theme, Language, Logout.
### Authenticated route transitions ### Authenticated screen transitions
- `/login``/lobby` after successful confirm-email-code. All transitions are in-memory screen/view changes; the URL stays
- `/lobby``/games/:id/map` when a game card is selected. `/game/` throughout.
- Any view → `/login` immediately on session revocation push event.
- Designer views can push a transient overlay onto `/map`; the back - login → lobby after successful confirm-email-code (`session.status`
settles to `authenticated`).
- lobby → game (view `map`) when a game card is selected
(`appScreen.go("game", { gameId })`).
- any screen → login immediately on session revocation push event
(`session.status` settles back to `anonymous`).
- the in-game header carries a "return to lobby" control
(`appScreen.go("lobby")`); browser Back from a game does the same.
- Designer views can push a transient overlay onto the map; the back
affordance returns to the originating designer. affordance returns to the originating designer.
Per-screen behaviour (validations, exact field names, error mappings) Per-screen behaviour (validations, exact field names, error mappings)
@@ -1062,37 +1103,58 @@ end-to-end before any data is wired.
Decisions taken with the project owner during implementation: Decisions taken with the project owner during implementation:
1. **Routing — file-system based, no extra dispatcher.** The 1. **Routing — single-URL app-shell, in-memory dispatch.** The game
"view router" called out in the original artifact list is UI is one SvelteKit route served at `/game/`; the address bar never
implemented as SvelteKit's file-system routes plus thin changes. The "view router" called out in the original artifact list
`+page.svelte` wrappers that mount the matching is the in-memory dispatch in `lib/game/game-shell.svelte` — an
`lib/active-view/<name>.svelte` stub. No separate dispatch `{#if}` ladder over `activeView.view` that mounts the matching
component lives in the codebase; each route file is a two-line `lib/active-view/<name>.svelte` stub. The top-level screen
wrapper. (login / lobby / lobby-create / game) is chosen by the single-route
2. **Optional designer ID segments.** Both designer URLs ship as dispatcher `routes/+page.svelte` from `session.status` +
`[[id]]` optional segments `appScreen.screen`. Both `appScreen` and `activeView` are rune
(`designer/ship-class/[[classId]]/`, singletons in `lib/app-nav.svelte.ts`; there are no per-screen or
`designer/science/[[scienceId]]/`) so Phase 18 / 21 can read per-view file routes (only the dev/test `/__debug/*` ones remain).
the param without a routing migration. Phase 10 stubs ignore Screen-level browser history (Back → lobby) is layered on top via
the param. SvelteKit shallow routing (`pushState`/`replaceState` + `page.state`)
3. **Battle URL — optional id.** `battle/[[battleId]]/` accepts so the URL stays `/game/`. This single-URL model is also the natural
both the list URL (`/battle`) and a specific battle URL fit for the deferred standalone wrappers (Wails desktop, Capacitor /
(`/battle/<id>`). Phase 27 keeps the optional segment and gomobile mobile in [ROADMAP.md](ROADMAP.md)), which load a single
switches behaviour based on presence. bundled `index.html` with no URLs or history. See
[docs/navigation.md](docs/navigation.md).
> This decision supersedes the original "file-system routes plus
> thin `+page.svelte` wrappers" plan. The app-shell transition was
> implemented after the MVP phases: the `routes/games/[id]/`
> subtree and the per-view route wrappers were removed, the layout
> became `lib/game/game-shell.svelte`, and the login / lobby /
> lobby-create screens moved under `lib/screens/`. The
> `lib/active-view/*` components are unchanged — only how they are
> mounted changed.
2. **In-game view sub-parameters — `activeView` state, not URL
segments.** What were optional URL segments are now optional fields
on `activeView` state: the science designer reads `scienceId`
(absent = new-science form), the battle view reads `battleId`
(empty = list) and `turn`, and the table view reads `tableEntity`.
Later phases set these through `activeView.select(view, params)`
instead of navigating a URL.
3. **Battle view — optional id.** The battle view accepts both the
list state (no `battleId`) and a specific battle (`battleId` set).
Phase 27 keeps the optional sub-param and switches behaviour based
on presence.
4. **Tablet sidebar — click toggle, not swipe.** The 7681024 px 4. **Tablet sidebar — click toggle, not swipe.** The 7681024 px
tablet sidebar slides in from a header-button click rather tablet sidebar slides in from a header-button click rather
than the IA section's swipe-from-right gesture. The structural than the IA section's swipe-from-right gesture. The structural
breakpoint switch satisfies Phase 10's acceptance criterion; breakpoint switch satisfies Phase 10's acceptance criterion;
Phase 35 polish lands the swipe gesture. Phase 35 polish lands the swipe gesture.
5. **Mobile tool overlay — `mobileTool` state, gated by URL.** 5. **Mobile tool overlay — `mobileTool` state, gated by active view.**
The mobile bottom-tabs Calc / Order navigate to `/map` and The mobile bottom-tabs Calc / Order select the map view and
set a layout-owned `mobileTool` rune. The layout's derived set a shell-owned `mobileTool` rune. The shell's derived
`effectiveTool` only honours the rune when the URL is `/map`, `effectiveTool` only honours the rune while `activeView.view ===
so navigating to any other view via the More drawer or the "map"`, so selecting any other view via the More drawer or the
header view-menu naturally drops the overlay. The desktop header view-menu naturally drops the overlay. The sidebar tool
sidebar separately accepts a `?sidebar=calc|inspector|order` state is pure in-memory rune state — there is no `?sidebar=` URL
URL param that seeds the initial tab on first mount, used by param (the app-shell carries no per-screen URL); the sidebar opens
later phases that want to land directly on a particular tool. on its `inspector` default and external events flip the tab.
6. **Sidebar tool filenames — `*-tab.svelte`.** Phase 12 / 13 / 30 6. **Sidebar tool filenames — `*-tab.svelte`.** Phase 12 / 13 / 30
each name their final implementation each name their final implementation
(`order-tab.svelte`, `inspector-tab.svelte`, (`order-tab.svelte`, `inspector-tab.svelte`,
@@ -1103,11 +1165,16 @@ Decisions taken with the project owner during implementation:
name is the static `race ?` string from i18n, mirroring the name is the static `race ?` string from i18n, mirroring the
spec's static `turn ?` placeholder. Phase 11 wires both from spec's static `turn ?` placeholder. Phase 11 wires both from
`user.games.report` data through `lib/header/turn-counter.svelte`. `user.games.report` data through `lib/header/turn-counter.svelte`.
8. **Auth gate inherited.** The root `+layout.svelte` already 8. **Auth gate — state-based in the dispatcher.** The single-route
redirects `anonymous → /login`; the in-game shell needs no dispatcher (`routes/+page.svelte`) renders the login screen for an
extra guard. Phase 10 verified this by booting the e2e shell `anonymous` session and the authenticated screens for an
spec via `__galaxyDebug.setDeviceSessionId` and observing the `authenticated` one; there is no `goto` redirect (the app-shell
post-`session.init` `authenticated` status. stays at `/game/`). The in-game shell needs no extra guard. Phase 10
verified the gate by booting the e2e shell spec via
`__galaxyDebug.setDeviceSessionId` and observing the
post-`session.init` `authenticated` status. (Originally the gate was
a `goto("/login")` redirect in the root layout; the app-shell
transition replaced it with state-based rendering.)
9. **More drawer mirrors the view-menu.** The mobile bottom-tabs 9. **More drawer mirrors the view-menu.** The mobile bottom-tabs
"More" drawer renders the same seven destinations as the "More" drawer renders the same seven destinations as the
header view-menu. The IA section's narrower More list (Mail, header view-menu. The IA section's narrower More list (Mail,
@@ -1136,9 +1203,11 @@ Artifacts (delivered):
`i18n.setLocale`; Logout calls `session.signOut("user")`) `i18n.setLocale`; Logout calls `session.signOut("user")`)
- `ui/frontend/src/lib/sidebar/{sidebar, tab-bar, calculator-tab, - `ui/frontend/src/lib/sidebar/{sidebar, tab-bar, calculator-tab,
inspector-tab, order-tab, bottom-tabs}.svelte` — three-tab inspector-tab, order-tab, bottom-tabs}.svelte` — three-tab
sidebar with `inspector` default and `?sidebar=` URL seed; sidebar with `inspector` default (the app-shell transition later
mobile-only bottom-tabs with `[Map, Calc, Order, More]` plus a dropped the original `?sidebar=` URL seed — there is no per-screen
More drawer duplicating the view-menu destinations URL to carry it); mobile-only bottom-tabs with
`[Map, Calc, Order, More]` plus a More drawer duplicating the
view-menu destinations
- `ui/frontend/src/lib/sidebar/types.ts` — shared `SidebarTab` - `ui/frontend/src/lib/sidebar/types.ts` — shared `SidebarTab`
and `MobileTool` types and `MobileTool` types
- `ui/frontend/src/lib/active-view/{map, table, report, battle, - `ui/frontend/src/lib/active-view/{map, table, report, battle,
@@ -1173,7 +1242,7 @@ Targeted tests (delivered):
view-menu navigation to every IA destination, account-menu view-menu navigation to every IA destination, account-menu
Logout / Language wiring); Logout / Language wiring);
- Vitest component tests for the sidebar (default tab, switching, - Vitest component tests for the sidebar (default tab, switching,
empty-state copy, `?sidebar=` URL seed, close button); empty-state copy, close button);
- Vitest component tests for every active-view stub (title, - Vitest component tests for every active-view stub (title,
`coming soon` copy, table-entity prop, battle-id prop); `coming soon` copy, table-entity prop, battle-id prop);
- Playwright e2e: visit every view stub via header dropdown and - Playwright e2e: visit every view stub via header dropdown and
@@ -1430,8 +1499,7 @@ Artifacts (delivered):
`tab-bar.svelte`, `bottom-tabs.svelte` — `historyMode` prop on `tab-bar.svelte`, `bottom-tabs.svelte` — `historyMode` prop on
the sidebar forwards to `hideOrder` on tab-bar / bottom-tabs; the sidebar forwards to `hideOrder` on tab-bar / bottom-tabs;
active-tab `order` is reset to `inspector` if the flag flips active-tab `order` is reset to `inspector` if the flag flips
on, and the `?sidebar=order` URL seed falls back to on while it is selected.
`inspector` while the flag is true.
- `ui/frontend/src/routes/games/[id]/+layout.svelte` — - `ui/frontend/src/routes/games/[id]/+layout.svelte` —
instantiates `OrderDraftStore`, sets context, runs instantiates `OrderDraftStore`, sets context, runs
`init({ cache, gameId })` next to `gameState.init` through `init({ cache, gameId })` next to `gameState.init` through
+13 -5
View File
@@ -53,9 +53,15 @@ quick orientation; deeper design notes live under `ui/docs/`.
+ SQLite on desktop, iOS Keychain / Android Keystore + SQLite on + SQLite on desktop, iOS Keychain / Android Keystore + SQLite on
mobile, all behind a single `KeyStore` and `Cache` TypeScript mobile, all behind a single `KeyStore` and `Cache` TypeScript
interface. interface.
- **Mobile-first navigation:** one active view occupies the main area - **Single-URL app-shell navigation:** the game UI is one route served
at a time; the sidebar holds a single tool (calculator, inspector, at `/game/`; the screen (login / lobby / game) and the in-game view
or order) with persistent state on switch. are in-memory state (`lib/app-nav.svelte.ts`), not URLs, so the
address bar never changes. Browser Back/Forward move between screens
via shallow routing without touching the URL — a model that also
suits the bundled standalone targets (Wails / Capacitor) that have no
URLs. One active view occupies the main area at a time; the sidebar
holds a single tool (calculator, inspector, or order) with persistent
state on switch. See [`docs/navigation.md`](docs/navigation.md).
## Repository layout ## Repository layout
@@ -81,16 +87,18 @@ ui/
├── mobile/ Capacitor project (planned — see ROADMAP.md) ├── mobile/ Capacitor project (planned — see ROADMAP.md)
└── frontend/ SvelteKit / Vite source └── frontend/ SvelteKit / Vite source
├── src/api/ GalaxyClient + typed Connect client + auth + session ├── src/api/ GalaxyClient + typed Connect client + auth + session
├── src/lib/ env config, session store, revocation watcher ├── src/lib/ app-shell nav + screens + game shell, env config, session store, stores
├── src/platform/core/ Core interface + WasmCore adapter ├── src/platform/core/ Core interface + WasmCore adapter
├── src/platform/store/ KeyStore/Cache interfaces + web adapter ├── src/platform/store/ KeyStore/Cache interfaces + web adapter
├── src/proto/ generated Protobuf-ES + Connect descriptors + FlatBuffers TS bindings ├── src/proto/ generated Protobuf-ES + Connect descriptors + FlatBuffers TS bindings
├── src/routes/ SvelteKit routes (/, /login, /lobby, /lobby/create) ├── src/routes/ single-URL app-shell: `/game/` dispatcher (+page.svelte) + `/__debug/*`
└── static/ core.wasm + wasm_exec.js (built by `make wasm` / CI; gitignored) └── static/ core.wasm + wasm_exec.js (built by `make wasm` / CI; gitignored)
``` ```
Linked topic docs: Linked topic docs:
- [`docs/navigation.md`](docs/navigation.md) — single-URL app-shell,
screens and views as in-memory state, screen history, sidebar tools.
- [`docs/auth-flow.md`](docs/auth-flow.md) — email-code login, - [`docs/auth-flow.md`](docs/auth-flow.md) — email-code login,
session store state machine, revocation watcher. session store state machine, revocation watcher.
- [`docs/lobby.md`](docs/lobby.md) — lobby UI sections, application - [`docs/lobby.md`](docs/lobby.md) — lobby UI sections, application
+29 -20
View File
@@ -18,10 +18,15 @@ authoritative in [`docs/FUNCTIONAL.md` §1](../../docs/FUNCTIONAL.md).
- `ui/frontend/src/lib/revocation-watcher.ts` — minimal - `ui/frontend/src/lib/revocation-watcher.ts` — minimal
`SubscribeEvents` watcher that triggers `signOut("revoked")` on `SubscribeEvents` watcher that triggers `signOut("revoked")` on
any non-aborted stream termination. any non-aborted stream termination.
- `ui/frontend/src/routes/login/+page.svelte` — two-step form. - `ui/frontend/src/lib/screens/login-screen.svelte` — two-step form.
- `ui/frontend/src/routes/lobby/+page.svelte` — placeholder lobby - `ui/frontend/src/lib/screens/lobby-screen.svelte` — lobby that
that issues the first authenticated `user.account.get`. issues the first authenticated `user.account.get`.
- `ui/frontend/src/routes/+layout.svelte`route guard plus the - `ui/frontend/src/routes/+page.svelte`the state-based auth gate /
screen dispatcher (anonymous → login, authenticated → the
`appScreen` screen). The single-URL app-shell has no per-screen
routes; see [`navigation.md`](navigation.md).
- `ui/frontend/src/routes/+layout.svelte` — boot-time session init,
the `loading` / `unsupported` interception, and the
browser-not-supported blocker. browser-not-supported blocker.
## State machine (`SessionStatus`) ## State machine (`SessionStatus`)
@@ -50,8 +55,9 @@ authoritative in [`docs/FUNCTIONAL.md` §1](../../docs/FUNCTIONAL.md).
``` ```
`signOut("revoked")` shares the same observable end state as `signOut("revoked")` shares the same observable end state as
`signOut("user")`; the reason exists only for telemetry. Both `signOut("user")`; the reason exists only for telemetry. Both settle
trigger the layout effect's `anonymous → /login` redirect. `status` to `anonymous`, which the dispatcher renders as the login
screen — there is no URL redirect (the app-shell stays at `/game/`).
## UX states and error mapping ## UX states and error mapping
@@ -67,7 +73,7 @@ those branches.
| 200 from `send-email-code` | advance to step `code`, focus the code input | | 200 from `send-email-code` | advance to step `code`, focus the code input |
| `invalid_request` from `send` | stay on step `email`, surface the gateway message | | `invalid_request` from `send` | stay on step `email`, surface the gateway message |
| `service_unavailable` from `send` | stay on step `email`, surface "service is temporarily unavailable" | | `service_unavailable` from `send` | stay on step `email`, surface "service is temporarily unavailable" |
| 200 from `confirm-email-code` | persist `device_session_id`, redirect to `/lobby` | | 200 from `confirm-email-code` | persist `device_session_id`, settle `status` to `authenticated` (dispatcher shows the lobby) |
| `invalid_request` from `confirm` | bounce to step `email`, message: "code expired or already used" | | `invalid_request` from `confirm` | bounce to step `email`, message: "code expired or already used" |
| any other error from `confirm` | stay on step `code`, surface the gateway message | | any other error from `confirm` | stay on step `code`, surface the gateway message |
@@ -89,8 +95,10 @@ After `confirm-email-code` succeeds, `session.signIn` writes the
`device_session_id` into the IDB cache (`namespace=session`, `device_session_id` into the IDB cache (`namespace=session`,
`key=device-session-id`). On the next page load, `key=device-session-id`). On the next page load,
`SessionStore.init` reads it back and settles `status` to `SessionStore.init` reads it back and settles `status` to
`authenticated`, so the layout effect routes the user straight to `authenticated`, so the dispatcher renders the authenticated screen
`/lobby`. straight away. Which authenticated screen it is comes from the
restored `appScreen` snapshot (lobby by default; see
[`navigation.md`](navigation.md)), not from the URL.
The keypair lives next to the id in the same database (object The keypair lives next to the id in the same database (object
store `keypair`, key `device`). Clearing site data wipes both; store `keypair`, key `device`). Clearing site data wipes both;
@@ -102,21 +110,22 @@ again. This is the documented re-login path — there is no paired
The keystore relies on WebCrypto Ed25519, which currently lands in The keystore relies on WebCrypto Ed25519, which currently lands in
Chrome ≥ 137, Firefox ≥ 130, Safari ≥ 17.4 (see Chrome ≥ 137, Firefox ≥ 130, Safari ≥ 17.4 (see
[`storage.md`](storage.md) for the rationale). On boot the layout [`storage.md`](storage.md) for the rationale). On boot the root
runs a sanity probe (`crypto.subtle.generateKey` for `Ed25519`); if layout runs a sanity probe (`crypto.subtle.generateKey` for
it rejects, the layout switches to a `browser not supported` page `Ed25519`); if it rejects, `status` settles to `unsupported` and the
instead of rendering `/login`. The client deliberately does not ship a layout renders a `browser not supported` page instead of the login
JavaScript Ed25519 fallback — the design decision is modern-browser screen. The client deliberately does not ship a JavaScript Ed25519
baseline only. fallback — the design decision is modern-browser baseline only.
## Revocation ## Revocation
The lobby layout opens a long-running `SubscribeEvents` stream as The root layout opens a long-running `SubscribeEvents` stream as
soon as `status` becomes `authenticated`. Its only contract is soon as `status` becomes `authenticated`. Its only contract is
liveness: any non-aborted termination of the stream is treated as liveness: any non-aborted termination of the stream is treated as
a server-side session revocation, the watcher calls a server-side session revocation, the watcher calls
`session.signOut("revoked")`, and the layout effect redirects to `session.signOut("revoked")`, `status` settles to `anonymous`, and
`/login`. the dispatcher swaps to the login screen on the next render — the
URL stays `/game/`.
Session revocation closes the active client within one second: the Session revocation closes the active client within one second: the
gateway closes the stream the moment it observes a gateway closes the stream the moment it observes a
@@ -126,8 +135,8 @@ reacts on the next event-loop tick.
## Localisation ## Localisation
The login form, the root layout's blocker page, and the lobby The login form, the root layout's blocker page, and the lobby
placeholder go through the i18n primitive in `src/lib/i18n/`. The screen go through the i18n primitive in `src/lib/i18n/`. The
language picker on `/login` lists every entry in language picker on the login screen lists every entry in
`SUPPORTED_LOCALES` by its native name and is initialised from `SUPPORTED_LOCALES` by its native name and is initialised from
`navigator.languages` (web) with `en` as the fallback. Picking a `navigator.languages` (web) with `en` as the fallback. Picking a
different language re-renders the form in place and is forwarded different language re-renders the form in place and is forwarded
+10 -7
View File
@@ -1,7 +1,9 @@
# Battle Viewer UX # Battle Viewer UX
The battle viewer is a dedicated view for battles The battle viewer is a dedicated active view for battles
(`/games/<id>/battle/<battleId>`). Bombings are a separate static (`activeView.view === "battle"`, with `battleId` and `turn`
sub-parameters; the app-shell has no per-view URL — see
[`navigation.md`](navigation.md)). Bombings are a separate static
table in the Reports view (`section-bombings.svelte`). The two table in the Reports view (`section-bombings.svelte`). The two
domains are deliberately not mixed in any visual surface or click domains are deliberately not mixed in any visual surface or click
target. target.
@@ -212,7 +214,8 @@ result is an X-shaped cross overlaid on the planet glyph.
The stroke width is computed by `battleMarkerStrokeWidth(shots)`: The stroke width is computed by `battleMarkerStrokeWidth(shots)`:
1 shot → 1 px, 100 shots → 5 px, linearly interpolated in between 1 shot → 1 px, 100 shots → 5 px, linearly interpolated in between
(`width = 1 + (shots 1) × 4 / 99`, clamped). A click on either (`width = 1 + (shots 1) × 4 / 99`, clamped). A click on either
line navigates to `/games/<id>/battle/<battleId>?turn=<turn>`. line opens the battle viewer in memory via
`activeView.select("battle", { battleId, turn })`.
### Bombing marker — colored ring ### Bombing marker — colored ring
@@ -223,10 +226,10 @@ Colour:
- yellow (`#FFD400`) when `wiped: false`, - yellow (`#FFD400`) when `wiped: false`,
- red (`#FF3030`) when `wiped: true`. - red (`#FF3030`) when `wiped: true`.
A click on the ring navigates to `/games/<id>/report#report-bombings` A click on the ring switches to the report view
and scrolls the matching `report-bombing-row` (by `data-planet`) (`activeView.select("report")`) and scrolls the matching
into view. Bombing markers never open the Battle Viewer — the two `report-bombing-row` (by `data-planet`) into view. Bombing markers
domains stay separate. never open the Battle Viewer — the two domains stay separate.
## Data source ## Data source
+8 -6
View File
@@ -1,9 +1,10 @@
# In-game diplomatic mail UI # In-game diplomatic mail UI
The in-game mail view consumes the `diplomail` subsystem in the The in-game mail view consumes the `diplomail` subsystem in the
backend. The route lives at `/games/:id/mail` and replaces the backend. It is the `mail` active view (`activeView.view === "mail"`)
active view when the user opens the "diplomatic mail" entry in the and replaces the active view when the user opens the "diplomatic mail"
header menu. entry in the header menu (`activeView.select("mail")`). The app-shell
has no per-view URL — see [`navigation.md`](navigation.md).
## Wire surface ## Wire surface
@@ -70,11 +71,12 @@ render the original directly with no toggle.
`diplomail.message.received` push frames are dispatched from `diplomail.message.received` push frames are dispatched from
`api/events.svelte.ts` via the singleton SubscribeEvents stream. The `api/events.svelte.ts` via the singleton SubscribeEvents stream. The
in-game layout (`routes/games/[id]/+layout.svelte`) parses the in-game shell (`lib/game/game-shell.svelte`) parses the
verified payload, calls `mailStore.applyPushEvent(gameId)` (which verified payload, calls `mailStore.applyPushEvent(gameId)` (which
re-fetches the inbox — the payload only carries a preview), and re-fetches the inbox — the payload only carries a preview), and
raises a toast through `lib/toast.svelte.ts` with a "view" raises a toast through `lib/toast.svelte.ts` whose "view" action
deep-link to `/games/:id/mail`. switches to the mail view in memory (`activeView.select("mail")`) —
no URL navigation.
The header view-menu's mail entry shows `mailStore.unreadCount` as The header view-menu's mail entry shows `mailStore.unreadCount` as
an inline pill — the only chrome the badge needs. an inline pill — the only chrome the badge needs.
+5 -5
View File
@@ -93,11 +93,11 @@ reconnect.
}); });
onDestroy(off); onDestroy(off);
``` ```
2. If the handler reads scoped data (per-game, per-route), register 2. If the handler reads scoped data (per-game), register from a
from a layout that owns that scope and pass the gameId via a component that owns that scope and pass the gameId via a closure.
closure. The handler should filter events whose payload does not The handler should filter events whose payload does not match its
match its scope (see `routes/games/[id]/+layout.svelte` for the scope (see `lib/game/game-shell.svelte` for the `game.turn.ready`
`game.turn.ready` filter). filter).
3. The payload encoding is owned by the producer side: the 3. The payload encoding is owned by the producer side: the
`game.turn.ready` event uses JSON `{game_id, turn}`. Document `game.turn.ready` event uses JSON `{game_id, turn}`. Document
the schema next to the producer (e.g. `backend/README.md` §10). the schema next to the producer (e.g. `backend/README.md` §10).
+32 -12
View File
@@ -6,13 +6,15 @@ inspector tabs, the order composer, and the calculator.
## Lifecycle ## Lifecycle
`routes/games/[id]/+layout.svelte` instantiates one `GameStateStore` The in-game shell (`lib/game/game-shell.svelte`) instantiates one
per game (the layout remounts when the user navigates to a different `GameStateStore` per game. The shell is mounted by the single-route
game id, so each game gets a fresh store). The layout exposes the dispatcher only while `appScreen.screen === "game"`, and remounts when
instance through Svelte context under `GAME_STATE_CONTEXT_KEY`; `appScreen.gameId` changes, so each game gets a fresh store. The shell
descendants read it via `getContext(GAME_STATE_CONTEXT_KEY)`. exposes the instance through Svelte context under
`GAME_STATE_CONTEXT_KEY`; descendants read it via
`getContext(GAME_STATE_CONTEXT_KEY)`.
The layout's `onMount` builds the `GalaxyClient`, loads `Cache` The shell's boot effect builds the `GalaxyClient`, loads `Cache`
through `loadStore()`, then calls `gameState.init({ client, cache, through `loadStore()`, then calls `gameState.init({ client, cache,
gameId })`. `init`: gameId })`. `init`:
@@ -21,9 +23,10 @@ gameId })`. `init`:
2. calls `setGame(gameId)`, which: 2. calls `setGame(gameId)`, which:
- reads the per-game wrap-mode preference from `Cache` - reads the per-game wrap-mode preference from `Cache`
(`game-prefs / <gameId>/wrap-mode`, default `torus`); (`game-prefs / <gameId>/wrap-mode`, default `torus`);
- calls `lobby.my.games.list` and finds the game record - calls `lobby.my.games.list` (`findGame`) and finds the game
(`GameSummary` carries `current_turn`); if the user is not a record (`GameSummary` carries `current_turn`); if the game is not
member, the store flips to `error`; in the player's list, the store sets the `notFound` flag (see
below);
- calls `user.games.report` for the discovered turn and decodes - calls `user.games.report` for the discovered turn and decodes
the FlatBuffers response into a TS-friendly `GameReport` shape. the FlatBuffers response into a TS-friendly `GameReport` shape.
@@ -40,6 +43,23 @@ The store exposes:
| `pendingTurn` | `number \| null` | latest server turn the user has not yet opened | | `pendingTurn` | `number \| null` | latest server turn the user has not yet opened |
| `wrapMode` | `torus / no-wrap` | per-game preference, persisted via `Cache` | | `wrapMode` | `torus / no-wrap` | per-game preference, persisted via `Cache` |
| `error` | `string \| null` | localised error message when `status === "error"` | | `error` | `string \| null` | localised error message when `status === "error"` |
| `notFound` | `boolean` | true when the game is not in the player's list (cancelled / removed / access revoked); the shell drops to the lobby |
## Missing or inaccessible game
A restored or stale game id (a `sessionStorage` snapshot pointing at a
game that was cancelled, removed, or whose access was revoked) is a
distinct case from a transient failure. When `findGame` returns no
matching record, `setGame` sets the boolean `notFound` flag rather
than synthesising an error message. After `init` resolves, the in-game
shell reads `gameState.notFound` and, when true, calls
`appScreen.go("lobby")` and shows a `game.events.unavailable` toast —
the player lands back in the lobby instead of on an in-game error
screen. A transient network failure takes the catch path instead,
leaving `notFound` false and flipping `status` to `error` so the
in-game error state offers a retry. `notFound` resets to false at the
start of every `setGame` / `advanceToPending`. See
[`navigation.md`](navigation.md) for the restore-and-validate flow.
## Store extensions ## Store extensions
@@ -48,7 +68,7 @@ wire lands (ships, fleets, sciences, routes, battles, mail).
`currentTurn` is split from `viewedTurn`, and `viewTurn(turn)` / `currentTurn` is split from `viewedTurn`, and `viewTurn(turn)` /
`returnToCurrent()` handle history navigation. The derived `returnToCurrent()` handle history navigation. The derived
`historyMode` rune flips automatically when `viewedTurn < `historyMode` rune flips automatically when `viewedTurn <
currentTurn`; the layout passes it to the sidebar / bottom-tabs currentTurn`; the shell passes it to the sidebar / bottom-tabs
wiring (which hides the order tab) and to wiring (which hides the order tab) and to
`OrderDraftStore.bindClient` (which gates `add` / `remove` / `move`). `OrderDraftStore.bindClient` (which gates `add` / `remove` / `move`).
See "History mode" below for the cache and refresh rules. See "History mode" below for the cache and refresh rules.
@@ -161,9 +181,9 @@ without losing the live snapshot. The store keeps two turn runes:
The derived `historyMode` rune (`status === "ready" && viewedTurn The derived `historyMode` rune (`status === "ready" && viewedTurn
< currentTurn`) drives every history-aware consumer: < currentTurn`) drives every history-aware consumer:
- the layout passes it to `Sidebar` / `BottomTabs` so the order - the shell passes it to `Sidebar` / `BottomTabs` so the order
tab vanishes; tab vanishes;
- the layout passes a `getHistoryMode` getter to - the shell passes a `getHistoryMode` getter to
`OrderDraftStore.bindClient` so `add` / `remove` / `move` are `OrderDraftStore.bindClient` so `add` / `remove` / `move` are
no-ops while the user is looking at a past turn; no-ops while the user is looking at a past turn;
- `RenderedReportSource` returns the raw report (no order overlay) - `RenderedReportSource` returns the raw report (no order overlay)
+1 -1
View File
@@ -85,7 +85,7 @@ helper is platform-agnostic by design.
The boot locale resolves once at module load (no async init): The boot locale resolves once at module load (no async init):
an explicit stored choice wins, otherwise browser/system detection, an explicit stored choice wins, otherwise browser/system detection,
otherwise `DEFAULT_LOCALE`. Callers that mutate the locale (the language otherwise `DEFAULT_LOCALE`. Callers that mutate the locale (the language
pickers on `/login` and in the account menu) call `i18n.setLocale(next)`, pickers on the login screen and in the account menu) call `i18n.setLocale(next)`,
which **persists** the choice to `localStorage` (key `galaxy-locale`) so which **persists** the choice to `localStorage` (key `galaxy-locale`) so
it survives reloads. An unrecognised stored value is ignored and falls it survives reloads. An unrecognised stored value is ignored and falls
back to detection. back to detection.
+6 -5
View File
@@ -15,8 +15,8 @@ width.
| Section | Empty state | Source | Action | | Section | Empty state | Source | Action |
| -------------------- | --------------------- | -------------------------- | --------------------------------------------------------- | | -------------------- | --------------------- | -------------------------- | --------------------------------------------------------- |
| `create new game` | (always visible) | — | Navigates to `/lobby/create` | | `create new game` | (always visible) | — | Opens the create screen (`appScreen.go("lobby-create")`) |
| `my games` | `no games yet` | `lobby.my.games.list` | Click → `/games/:id/map` | | `my games` | `no games yet` | `lobby.my.games.list` | Click → enters the game on the map view (`activeView.reset()` + `appScreen.go("game", { gameId })`) |
| `pending invitations`| `no invitations` | `lobby.my.invites.list` | Accept (`lobby.invite.redeem`) / Decline (`lobby.invite.decline`) | | `pending invitations`| `no invitations` | `lobby.my.invites.list` | Accept (`lobby.invite.redeem`) / Decline (`lobby.invite.decline`) |
| `my applications` | `no applications` | `lobby.my.applications.list` | Status badge (`pending` / `approved` / `rejected`) | | `my applications` | `no applications` | `lobby.my.applications.list` | Status badge (`pending` / `approved` / `rejected`) |
| `public games` | `no public games` | `lobby.public.games.list` | Submit application via inline race-name form (`lobby.application.submit`) | | `public games` | `no public games` | `lobby.public.games.list` | Submit application via inline race-name form (`lobby.application.submit`) |
@@ -85,9 +85,10 @@ public game (FUNCTIONAL.md §3.3). Fields:
| `start_gap_players` | Advanced toggle | `2` | | | `start_gap_players` | Advanced toggle | `2` | |
| `target_engine_version` | Advanced toggle | `v1` | Falls back to `v1` if blank | | `target_engine_version` | Advanced toggle | `v1` | Falls back to `v1` if blank |
On success the page navigates back to `/lobby` and the new game shows On success the create screen returns to the lobby
up in `my games` once the lobby's onMount has had a chance to refresh (`appScreen.go("lobby")`) and the new game shows up in `my games`
the list. once the lobby's onMount has had a chance to refresh the list (the
lobby screen remounts on return, so its onMount re-fires).
## Errors ## Errors
+158 -76
View File
@@ -1,46 +1,120 @@
# In-game shell — navigation model # In-game shell — navigation model
This doc covers the chrome that wraps every in-game view: the This doc covers the chrome that wraps every in-game view: the
responsive layout shell, the active-view router built on SvelteKit's single-URL app-shell that selects screens and views from in-memory
file-system routes, the sidebar with three tools and its state, the responsive layout shell, the sidebar with three tools and
state-preservation rule, and the mobile bottom-tabs. The user-facing its state-preservation rule, and the mobile bottom-tabs. The
spec — view list, breakpoint diagrams, history-mode plans — lives in user-facing spec — view list, breakpoint diagrams, history-mode plans
[`../PLAN.md`](../PLAN.md), section — lives in [`../PLAN.md`](../PLAN.md), section
`Information Architecture and Navigation`. This doc is the source of `Information Architecture and Navigation`. This doc is the source of
truth for how those rules are implemented. truth for how those rules are implemented.
## Active-view model ## App-shell: one URL, screens and views as state
The client renders **one active view at a time**. Every active view is The game UI is a **single SvelteKit route served at `/game/`**. There
a SvelteKit route under `routes/games/[id]/`; the route file is a are no per-screen or per-view routes — the address bar stays `/game/`
two-line wrapper that mounts the matching content component from for the whole session. The only other routes are the dev/test-only
`src/lib/active-view/<name>.svelte`. The "view router" mentioned in `/__debug/*` surfaces. What the URL used to encode now lives in two
the plan is the file system plus those wrappers — there is no rune singletons in `src/lib/app-nav.svelte.ts`:
separate dispatch component.
| URL | Active view component | - **`appScreen`** — the top-level screen
| ------------------------------------------ | ---------------------------------------------------------------------- | (`login` / `lobby` / `lobby-create` / `game`) plus the active
| `/games/:id/map` | `lib/active-view/map.svelte` | `gameId`. It replaces the old `goto`-based redirects and the `[id]`
| `/games/:id/table/:entity` | `lib/active-view/table.svelte` | route param.
| `/games/:id/report` | `lib/active-view/report.svelte` (see [report-view.md](report-view.md)) | - **`activeView`** — the in-game view (`map` / `table` / `report` /
| `/games/:id/battle/:battleId?` | `lib/active-view/battle.svelte` | `battle` / `mail` / `designer-science`) plus the sub-parameters the
| `/games/:id/mail` | `lib/active-view/mail.svelte` | old route segments carried (`tableEntity`, `battleId`, `turn`,
| `/games/:id/designer/science/:scienceId?` | `lib/active-view/designer-science.svelte` | `scienceId`). It replaces the URL params the route wrappers read.
`/games/:id` (no trailing view) redirects to `/games/:id/map`. The A single-route dispatcher (`src/routes/+page.svelte`) chooses what to
optional `:scienceId?` segment on the science designer route matches render: it gates on `session.status` (anonymous → login, authenticated
SvelteKit's `[[scienceId]]` syntax — `/designer/science` opens the → the `appScreen.screen`), and for the authenticated tree mounts the
empty new-science form, `/designer/science/{name}` opens the named matching screen component from `src/lib/screens/`
science. Ship-class design is folded into the sidebar ship-class (`login-screen.svelte`, `lobby-screen.svelte`,
`lobby-create-screen.svelte`) or, for `screen === "game"`, the in-game
shell `src/lib/game/game-shell.svelte`. The game shell in turn renders
the active view from `activeView` (see below). Navigation is
`appScreen.go(screen, { gameId })` and `activeView.select(view,
params)` — never `goto`.
### Active-view dispatch
The client renders **one active view at a time**. The game shell
(`game-shell.svelte`) holds an `{#if}` ladder keyed on
`activeView.view` that mounts the matching content component from
`src/lib/active-view/<name>.svelte`:
| `activeView.view` | sub-params | Active view component |
| ------------------- | ----------------------- | ---------------------------------------------------------------------- |
| `map` | — | `lib/active-view/map.svelte` |
| `table` | `tableEntity` | `lib/active-view/table.svelte` |
| `report` | — | `lib/active-view/report.svelte` (see [report-view.md](report-view.md)) |
| `battle` | `battleId`, `turn` | `lib/active-view/battle.svelte` |
| `mail` | — | `lib/active-view/mail.svelte` |
| `designer-science` | `scienceId` | `lib/active-view/designer-science.svelte` |
Entering a game defaults the view to `map` (`activeView.reset()`).
The optional `scienceId` sub-param on the science designer is absent
for the empty new-science form and set to the science name for an
existing one. Ship-class design is folded into the sidebar ship-class
calculator (`lib/sidebar/calculator-tab.svelte`, see calculator (`lib/sidebar/calculator-tab.svelte`, see
[calculator-ux.md](calculator-ux.md)), reached from the ship-classes [calculator-ux.md](calculator-ux.md)), reached from the ship-classes
table and the view/bottom menus. table and the view/bottom menus.
The `entity` slug on the table route is kebab-case (`planets`, The `tableEntity` slug is kebab-case (`planets`, `ship-classes`,
`ship-classes`, `ship-groups`, `fleets`, `sciences`, `races`). `ship-groups`, `fleets`, `sciences`, `races`). `table.svelte` is the
`table.svelte` is the active-view router: it dispatches by slug to table dispatcher: it switches by slug to the per-entity component
the per-entity component (`ship-classes``table-ship-classes.svelte`; (`ship-classes``table-ship-classes.svelte`; other entities dispatch
other entities dispatch to their respective components). to their respective components).
## Screen history: Back/Forward without a URL
Browser **Back/Forward move between screens**, not views, and they do
so without ever changing the URL. The shell layers screen history on
top of `appScreen` via SvelteKit shallow routing: `appScreen.go(...)`
calls `pushState("", { screen, gameId })` for the overlay screens
(`game`, `lobby-create`) and `replaceState(...)` for `lobby` / `login`,
so browser **Back from a game returns to the lobby** beneath it. On
the first authenticated render the dispatcher stamps the restored
overlay on top of the load entry, then mirrors `page.state` back into
the store on every popstate through `appScreen.syncFromHistory(...)`.
The store is the source of truth; history only mirrors it.
In-game **view switches do not create history entries**
`activeView.select(...)` only mutates state and persists the snapshot.
Back from any in-game view therefore leaves the game entirely rather
than stepping through the views the player visited.
A **"return to lobby" control** lives in the in-game header
(`lib/header/header.svelte`, `data-testid="return-to-lobby"`,
label `game.shell.menu.return_to_lobby`); it calls
`appScreen.go("lobby")`.
## Refresh and restore
`appScreen` / `activeView` persist a snapshot (screen, game id, view +
sub-params) to `sessionStorage` (`galaxy-app-nav`) on every mutation
and read it back once at construction, so a refresh restores the last
screen and view. On a full load the dispatcher records the restored
game id (`appScreen.restoredGameId`); the game shell's boot path then
validates it against the player's game list. `GameStateStore.init`
looks the game up through `listMyGames` / `findGame`, and if the game
is gone (cancelled, removed, or access revoked) it sets the distinct
`gameState.notFound` flag. The shell reacts by dropping to the lobby
(`appScreen.go("lobby")`) with an `game.events.unavailable` toast
rather than stranding the user on an in-game error. A transient
network error keeps `notFound` false and surfaces the in-game error
state instead. See [`game-state.md`](game-state.md) for the
`notFound` semantics.
## Standalone-target compatibility
The single-URL app-shell is the natural fit for the planned
standalone wrappers (Wails desktop, Capacitor / gomobile mobile —
see [`../ROADMAP.md`](../ROADMAP.md)). Those targets load a single
bundled `index.html` with no server, no per-route URLs, and no browser
history to rely on; an in-memory screen/view model and shallow-routing
history that never touches the address bar work there unchanged.
## Sidebar tools and state preservation ## Sidebar tools and state preservation
@@ -53,36 +127,38 @@ The desktop sidebar hosts three tools:
| Order | `lib/sidebar/order-tab.svelte` | | Order | `lib/sidebar/order-tab.svelte` |
The selected-tab state is a `$state` rune in The selected-tab state is a `$state` rune in
`routes/games/[id]/+layout.svelte`, bound into `lib/game/game-shell.svelte`, bound into
`lib/sidebar/sidebar.svelte` via `$bindable()`. The layout owns the `lib/sidebar/sidebar.svelte` via `$bindable()`. The shell owns the
rune so external events — such as a planet click — can drive the rune so external events — such as a planet click — can drive the
active tab from outside the sidebar without plumbing callbacks. The component is mounted by the layout, and active tab from outside the sidebar without plumbing callbacks. The
SvelteKit keeps that layout instance alive while the user navigates shell instance lives for the lifetime of the `game` screen, and an
between child routes (`/games/:id/map``/games/:id/report` → …), in-game view switch is a pure `activeView` state change that never
so the rune survives every active-view switch automatically with no remounts the shell, so the rune survives every active-view switch
URL coupling needed. The URL seed and the history-mode reset automatically — it is in-memory state, with no URL coupling. The
described below still live inside the sidebar — they mutate the history-mode reset described below lives inside the sidebar — it
bindable in place; the layout sees the change through the binding. mutates the bindable in place; the shell sees the change through the
binding.
A `?sidebar=calc|calculator|inspector|order` URL param is read once The tool state is pure in-memory rune state. There is no `?sidebar=`
on mount and seeds the initial tab. Navigation flows that want to URL param (the app-shell has no per-screen URL to carry one) and no
land the user on a particular tool can set this param on navigation. default-tab URL seed; the shell opens on its `inspector` default and
external events flip the tab.
The Order entry is hidden when the layout's `historyMode` flag is The Order entry is hidden when the shell's `historyMode` flag is
true. `+layout.svelte` forwards a derived value to `Sidebar`, which true. `game-shell.svelte` forwards a derived value to `Sidebar`, which
forwards `hideOrder` to its `TabBar`; the same flag goes to forwards `hideOrder` to its `TabBar`; the same flag goes to
`BottomTabs` so the mobile `Order` button is also suppressed. A `BottomTabs` so the mobile `Order` button is also suppressed. An
`?sidebar=order` URL seed that arrives while the flag is true falls `$effect` on the sidebar resets `activeTab` away from `order` if the
back to `inspector`, and an `$effect` on the sidebar resets flag flips on mid-session.
`activeTab` away from `order` if the flag flips on mid-session.
The `historyMode` flag is derived from the live history signal owned The `historyMode` flag is derived from the live history signal owned
by `GameStateStore`. The derivation lives directly in `+layout.svelte` by `GameStateStore`. The derivation lives directly in
`game-shell.svelte`
(`const historyMode = $derived(gameState.historyMode)`) — no (`const historyMode = $derived(gameState.historyMode)`) — no
separate `lib/history-mode.ts` module exists, because the layout is separate `lib/history-mode.ts` module exists, because the shell is
the single consumer and the project's compactness rule rejects a the single consumer and the project's compactness rule rejects a
one-line indirection. The order draft survives the toggle because one-line indirection. The order draft survives the toggle because
`OrderDraftStore` lives one level above the sidebar in the layout `OrderDraftStore` lives one level above the sidebar in the shell
hierarchy; the same `historyMode` derivation is also fed into hierarchy; the same `historyMode` derivation is also fed into
`OrderDraftStore.bindClient` so inspector-driven mutations `OrderDraftStore.bindClient` so inspector-driven mutations
(`add` / `remove` / `move`) become no-ops while the user is (`add` / `remove` / `move`) become no-ops while the user is
@@ -107,7 +183,7 @@ header whenever `gameState.historyMode === true`. It shows
"Viewing turn {N} · read-only" with a "Return to current turn" "Viewing turn {N} · read-only" with a "Return to current turn"
button that delegates back to `gameState.returnToCurrent()`. Both button that delegates back to `gameState.returnToCurrent()`. Both
the navigator and the banner read `gameState` through context, so the navigator and the banner read `gameState` through context, so
the layout is the only place where the wiring lives. the game shell is the only place where the wiring lives.
## Layout breakpoints ## Layout breakpoints
@@ -134,18 +210,20 @@ raises a bottom-sheet — see [Planet selection](#planet-selection).
## Mobile bottom-tabs and tool overlay ## Mobile bottom-tabs and tool overlay
The bottom-tabs row is `[Map, Calc, Order, More]`. Map navigates to The bottom-tabs row is `[Map, Calc, Order, More]`. Map selects the
`/games/:id/map` and clears any tool overlay. Calc and Order navigate map view (`activeView.select("map")`) and clears any tool overlay.
to `/games/:id/map` too — but they also flip the layout's Calc and Order select the map view too — but they also flip the
`mobileTool` state to `calc` / `order`, which the layout uses to shell's `mobileTool` state to `calc` / `order`, which the shell uses
swap the active-view slot for the Calculator / Order tool component. to swap the active-view slot for the Calculator / Order tool
component.
The tool overlay only applies when the URL is `/map`. Navigating to The tool overlay only applies while the active view is the map.
any other view through the More drawer or the header view-menu makes The shell's derived `effectiveTool` is gated by
the layout's derived `effectiveTool` collapse back to `map`, so the `activeView.view === "map"`: selecting any other view through the More
user always sees the URL's active view rather than a stale overlay. drawer or the header view-menu collapses `effectiveTool` back to
The next time the user taps a Calc or Order bottom-tab, the `map`, so the user always sees the active view rather than a stale
navigation re-routes them to `/map` and re-applies the overlay. overlay. The next time the user taps a Calc or Order bottom-tab, the
selection switches back to the map view and re-applies the overlay.
The `More` button opens a drawer that mirrors the header view-menu The `More` button opens a drawer that mirrors the header view-menu
content. A narrower "More" list (Mail, Battle log, Tables, History, content. A narrower "More" list (Mail, Battle log, Tables, History,
@@ -155,12 +233,12 @@ a single source of truth for destinations.
## Transient map overlays ## Transient map overlays
Some views can push a transient overlay onto `/map` with a back Some views can push a transient overlay onto the map view with a back
affordance. (The calculator reach circles are a simpler, always-on affordance. (The calculator reach circles are a simpler, always-on
map extra rather than a back-stacked overlay; the transient map extra rather than a back-stacked overlay; the transient
back-stack mechanism is planned — see back-stack mechanism is planned — see
[../ROADMAP.md](../ROADMAP.md).) A transient overlay clears when the [../ROADMAP.md](../ROADMAP.md).) A transient overlay clears when the
user navigates to any other view via the header or the bottom-tabs. user selects any other view via the header or the bottom-tabs.
The back-stack mechanism is not yet implemented; it is planned The back-stack mechanism is not yet implemented; it is planned
alongside its first user (multi-turn projection, range circles in the alongside its first user (multi-turn projection, range circles in the
@@ -180,14 +258,14 @@ translating a renderer click into a planet selection. The flow:
primitive, looks the planet up by `number` in the live primitive, looks the planet up by `number` in the live
`GameStateStore.report`, and calls `SelectionStore.selectPlanet(number)`. `GameStateStore.report`, and calls `SelectionStore.selectPlanet(number)`.
3. `SelectionStore` (`lib/selection.svelte.ts`) is a runes store 3. `SelectionStore` (`lib/selection.svelte.ts`) is a runes store
instantiated by the layout and exposed via Svelte context under instantiated by the game shell and exposed via Svelte context under
`SELECTION_CONTEXT_KEY`. It carries a discriminated union — `SELECTION_CONTEXT_KEY`. It carries a discriminated union —
`{ kind: "planet"; id: number }` for planets and widened for `{ kind: "planet"; id: number }` for planets and widened for
ship groups. Selection is in-memory only: it survives the ship groups. Selection is in-memory only: it survives the
layout's lifetime (active-view switches inside `/games/:id/*`) shell's lifetime (in-memory `activeView` switches inside the game
but does not persist across reloads — that contrast with the screen) but does not persist across reloads — that contrast with
order draft is intentional. the order draft is intentional.
4. The layout watches the selection rune and, on the null → planet 4. The shell watches the selection rune and, on the null → planet
transition, flips its bound `activeTab` to `inspector` and transition, flips its bound `activeTab` to `inspector` and
`sidebarOpen` to `true`. Desktop already has the sidebar pinned; `sidebarOpen` to `true`. Desktop already has the sidebar pinned;
tablet needs the drawer to surface; mobile is unaffected by the tablet needs the drawer to surface; mobile is unaffected by the
@@ -201,7 +279,7 @@ translating a renderer click into a planet selection. The flow:
state instead of holding stale rows. state instead of holding stale rows.
The mobile bottom-sheet is mounted alongside `<BottomTabs />` in the The mobile bottom-sheet is mounted alongside `<BottomTabs />` in the
layout. Its visibility is conditional on `effectiveTool === "map"` so game shell. Its visibility is conditional on `effectiveTool === "map"` so
it does not stack on top of the calc / order overlays. The dismissal it does not stack on top of the calc / order overlays. The dismissal
surface is a close button (`✕`) that calls `SelectionStore.clear()`. surface is a close button (`✕`) that calls `SelectionStore.clear()`.
Tap-outside and swipe-down dismissal are deferred to the finalization Tap-outside and swipe-down dismissal are deferred to the finalization
@@ -224,8 +302,12 @@ together with the sheet's swipe-to-dismiss gesture.
## Auth gate ## Auth gate
The root `+layout.svelte` redirects `anonymous → /login` for any The auth gate is state-based, applied by the dispatcher
non-`/__debug/` path; the in-game shell inherits that gate without (`src/routes/+page.svelte`): an `anonymous` session renders the login
any extra check. When a session is revoked while the user is in the screen, an `authenticated` one renders the `appScreen.screen` (lobby /
shell, the same redirect fires through the existing game / …). There is no `goto("/login")` redirect. When a session is
revocation watcher. revoked while the user is in the game shell, the revocation watcher
flips `session.status` back to `anonymous`, and the dispatcher swaps
the whole tree to the login screen on the next render — the URL stays
`/game/` throughout. See [`auth-flow.md`](auth-flow.md) for the
session state machine.
+9 -11
View File
@@ -195,15 +195,15 @@ Lifecycle:
| `dispose()` | Marks the store destroyed; subsequent `persist()` calls are no-ops so a fast game-switch does not write stale state into the next id. | | `dispose()` | Marks the store destroyed; subsequent `persist()` calls are no-ops so a fast game-switch does not write stale state into the next id. |
Mutations made before `init` resolves are silently ignored — the Mutations made before `init` resolves are silently ignored — the
layout always awaits `init` through `Promise.all([...])` next to shell always awaits `init` through `Promise.all([...])` next to
`gameState.init` before exposing the store. `gameState.init` before exposing the store.
Layout integration mirrors `GameStateStore`: Shell integration mirrors `GameStateStore`:
- One instance per game, created in - One instance per game, created in the in-game shell
[`../frontend/src/routes/games/[id]/+layout.svelte`](../frontend/src/routes/games/[id]/+layout.svelte). [`../frontend/src/lib/game/game-shell.svelte`](../frontend/src/lib/game/game-shell.svelte).
- Exposed through the `ORDER_DRAFT_CONTEXT_KEY` Svelte context. - Exposed through the `ORDER_DRAFT_CONTEXT_KEY` Svelte context.
- Disposed in the layout's `onDestroy`. - Disposed in the shell's `onDestroy`.
The order tab and the planet inspector both consume the store via The order tab and the planet inspector both consume the store via
`getContext(ORDER_DRAFT_CONTEXT_KEY)` to push new commands. `getContext(ORDER_DRAFT_CONTEXT_KEY)` to push new commands.
@@ -257,7 +257,7 @@ snapshot (history mode is the planned reader).
`OrderDraftStore` records `needsServerHydration = true` when no `OrderDraftStore` records `needsServerHydration = true` when no
cache row exists for the active game (fresh install, cleared cache row exists for the active game (fresh install, cleared
storage, switching device). After the layout boot resolves both storage, switching device). After the shell boot resolves both
`gameState.init` and `orderDraft.init`, it calls `gameState.init` and `orderDraft.init`, it calls
`orderDraft.hydrateFromServer({ client, turn })` which issues `orderDraft.hydrateFromServer({ client, turn })` which issues
`user.games.order.get` against the gateway. A `found = false` `user.games.order.get` against the gateway. A `found = false`
@@ -294,14 +294,12 @@ report as it was. The Order tab is hidden when history mode is active
— the player is browsing an immutable snapshot, and composing commands — the player is browsing an immutable snapshot, and composing commands
against it would be confusing. against it would be confusing.
The layout owns the `historyMode` flag and passes it to: The in-game shell owns the `historyMode` flag and passes it to:
- `Sidebar` as `historyMode`. The sidebar forwards it to its - `Sidebar` as `historyMode`. The sidebar forwards it to its
`TabBar` as `hideOrder`. The Order entry is filtered out of the `TabBar` as `hideOrder`. The Order entry is filtered out of the
tab list when true. If a `?sidebar=order` URL seed lands while tab list when true. If the active tab is `order` when the flag
the flag is true, the sidebar falls back to `inspector`. If the flips on, an effect resets it to `inspector`.
active tab is `order` when the flag flips on, an effect resets
it to `inspector`.
- `BottomTabs` as `hideOrder`. The mobile bottom-tab `Order` - `BottomTabs` as `hideOrder`. The mobile bottom-tab `Order`
button is suppressed when true. button is suppressed when true.
+13 -3
View File
@@ -4,12 +4,21 @@ The web client is an installable, offline-tolerant PWA. It uses
SvelteKit's native service worker (no Workbox) so there is no extra SvelteKit's native service worker (no Workbox) so there is no extra
build dependency and the cache logic stays explicit. build dependency and the cache logic stays explicit.
The single-URL app-shell (see [`navigation.md`](navigation.md)) makes
the offline story simpler: the whole game UI lives at one route
(`${base}/`, i.e. `/game/` under the single-origin deployment), so
there is exactly one navigation target to precache and fall back to —
no per-screen routes to enumerate. The service-worker scope and the
manifest are unchanged by that refactor; both were already base-aware
(the SW keys everything off `$service-worker`'s `base`, and the
manifest uses relative `./` `start_url` / `scope`).
## Pieces ## Pieces
- [`src/service-worker.ts`](../frontend/src/service-worker.ts) — the - [`src/service-worker.ts`](../frontend/src/service-worker.ts) — the
worker. SvelteKit registers it automatically in the production build. worker. SvelteKit registers it automatically in the production build.
It precaches the app shell (`/`), the build artefacts (JS/CSS + It precaches the app shell (`${base}/`), the build artefacts (JS/CSS
`core.wasm`), and the static files under a **version-keyed** cache + `core.wasm`), and the static files under a **version-keyed** cache
(`galaxy-cache-<version>`, `version` from `$service-worker`). On (`galaxy-cache-<version>`, `version` from `$service-worker`). On
`activate` it deletes every other cache, so a new deploy never serves `activate` it deletes every other cache, so a new deploy never serves
stale code. Strategy: cache-first for the version-keyed build/files; stale code. Strategy: cache-first for the version-keyed build/files;
@@ -17,7 +26,8 @@ build dependency and the cache logic stays explicit.
shell answers navigations when fully offline. The gateway (cross- shell answers navigations when fully offline. The gateway (cross-
origin) is never intercepted — it is always live network. origin) is never intercepted — it is always live network.
- [`static/manifest.webmanifest`](../frontend/static/manifest.webmanifest) - [`static/manifest.webmanifest`](../frontend/static/manifest.webmanifest)
— name, `standalone` display, `start_url`/`scope` `/`, dark — name, `standalone` display, relative `./` `start_url`/`scope` (so
it resolves under whatever `base` the build is deployed at), dark
`theme_color`/`background_color`, and the icon set. `theme_color`/`background_color`, and the icon set.
- [`static/icons/`](../frontend/static/icons/) — `192`/`512` (`any`), - [`static/icons/`](../frontend/static/icons/) — `192`/`512` (`any`),
a `512` `maskable`, and a `180` apple-touch icon. They are placeholder a `512` `maskable`, and a `180` apple-touch icon. They are placeholder
+18 -28
View File
@@ -107,36 +107,23 @@ visible area so that scrolling down advances the highlight
naturally. The observer is created on mount and torn down on naturally. The observer is created on mount and torn down on
unmount. unmount.
The in-game shell layout (`routes/games/[id]/+layout.svelte`) The in-game shell (`lib/game/game-shell.svelte`)
expands `<main class="active-view-host">` to fit content rather expands `<main class="active-view-host">` to fit content rather
than constraining it, so the document body is the actual scroll than constraining it, so the document body is the actual scroll
container — not the host. The IntersectionObserver root is `null` container — not the host. The IntersectionObserver root is `null`
to match. to match.
## Scroll save / restore ## Scroll position
`routes/games/[id]/report/+page.svelte` exports a SvelteKit The report is the `report` active view; switching to another view is
`Snapshot<{ scrollY: number }>`: an in-memory `activeView` state change, not a navigation, and the
report component is remounted when the user returns to it. The
- `capture()` reads `window.scrollY` when SvelteKit's single-URL app-shell therefore does not carry SvelteKit's route-keyed
`beforeNavigate` cycle runs. `Snapshot` scroll save/restore — that mechanism was tied to the old
- `restore(value)` schedules a short `/games/:id/report` route and was removed with it. A re-entered report
`requestAnimationFrame` poll that waits for opens at the top; the IntersectionObserver re-derives the active TOC
`document.documentElement.scrollHeight` to grow tall enough to slug from the scroll position on the next animation frame, so the
honour the saved offset, then calls `window.scrollTo(0, value)`. highlight stays consistent without a separate source of truth.
The poll caps at ~60 frames (≈ 1 second) so a never-tall-enough
body never pins a frame loop.
The capture / restore pair is keyed by route, so:
- Forward navigation from `/report` to `/map` lands `/map` at
scrollY 0 (no snapshot for `/map` to restore from).
- History-back from `/map` to `/report` restores the previously
captured scrollY — the user returns to the same section.
The Snapshot API does not capture the active sidebar slug; the
IntersectionObserver re-derives it from the restored scroll
position on the next animation frame, which keeps the TOC
highlight consistent without a second source of truth.
## i18n namespace ## i18n namespace
@@ -169,10 +156,13 @@ couple them silently.
/ IntersectionObserver are out of scope. / IntersectionObserver are out of scope.
- **Playwright** — `tests/e2e/report-sections.spec.ts` exercises - **Playwright** — `tests/e2e/report-sections.spec.ts` exercises
the full integration: every TOC anchor lands its section in the full integration: every TOC anchor lands its section in
view, the snapshot mechanism preserves `window.scrollY` on view, the back-to-map button switches to the map view
history navigation, the back-to-map button reaches `/map`, the (`activeView.select("map")`), and the mobile `<select>` scrolls
mobile `<select>` scrolls to the chosen section on a narrow to the chosen section on a narrow viewport. The spec drives the
viewport. app-shell through `window.__galaxyNav` (the dev-only nav surface)
instead of `page.goto` per-view URLs. The old "scroll position
survives a `/map` round-trip via SvelteKit `Snapshot`" case was
dropped — see the [scroll position](#scroll-position) note.
Test IDs follow the pattern `report-section-<slug>` for section Test IDs follow the pattern `report-section-<slug>` for section
roots, `report-toc-<slug>` for TOC anchors, and per-section row roots, `report-toc-<slug>` for TOC anchors, and per-section row
+2 -1
View File
@@ -186,7 +186,8 @@ Thin orchestration layer over `KeyStore` + `Cache`:
push-event-driven revocation path. push-event-driven revocation path.
A `null` `deviceSessionId` is the signal that the session is A `null` `deviceSessionId` is the signal that the session is
unauthenticated — the root layout routes such users to `/login`. unauthenticated — `session.status` settles to `anonymous` and the
dispatcher renders the login screen (the app-shell stays at `/game/`).
## Test layout ## Test layout
+9 -8
View File
@@ -128,9 +128,10 @@ report" affordance (`import.meta.env.DEV`). The flow is:
2. Run the UI dev server (`pnpm -C ui/frontend dev`), open the lobby, 2. Run the UI dev server (`pnpm -C ui/frontend dev`), open the lobby,
and use the "Load JSON…" file picker in the **Synthetic test and use the "Load JSON…" file picker in the **Synthetic test
reports (DEV)** section. The page navigates to reports (DEV)** section. The lobby enters a `synthetic-<uuid>` game
`/games/synthetic-<uuid>/map` with the report wired into the on the map view (`activeView.reset()` + `appScreen.go("game", {
in-game shell. gameId })`) with the report wired into the in-game shell. The
app-shell URL stays `/game/` — see [`navigation.md`](navigation.md).
In synthetic mode: In synthetic mode:
@@ -139,16 +140,16 @@ In synthetic mode:
- Composing orders works locally (overlay applies through - Composing orders works locally (overlay applies through
`applyOrderOverlay` as usual), but **nothing is sent to the `applyOrderOverlay` as usual), but **nothing is sent to the
gateway** — `OrderDraftStore.scheduleSync` short-circuits because gateway** — `OrderDraftStore.scheduleSync` short-circuits because
the synthetic id is not a UUID and the layout deliberately does the synthetic id is not a UUID and the in-game shell deliberately
not bind a `GalaxyClient` for this game. does not bind a `GalaxyClient` for this game.
- The order draft is persisted into the platform `Cache` under the - The order draft is persisted into the platform `Cache` under the
same `order-drafts` namespace as real games, keyed by the same `order-drafts` namespace as real games, keyed by the
synthetic id, so navigating back into the same synthetic session synthetic id, so navigating back into the same synthetic session
restores the draft. The cache is cleared with restores the draft. The cache is cleared with
`__galaxyDebug.clearOrderDraft(gameId)` (DEV debug surface). `__galaxyDebug.clearOrderDraft(gameId)` (DEV debug surface).
- A page reload loses the in-memory report registry; opening the - A page reload loses the in-memory report registry; a restored
same synthetic id afterwards redirects to /lobby. Re-load the JSON synthetic game whose report is gone falls back to the lobby
to reseed. (`appScreen.go("lobby")`). Re-load the JSON to reseed.
The synthetic-report parity rule requires every change that extends The synthetic-report parity rule requires every change that extends
`decodeReport` to also extend the legacy parser in lockstep, or to `decodeReport` to also extend the legacy parser in lockstep, or to
+3 -3
View File
@@ -16,8 +16,8 @@
// asynchronously; the watcher in `lib/revocation-watcher.ts` calls // asynchronously; the watcher in `lib/revocation-watcher.ts` calls
// it without user interaction. The post-condition is the same as // it without user interaction. The post-condition is the same as
// `signOut("user")` — keypair regenerated, session id wiped, // `signOut("user")` — keypair regenerated, session id wiped,
// status returned to `anonymous` — so the layout's existing // status returned to `anonymous` — so the dispatcher's state-based
// `anonymous → /login` redirect handles both reasons uniformly. // auth gate renders the login screen for both reasons uniformly.
import type { import type {
Cache, Cache,
@@ -83,7 +83,7 @@ export class SessionStore {
* revoked public key, and returns the status to `anonymous`. The * revoked public key, and returns the status to `anonymous`. The
* `reason` is recorded in console output for telemetry but does * `reason` is recorded in console output for telemetry but does
* not change the post-state — both user-driven logout and * not change the post-state — both user-driven logout and
* gateway-driven revocation land the user back on `/login`. * gateway-driven revocation return the user to the login screen.
*/ */
async signOut(reason: "user" | "revoked"): Promise<void> { async signOut(reason: "user" | "revoked"): Promise<void> {
if (this.keyStore === null || this.cache === null) { if (this.keyStore === null || this.cache === null) {
@@ -6,10 +6,8 @@
// 1. Every TOC anchor click scrolls the matching section into view // 1. Every TOC anchor click scrolls the matching section into view
// and the section is present in the DOM with at least one row // and the section is present in the DOM with at least one row
// (or its empty-state copy when it is intentionally empty). // (or its empty-state copy when it is intentionally empty).
// 2. Snapshot save/restore on the active-view-host scroll // 2. The "back to map" button switches to the map view.
// container survives a /map navigation round-trip. // 3. The mobile <select> fallback scrolls a section into view on
// 3. The "back to map" button navigates to the map URL.
// 4. The mobile <select> fallback scrolls a section into view on
// a narrow viewport. // a narrow viewport.
import { fromJson, type JsonValue } from "@bufbuild/protobuf"; import { fromJson, type JsonValue } from "@bufbuild/protobuf";