Files
galaxy-game/ui/frontend/tests/e2e/planet-production.spec.ts
T
Ilia Denisov 4a23c357e5
Tests · UI / test (push) Waiting to run
Tests · UI / test (pull_request) Waiting to run
feat(ui): F8-05 — game-mode chrome cleanup + inspector compact rows (#48)
Drains six F8 polish items (parent #43) in one feature:

а) Chrome cleanup
- п.6 — remove the AccountMenu (settings/sessions/theme/language/logout
  ∼ rudimentary in-game) and replace it with a single icon-button
  light/dark theme toggle. The toggle flips an in-memory `theme.override`;
  game-shell unmount calls `theme.clearOverride()` so the lobby (and
  any re-entry) re-projects the persisted lobby choice.
- п.8 — remove the wrap-scrolling radio from the map gear popover. The
  per-game `wrapMode` store and the renderer's no-wrap path stay in
  place for a future engine-side topology feature; only the UI surface
  is dropped (wrap is a server-side concept, not a per-session UI
  affordance).

б) Inspector compact rows (single idiom: select + ✓ apply / ✗ cancel,
or contextual edit/remove/add)
- п.13 — planet name is now click-to-edit: clicking the name opens an
  inline `<input>` + ✓ confirm icon; Escape cancels; the explicit
  Rename action button and Cancel button are gone.
- п.14 — production becomes one row: primary `<select>` picks
  industry/materials/research/ship, conditional secondary `<select>`
  picks the target (tech / science / ship class) for research and
  ship contexts. Apply is gated until row state differs from the
  planet's current effective production; auto-submit-on-click is
  replaced by the apply-gate.
- п.16 — cargo routes collapse to one row: a single dropdown
  (COL/CAP/MAT/EMP plus a placeholder that absorbs the old section
  title) and contextual action buttons (add / edit + remove) to the
  right. After a successful pick or remove the dropdown stays on the
  type the user just acted on.
- п.32 — stationed ship groups hoist the race column into a dropdown
  above the table. The dropdown seeds with the player's own race when
  local groups are stationed here, otherwise the first race
  alphabetically; rendered only when more than one race is in orbit.
  The race column is dropped in both single- and multi-race modes —
  the dropdown's value already names the active race.

Tests: unit and Playwright e2e updated for every changed test-id and
flow; new coverage added for `theme.override`, the in-game toggle, the
apply-gate behaviour, and the stationed-race dropdown. i18n keys for
the removed menu items, the wrap radios, the cargo title, and the
explicit `rename.cancel` are dropped from both locales; new
`game.shell.theme_toggle.*`, `production.main/target.*`,
`production.apply/cancel`, `cargo.placeholder`, and
`ship_groups.race_filter.aria` keys land.

Docs synced: `docs/FUNCTIONAL.md` §6.7 + `docs/FUNCTIONAL_ru.md`
mirror drop the torus / no-wrap radio mention; `ui/docs/design-system.md`
documents the lobby-owned persisted picker + the in-game ephemeral
override channel.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-27 13:38:42 +02:00

386 lines
11 KiB
TypeScript

// Phase 15 end-to-end coverage for the planet-production flow. Boots
// an authenticated session, mocks the lobby + report + order routes
// (including a seeded `Scout` ship class so the Build-Ship branch is
// reachable), drives a click into the renderer to select a planet,
// then walks the segmented control through three production choices.
// The final assertion verifies that the order tab carries exactly
// one row at all times (the collapse-by-`planetNumber` rule), that
// the gateway received the latest choice, and that the row survives
// a reload via `user.games.order.get`.
import { fromJson, type JsonValue } from "@bufbuild/protobuf";
import { expect, test, type Page } from "@playwright/test";
import { ByteBuffer } from "flatbuffers";
import { ExecuteCommandRequestSchema } from "../../src/proto/edge/v1/edge_gateway_pb";
import { UUID } from "../../src/proto/galaxy/fbs/common";
import {
CommandPlanetProduce,
PlanetProduction,
UserGamesOrder,
UserGamesOrderGet,
} from "../../src/proto/galaxy/fbs/order";
import { GameReportRequest } from "../../src/proto/galaxy/fbs/report";
import { forgeExecuteCommandResponseJson } from "./fixtures/sign-response";
import {
buildMyGamesListPayload,
type GameFixture,
} from "./fixtures/lobby-fbs";
import { buildReportPayload } from "./fixtures/report-fbs";
import {
buildOrderGetResponsePayload,
buildOrderResponsePayload,
type CommandResultFixture,
} from "./fixtures/order-fbs";
const SESSION_ID = "phase-15-production-session";
const GAME_ID = "15151515-1515-1515-1515-151515151515";
const WORLD = 4000;
const CENTRE = WORLD / 2;
const TURN = 5;
const SHIP_CLASS = "Scout";
interface MockHandle {
get lastSubmitted(): {
productionType: PlanetProduction;
subject: string;
planetNumber: number;
} | null;
get submitCount(): number;
}
async function mockGateway(page: Page): Promise<MockHandle> {
const game: GameFixture = {
gameId: GAME_ID,
gameName: "Phase 15 Game",
gameType: "private",
status: "running",
ownerUserId: "user-1",
minPlayers: 2,
maxPlayers: 8,
enrollmentEndsAtMs: BigInt(Date.now() + 86_400_000),
createdAtMs: BigInt(Date.now() - 86_400_000),
updatedAtMs: BigInt(Date.now()),
currentTurn: TURN,
};
let storedOrder: CommandResultFixture[] = [];
let lastReportProduction = "Drive";
let lastSubmitted: {
productionType: PlanetProduction;
subject: string;
planetNumber: number;
} | null = null;
let submitCount = 0;
await page.route(
"**/edge.v1.Gateway/ExecuteCommand",
async (route) => {
const reqText = route.request().postData();
if (reqText === null) {
await route.fulfill({ status: 400 });
return;
}
const req = fromJson(
ExecuteCommandRequestSchema,
JSON.parse(reqText) as JsonValue,
);
let resultCode = "ok";
let payload: Uint8Array;
switch (req.messageType) {
case "lobby.my.games.list":
payload = buildMyGamesListPayload([game]);
break;
case "user.games.report": {
GameReportRequest.getRootAsGameReportRequest(
new ByteBuffer(req.payloadBytes),
).gameId(new UUID());
payload = buildReportPayload({
turn: TURN,
mapWidth: WORLD,
mapHeight: WORLD,
localPlanets: [
{
number: 17,
name: "Earth",
x: CENTRE,
y: CENTRE,
size: 1000,
resources: 10,
capital: 0,
material: 0,
population: 850,
colonists: 25,
industry: 700,
production: lastReportProduction,
freeIndustry: 175,
},
],
localShipClass: [{ name: SHIP_CLASS }],
});
break;
}
case "user.games.order": {
const decoded = UserGamesOrder.getRootAsUserGamesOrder(
new ByteBuffer(req.payloadBytes),
);
submitCount += 1;
const length = decoded.commandsLength();
const fixtures: CommandResultFixture[] = [];
for (let i = 0; i < length; i++) {
const item = decoded.commands(i);
if (item === null) continue;
const cmdId = item.cmdId() ?? "";
const inner = new CommandPlanetProduce();
item.payload(inner);
const productionType = inner.production();
const subject = inner.subject() ?? "";
const planetNumber = Number(inner.number());
lastSubmitted = { productionType, subject, planetNumber };
fixtures.push({
kind: "setProductionType",
cmdId,
planetNumber,
productionType: planetProductionToLiteral(productionType),
subject,
applied: true,
errorCode: null,
});
}
storedOrder = fixtures;
if (lastSubmitted !== null) {
lastReportProduction = displayFromSubmitted(lastSubmitted);
}
payload = buildOrderResponsePayload(GAME_ID, fixtures, Date.now());
break;
}
case "user.games.order.get": {
UserGamesOrderGet.getRootAsUserGamesOrderGet(
new ByteBuffer(req.payloadBytes),
);
payload = buildOrderGetResponsePayload(
GAME_ID,
storedOrder,
Date.now(),
storedOrder.length > 0,
);
break;
}
default:
resultCode = "internal_error";
payload = new Uint8Array();
}
const body = await forgeExecuteCommandResponseJson({
requestId: req.requestId,
timestampMs: BigInt(Date.now()),
resultCode,
payloadBytes: payload,
});
await route.fulfill({
status: 200,
contentType: "application/json",
body,
});
},
);
await page.route(
"**/edge.v1.Gateway/SubscribeEvents",
async () => {
await new Promise<void>(() => {});
},
);
return {
get lastSubmitted() {
return lastSubmitted;
},
get submitCount() {
return submitCount;
},
};
}
async function bootSession(page: Page): Promise<void> {
await page.goto("/__debug/store");
await expect(page.getByTestId("debug-store-ready")).toBeVisible();
await page.waitForFunction(() => window.__galaxyDebug?.ready === true);
await page.evaluate(() => window.__galaxyDebug!.clearSession());
await page.evaluate(
(id) => window.__galaxyDebug!.setDeviceSessionId(id),
SESSION_ID,
);
await page.evaluate(
(gameId) => window.__galaxyDebug!.clearOrderDraft(gameId),
GAME_ID,
);
}
async function clickPlanetCentre(page: Page): Promise<void> {
const canvas = page.locator("canvas");
const box = await canvas.boundingBox();
expect(box).not.toBeNull();
if (box === null) throw new Error("canvas has no bounding box");
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
}
function planetProductionToLiteral(
value: PlanetProduction,
): "MAT" | "CAP" | "DRIVE" | "WEAPONS" | "SHIELDS" | "CARGO" | "SCIENCE" | "SHIP" {
switch (value) {
case PlanetProduction.MAT:
return "MAT";
case PlanetProduction.CAP:
return "CAP";
case PlanetProduction.DRIVE:
return "DRIVE";
case PlanetProduction.WEAPONS:
return "WEAPONS";
case PlanetProduction.SHIELDS:
return "SHIELDS";
case PlanetProduction.CARGO:
return "CARGO";
case PlanetProduction.SCIENCE:
return "SCIENCE";
case PlanetProduction.SHIP:
return "SHIP";
default:
throw new Error(`unexpected production enum ${value}`);
}
}
function displayFromSubmitted(value: {
productionType: PlanetProduction;
subject: string;
}): string {
switch (value.productionType) {
case PlanetProduction.MAT:
return "Material";
case PlanetProduction.CAP:
return "Capital";
case PlanetProduction.DRIVE:
return "Drive";
case PlanetProduction.WEAPONS:
return "Weapons";
case PlanetProduction.SHIELDS:
return "Shields";
case PlanetProduction.CARGO:
return "Cargo";
case PlanetProduction.SCIENCE:
case PlanetProduction.SHIP:
return value.subject;
default:
return "";
}
}
test("switching production three times collapses to one auto-synced row", async ({
page,
}, testInfo) => {
test.skip(
testInfo.project.name.startsWith("chromium-mobile"),
"phase 15 spec covers desktop layout; mobile inherits the same store",
);
const handle = await mockGateway(page);
await bootSession(page);
await page.goto("/");
await page.waitForFunction(() => window.__galaxyNav !== undefined);
await page.evaluate(
(id) => window.__galaxyNav!.enterGame(id, "map", {}),
GAME_ID,
);
await expect(page.getByTestId("active-view-map")).toHaveAttribute(
"data-status",
"ready",
);
await clickPlanetCentre(page);
const sidebar = page.getByTestId("sidebar-tool-inspector");
await expect(sidebar.getByTestId("inspector-planet-name")).toHaveText("Earth");
const mainSelect = sidebar.getByTestId("inspector-planet-production-main");
const targetSelect = sidebar.getByTestId(
"inspector-planet-production-target",
);
const applyBtn = sidebar.getByTestId("inspector-planet-production-apply");
// Initial state: report.production = "Drive" → main is "research"
// and the target is "DRIVE"; both apply/cancel start inert.
await expect(mainSelect).toHaveValue("research");
await expect(targetSelect).toHaveValue("DRIVE");
await expect(applyBtn).toBeDisabled();
// Pick 1: Industry + ✓ → CAP
await mainSelect.selectOption("industry");
await expect(applyBtn).toBeEnabled();
await applyBtn.click();
await page.getByTestId("sidebar-tab-order").click();
const orderTool = page.getByTestId("sidebar-tool-order");
await expect(orderTool.getByTestId("order-list").locator("li")).toHaveCount(
1,
);
await expect(orderTool.getByTestId("order-command-label-0")).toContainText(
"Capital",
);
await expect(orderTool.getByTestId("order-command-status-0")).toHaveText(
"applied",
);
// Pick 2: Materials + ✓ → MAT (replaces CAP via collapse)
await page.getByTestId("sidebar-tab-inspector").click();
await mainSelect.selectOption("materials");
await applyBtn.click();
await page.getByTestId("sidebar-tab-order").click();
await expect(orderTool.getByTestId("order-list").locator("li")).toHaveCount(
1,
);
await expect(orderTool.getByTestId("order-command-label-0")).toContainText(
"Material",
);
// Pick 3: Build Ship → target select appears → Scout + ✓ (replaces MAT)
await page.getByTestId("sidebar-tab-inspector").click();
await mainSelect.selectOption("ship");
await targetSelect.selectOption(SHIP_CLASS);
await applyBtn.click();
await page.getByTestId("sidebar-tab-order").click();
await expect(orderTool.getByTestId("order-list").locator("li")).toHaveCount(
1,
);
await expect(orderTool.getByTestId("order-command-label-0")).toContainText(
SHIP_CLASS,
);
await expect(orderTool.getByTestId("order-sync")).toHaveAttribute(
"data-sync-status",
"synced",
);
expect(handle.lastSubmitted).not.toBeNull();
expect(handle.lastSubmitted!.planetNumber).toBe(17);
expect(handle.lastSubmitted!.productionType).toBe(PlanetProduction.SHIP);
expect(handle.lastSubmitted!.subject).toBe(SHIP_CLASS);
expect(handle.submitCount).toBeGreaterThanOrEqual(3);
// Reload: the shell polls user.games.order.get on boot, so the
// row is restored from the server's stored state even when the
// local cache is wiped. The restored `game` screen re-stamps
// history via shallow routing on first render, so wait only for the
// navigation to commit (a default `reload()` waiting for `load`
// races that `pushState` and aborts).
await page.reload({ waitUntil: "commit" });
await expect(page.getByTestId("active-view-map")).toHaveAttribute(
"data-status",
"ready",
);
await page.getByTestId("sidebar-tab-order").click();
await expect(orderTool.getByTestId("order-list").locator("li")).toHaveCount(
1,
);
await expect(orderTool.getByTestId("order-command-label-0")).toContainText(
SHIP_CLASS,
);
});