feat(ui): F8-10 — tables planets / ship-groups / fleets, ship-classes delete guard (#53)
Tests · UI / test (push) Waiting to run
Tests · UI / test (pull_request) Successful in 2m45s

Lights up three previously-stubbed table active views and tightens the
existing one:

  - table-planets: 4 kind checkboxes (own / foreign / uninhabited /
    unknown) + race dropdown that filters the foreign slice; row click
    selects + centres the planet on the map.
  - table-ship-groups: local + foreign groups in one grid, owner
    checkboxes, planet dropdown (destination OR origin), class
    dropdown; on-planet click focuses the destination planet, in-space
    click focuses the ship group itself (camera follows interpolated
    position).
  - table-fleets: own fleets only with the shared planet dropdown;
    on-planet click focuses the planet, in-space click centres the
    camera on the interpolated fleet position without altering the
    selection (no fleet variant in Selected).
  - table-ship-classes: per-row Delete is disabled with a count tooltip
    while at least one local ship group references the class. The
    engine refuses the removal anyway; the UI pre-empts the surface.

Wires the click → map flow through a transient `SelectionStore.focus`
/ `focusPoint` channel that `map.svelte` consumes once on mount —
in-memory only, so an F5 does not re-centre.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Ilia Denisov
2026-05-27 20:35:38 +02:00
parent ef4cecb4b2
commit 80ed11e3b6
17 changed files with 2537 additions and 22 deletions
+143
View File
@@ -0,0 +1,143 @@
// F8-10 end-to-end coverage for the planets table → map navigation.
// Boots an authenticated session, mocks the gateway with a small
// planets-only report, navigates to `table → planets`, clicks the
// first row, and asserts the active view switches to the map (which
// also implicitly proves that the `SelectionStore.focus` → map mount
// hand-off lands inside the live shell). Ship-groups and fleets are
// covered by their vitest specs — one e2e is enough to smoke the
// composed flow.
import { fromJson, type JsonValue } from "@bufbuild/protobuf";
import { expect, test, type Page } from "@playwright/test";
import { ExecuteCommandRequestSchema } from "../../src/proto/edge/v1/edge_gateway_pb";
import { forgeExecuteCommandResponseJson } from "./fixtures/sign-response";
import {
buildMyGamesListPayload,
type GameFixture,
} from "./fixtures/lobby-fbs";
import { buildReportPayload } from "./fixtures/report-fbs";
const SESSION_ID = "f8-10-tables-session";
const GAME_ID = "f8101010-0000-4000-8000-101010101010";
async function mockGateway(page: Page): Promise<void> {
const game: GameFixture = {
gameId: GAME_ID,
gameName: "F8-10 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: 1,
};
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 payload: Uint8Array;
switch (req.messageType) {
case "lobby.my.games.list":
payload = buildMyGamesListPayload([game]);
break;
case "user.games.report":
payload = buildReportPayload({
turn: 1,
mapWidth: 4000,
mapHeight: 4000,
localPlanets: [
{ number: 1, name: "Home", x: 1000, y: 1000 },
],
otherPlanets: [
{
number: 2,
name: "Frontier",
x: 2000,
y: 1500,
owner: "Federation",
},
],
uninhabitedPlanets: [
{ number: 3, name: "Rock", x: 1500, y: 2200 },
],
});
break;
default:
payload = new Uint8Array();
}
const body = await forgeExecuteCommandResponseJson({
requestId: req.requestId,
timestampMs: BigInt(Date.now()),
resultCode: "ok",
payloadBytes: payload,
});
await route.fulfill({
status: 200,
contentType: "application/json",
body,
});
},
);
// Hold SubscribeEvents open — mirrors the pattern in other e2e
// specs to avoid the revocation watcher signing the session out.
await page.route(
"**/edge.v1.Gateway/SubscribeEvents",
async () => {
await new Promise<void>(() => {});
},
);
}
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,
);
}
test("clicking a row in the planets table opens the map", async ({ page }) => {
await mockGateway(page);
await bootSession(page);
await page.goto("/");
await page.waitForFunction(() => window.__galaxyNav !== undefined);
await page.evaluate(
(id) =>
window.__galaxyNav!.enterGame(id, "table", {
tableEntity: "planets",
}),
GAME_ID,
);
const table = page.getByTestId("planets-table");
await expect(table).toBeVisible();
const rows = page.getByTestId("planets-row");
await expect(rows).toHaveCount(3);
// Click the foreign planet — the data-* stamps let the spec assert
// against a deterministic row regardless of default sort.
await page
.locator('[data-testid="planets-row"][data-number="2"]')
.click();
await expect(page.getByTestId("active-view-map")).toBeVisible();
});
+6 -11
View File
@@ -48,21 +48,16 @@ describe("active-view stubs", () => {
expect(ui.getByTestId("map-canvas-wrap")).toBeInTheDocument();
});
test("table stub falls back for not-yet-implemented entities", () => {
const ui = render(TableView, { props: { entity: "planets" } });
test("table stub falls back for unknown entities", () => {
// Every menu-known slug is wired to a real component by F8-10;
// the fallback branch still exists for defensive routing (e.g.
// a restored snapshot referencing a removed entity).
const ui = render(TableView, { props: { entity: "unknown-slug" } });
const node = ui.getByTestId("active-view-table");
expect(node).toHaveAttribute("data-entity", "planets");
expect(node).toHaveTextContent("planets");
expect(node).toHaveAttribute("data-entity", "unknown-slug");
expect(node).toHaveTextContent("coming soon");
});
test("table stub also handles multi-word entities", () => {
const ui = render(TableView, { props: { entity: "ship-groups" } });
const node = ui.getByTestId("active-view-table");
expect(node).toHaveAttribute("data-entity", "ship-groups");
expect(node).toHaveTextContent("ship groups");
});
test("report view mounts with the icon-popup TOC", () => {
// Phase 23 replaces the Phase 10 stub with the full report
// orchestrator. The orchestrator mounts the table of contents
+85
View File
@@ -44,4 +44,89 @@ describe("SelectionStore", () => {
store.clear();
expect(store.selected).toBeNull();
});
test("focus sets the selection and queues the pending focus", () => {
const store = new SelectionStore();
store.focus({ kind: "planet", id: 11 });
expect(store.selected).toEqual({ kind: "planet", id: 11 });
expect(store.consumePendingFocus()).toEqual({ kind: "planet", id: 11 });
});
test("focus also works for a ship group target", () => {
const store = new SelectionStore();
store.focus({ kind: "shipGroup", ref: { variant: "local", id: "abc" } });
expect(store.selected).toEqual({
kind: "shipGroup",
ref: { variant: "local", id: "abc" },
});
expect(store.consumePendingFocus()).toEqual({
kind: "shipGroup",
ref: { variant: "local", id: "abc" },
});
});
test("consumePendingFocus clears the queued request", () => {
const store = new SelectionStore();
store.focus({ kind: "planet", id: 1 });
expect(store.consumePendingFocus()).not.toBeNull();
expect(store.consumePendingFocus()).toBeNull();
});
test("consumePendingFocus returns null when no focus was queued", () => {
const store = new SelectionStore();
store.selectPlanet(5);
expect(store.consumePendingFocus()).toBeNull();
});
test("clear leaves any queued pending focus untouched", () => {
const store = new SelectionStore();
store.focus({ kind: "planet", id: 9 });
store.clear();
expect(store.selected).toBeNull();
expect(store.consumePendingFocus()).toEqual({ kind: "planet", id: 9 });
});
test("dispose drops a queued pending focus", () => {
const store = new SelectionStore();
store.focus({ kind: "planet", id: 2 });
store.dispose();
expect(store.consumePendingFocus()).toBeNull();
});
test("focus is a no-op after dispose", () => {
const store = new SelectionStore();
store.dispose();
store.focus({ kind: "planet", id: 7 });
expect(store.selected).toBeNull();
expect(store.consumePendingFocus()).toBeNull();
});
test("focusPoint queues a coord without touching selection", () => {
const store = new SelectionStore();
store.selectPlanet(1);
store.focusPoint(12, 34);
expect(store.selected).toEqual({ kind: "planet", id: 1 });
expect(store.consumePendingCenter()).toEqual({ x: 12, y: 34 });
});
test("consumePendingCenter clears the queued point", () => {
const store = new SelectionStore();
store.focusPoint(5, 7);
expect(store.consumePendingCenter()).toEqual({ x: 5, y: 7 });
expect(store.consumePendingCenter()).toBeNull();
});
test("dispose drops a queued pending centre", () => {
const store = new SelectionStore();
store.focusPoint(1, 2);
store.dispose();
expect(store.consumePendingCenter()).toBeNull();
});
test("focusPoint is a no-op after dispose", () => {
const store = new SelectionStore();
store.dispose();
store.focusPoint(1, 2);
expect(store.consumePendingCenter()).toBeNull();
});
});
+219
View File
@@ -0,0 +1,219 @@
// Vitest coverage for the F8-10 fleets table active view.
// Mounts the component against a synthetic `RenderedReportSource`
// and a real `SelectionStore`; verifies the click semantics for both
// on-planet (focus the destination planet) and in-space (centre the
// camera on the interpolated point, leave selection untouched).
import "@testing-library/jest-dom/vitest";
import { fireEvent, render } from "@testing-library/svelte";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { i18n } from "../src/lib/i18n/index.svelte";
import type {
GameReport,
ReportLocalFleet,
ReportPlanet,
} from "../src/api/game-state";
import { RENDERED_REPORT_CONTEXT_KEY } from "../src/lib/rendered-report.svelte";
import {
SELECTION_CONTEXT_KEY,
SelectionStore,
} from "../src/lib/selection.svelte";
import { activeView } from "../src/lib/app-nav.svelte";
import { EMPTY_SHIP_GROUPS } from "./helpers/empty-ship-groups";
const pageMock = vi.hoisted(() => ({
url: new URL("http://localhost/games/g1/table/fleets"),
params: { id: "g1" } as Record<string, string>,
}));
const gotoMock = vi.hoisted(() => vi.fn());
vi.mock("$app/state", () => ({
page: pageMock,
}));
vi.mock("$app/navigation", () => ({
goto: gotoMock,
pushState: vi.fn(),
replaceState: vi.fn(),
}));
import TableFleets from "../src/lib/active-view/table-fleets.svelte";
let selection: SelectionStore;
beforeEach(() => {
selection = new SelectionStore();
i18n.resetForTests("en");
pageMock.params = { id: "g1" };
gotoMock.mockClear();
activeView.reset();
});
afterEach(() => {
selection.dispose();
});
function planet(num: number, x = 0, y = 0): ReportPlanet {
return {
number: num,
name: `P${num}`,
x,
y,
kind: "local",
owner: null,
size: null,
resources: null,
industryStockpile: null,
materialsStockpile: null,
industry: null,
population: null,
colonists: null,
production: null,
freeIndustry: null,
};
}
function fleet(
overrides: Partial<ReportLocalFleet> & Pick<ReportLocalFleet, "name" | "destination">,
): ReportLocalFleet {
return {
groupCount: 1,
origin: null,
range: null,
speed: 0,
state: "In_Orbit",
...overrides,
};
}
function makeReport(opts: {
planets?: ReportPlanet[];
fleets?: ReportLocalFleet[];
}): GameReport {
return {
turn: 1,
mapWidth: 1000,
mapHeight: 1000,
planetCount: opts.planets?.length ?? 0,
planets: opts.planets ?? [],
race: "Me",
localShipClass: [],
routes: [],
localPlayerDrive: 0,
localPlayerWeapons: 0,
localPlayerShields: 0,
localPlayerCargo: 0,
...EMPTY_SHIP_GROUPS,
localFleets: opts.fleets ?? [],
};
}
function mount(report: GameReport | null) {
const renderedReport = {
get report() {
return report;
},
};
const context = new Map<unknown, unknown>([
[RENDERED_REPORT_CONTEXT_KEY, renderedReport],
[SELECTION_CONTEXT_KEY, selection],
]);
return render(TableFleets, { context });
}
describe("fleets table", () => {
test("renders a loading placeholder before the report lands", () => {
const ui = mount(null);
expect(ui.getByTestId("fleets-loading")).toBeInTheDocument();
});
test("renders an empty placeholder when no fleets exist", () => {
const ui = mount(makeReport({ planets: [planet(1)] }));
expect(ui.getByTestId("fleets-empty")).toBeInTheDocument();
});
test("renders one row per fleet", () => {
const ui = mount(
makeReport({
planets: [planet(1), planet(2)],
fleets: [
fleet({ name: "Alpha", destination: 1 }),
fleet({
name: "Bravo",
destination: 2,
origin: 1,
range: 4,
state: "In_Space",
}),
],
}),
);
expect(ui.getAllByTestId("fleets-row")).toHaveLength(2);
});
test("planet dropdown filters by destination OR origin", async () => {
const ui = mount(
makeReport({
planets: [planet(1), planet(2), planet(3)],
fleets: [
fleet({ name: "Alpha", destination: 1 }),
fleet({
name: "Bravo",
destination: 3,
origin: 2,
range: 4,
state: "In_Space",
}),
],
}),
);
const sel = ui.getByTestId("fleets-filter-planet") as HTMLSelectElement;
await fireEvent.change(sel, { target: { value: "2" } });
const names = ui
.getAllByTestId("fleets-row")
.map((r) => r.getAttribute("data-name"));
expect(names).toEqual(["Bravo"]);
});
test("click on on-planet fleet focuses the destination planet", async () => {
const ui = mount(
makeReport({
planets: [planet(7)],
fleets: [fleet({ name: "Alpha", destination: 7 })],
}),
);
await fireEvent.click(ui.getByTestId("fleets-row"));
expect(selection.selected).toEqual({ kind: "planet", id: 7 });
expect(selection.consumePendingFocus()).toEqual({
kind: "planet",
id: 7,
});
expect(activeView.view).toBe("map");
});
test("click on in-space fleet centres camera point and leaves selection alone", async () => {
const ui = mount(
makeReport({
planets: [planet(1, 0, 0), planet(2, 100, 0)],
fleets: [
fleet({
name: "Bravo",
destination: 2,
origin: 1,
range: 25,
state: "In_Space",
}),
],
}),
);
expect(selection.selected).toBeNull();
await fireEvent.click(ui.getByTestId("fleets-row"));
expect(selection.selected).toBeNull();
// 25 world units away from dest (2 at x=100) toward origin (1 at x=0):
// dest + (range/total)*(origin-dest) = 100 + 0.25 * -100 = 75
expect(selection.consumePendingCenter()).toEqual({ x: 75, y: 0 });
expect(activeView.view).toBe("map");
});
});
+210
View File
@@ -0,0 +1,210 @@
// Vitest coverage for the F8-10 planets table active view.
// The component is mounted against a synthetic `RenderedReportSource`
// (kind discriminants set per case) and a real `SelectionStore`, so
// the click → focus contract is exercised end-to-end without needing
// the live map renderer.
import "@testing-library/jest-dom/vitest";
import { fireEvent, render } from "@testing-library/svelte";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { i18n } from "../src/lib/i18n/index.svelte";
import type { GameReport, ReportPlanet } from "../src/api/game-state";
import { RENDERED_REPORT_CONTEXT_KEY } from "../src/lib/rendered-report.svelte";
import {
SELECTION_CONTEXT_KEY,
SelectionStore,
} from "../src/lib/selection.svelte";
import { activeView } from "../src/lib/app-nav.svelte";
import { EMPTY_SHIP_GROUPS } from "./helpers/empty-ship-groups";
const pageMock = vi.hoisted(() => ({
url: new URL("http://localhost/games/g1/table/planets"),
params: { id: "g1" } as Record<string, string>,
}));
const gotoMock = vi.hoisted(() => vi.fn());
vi.mock("$app/state", () => ({
page: pageMock,
}));
vi.mock("$app/navigation", () => ({
goto: gotoMock,
pushState: vi.fn(),
replaceState: vi.fn(),
}));
import TablePlanets from "../src/lib/active-view/table-planets.svelte";
let selection: SelectionStore;
beforeEach(() => {
selection = new SelectionStore();
i18n.resetForTests("en");
pageMock.params = { id: "g1" };
gotoMock.mockClear();
activeView.reset();
});
afterEach(() => {
selection.dispose();
});
function planet(overrides: Partial<ReportPlanet> & { number: number }): ReportPlanet {
return {
name: `P${overrides.number}`,
x: 0,
y: 0,
kind: "uninhabited",
owner: null,
size: null,
resources: null,
industryStockpile: null,
materialsStockpile: null,
industry: null,
population: null,
colonists: null,
production: null,
freeIndustry: null,
...overrides,
};
}
function makeReport(planets: ReportPlanet[]): GameReport {
return {
turn: 1,
mapWidth: 1000,
mapHeight: 1000,
planetCount: planets.length,
planets,
race: "Me",
localShipClass: [],
routes: [],
localPlayerDrive: 0,
localPlayerWeapons: 0,
localPlayerShields: 0,
localPlayerCargo: 0,
...EMPTY_SHIP_GROUPS,
};
}
function mount(report: GameReport | null) {
const renderedReport = {
get report() {
return report;
},
};
const context = new Map<unknown, unknown>([
[RENDERED_REPORT_CONTEXT_KEY, renderedReport],
[SELECTION_CONTEXT_KEY, selection],
]);
return render(TablePlanets, { context });
}
describe("planets table", () => {
test("renders a loading placeholder before the report lands", () => {
const ui = mount(null);
expect(ui.getByTestId("planets-loading")).toBeInTheDocument();
});
test("renders an empty placeholder when the report has no planets", () => {
const ui = mount(makeReport([]));
expect(ui.getByTestId("planets-empty")).toBeInTheDocument();
});
test("renders one row per planet with kind classification", () => {
const ui = mount(
makeReport([
planet({ number: 1, name: "Earth", kind: "local" }),
planet({
number: 2,
name: "Vega",
kind: "other",
owner: "Klingon",
}),
planet({ number: 3, name: "Rock", kind: "uninhabited" }),
planet({ number: 4, name: "", kind: "unidentified" }),
]),
);
const rows = ui.getAllByTestId("planets-row");
expect(rows).toHaveLength(4);
expect(rows[0]).toHaveAttribute("data-kind", "local");
expect(rows[1]).toHaveAttribute("data-kind", "other");
});
test("kind checkboxes filter the visible rows independently", async () => {
const ui = mount(
makeReport([
planet({ number: 1, kind: "local" }),
planet({ number: 2, kind: "other", owner: "A" }),
planet({ number: 3, kind: "uninhabited" }),
planet({ number: 4, kind: "unidentified" }),
]),
);
await fireEvent.click(ui.getByTestId("planets-filter-own"));
let kinds = ui
.getAllByTestId("planets-row")
.map((r) => r.getAttribute("data-kind"));
expect(kinds).toEqual(["other", "uninhabited", "unidentified"]);
await fireEvent.click(ui.getByTestId("planets-filter-uninhabited"));
kinds = ui
.getAllByTestId("planets-row")
.map((r) => r.getAttribute("data-kind"));
expect(kinds).toEqual(["other", "unidentified"]);
});
test("owner dropdown narrows the foreign slice only", async () => {
const ui = mount(
makeReport([
planet({ number: 1, kind: "local" }),
planet({ number: 2, kind: "other", owner: "Klingon" }),
planet({ number: 3, kind: "other", owner: "Romulan" }),
planet({ number: 4, kind: "uninhabited" }),
]),
);
const select = ui.getByTestId(
"planets-filter-owner",
) as HTMLSelectElement;
await fireEvent.change(select, { target: { value: "Klingon" } });
const numbers = ui
.getAllByTestId("planets-row")
.map((r) => r.getAttribute("data-number"));
// own (1) + foreign Klingon (2) + uninhabited (4); Romulan dropped
expect(numbers).toEqual(["1", "2", "4"]);
});
test("clicking a row focuses the planet and switches the active view", async () => {
const ui = mount(
makeReport([
planet({ number: 7, kind: "local", name: "Earth", x: 12, y: 34 }),
]),
);
await fireEvent.click(ui.getByTestId("planets-row"));
expect(selection.selected).toEqual({ kind: "planet", id: 7 });
expect(selection.consumePendingFocus()).toEqual({
kind: "planet",
id: 7,
});
expect(activeView.view).toBe("map");
});
test("number column sorts ascending then descending", async () => {
const ui = mount(
makeReport([
planet({ number: 3, kind: "local" }),
planet({ number: 1, kind: "local" }),
planet({ number: 2, kind: "local" }),
]),
);
const numbers = ui
.getAllByTestId("planets-row")
.map((r) => r.getAttribute("data-number"));
expect(numbers).toEqual(["1", "2", "3"]);
await fireEvent.click(ui.getByTestId("planets-column-number"));
const reversed = ui
.getAllByTestId("planets-row")
.map((r) => r.getAttribute("data-number"));
expect(reversed).toEqual(["3", "2", "1"]);
});
});
+60 -2
View File
@@ -17,7 +17,11 @@ import {
} from "vitest";
import { i18n } from "../src/lib/i18n/index.svelte";
import type { GameReport, ShipClassSummary } from "../src/api/game-state";
import type {
GameReport,
ReportLocalShipGroup,
ShipClassSummary,
} from "../src/api/game-state";
import {
ORDER_DRAFT_CONTEXT_KEY,
OrderDraftStore,
@@ -89,7 +93,10 @@ function shipClass(
};
}
function makeReport(localShipClass: ShipClassSummary[]): GameReport {
function makeReport(
localShipClass: ShipClassSummary[],
localShipGroups: ReportLocalShipGroup[] = [],
): GameReport {
return {
turn: 1,
mapWidth: 1000,
@@ -104,6 +111,29 @@ function makeReport(localShipClass: ShipClassSummary[]): GameReport {
localPlayerShields: 0,
localPlayerCargo: 0,
...EMPTY_SHIP_GROUPS,
localShipGroups,
};
}
function shipGroup(
overrides: Partial<ReportLocalShipGroup> &
Pick<ReportLocalShipGroup, "class">,
): ReportLocalShipGroup {
return {
id: crypto.randomUUID(),
state: "In_Orbit",
fleet: null,
count: 1,
tech: { drive: 0, weapons: 0, shields: 0, cargo: 0 },
cargo: "NONE",
load: 0,
destination: 1,
origin: null,
range: null,
speed: 0,
mass: 0,
race: "Foo",
...overrides,
};
}
@@ -210,6 +240,34 @@ describe("ship-classes table", () => {
expect(cmd.name).toBe("Drone");
});
test("delete is disabled when a local ship group uses the class", async () => {
const ui = mountTable(
makeReport(
[shipClass({ name: "Cruiser" }), shipClass({ name: "Drone" })],
[
shipGroup({ class: "Cruiser" }),
shipGroup({ class: "Cruiser", count: 4 }),
],
),
);
const buttons = ui.getAllByTestId("ship-classes-delete");
const map = new Map(
buttons.map((b) => {
const row = b.closest('[data-testid="ship-classes-row"]');
return [row?.getAttribute("data-name") ?? "", b];
}),
);
const cruiserBtn = map.get("Cruiser") as HTMLButtonElement;
const droneBtn = map.get("Drone") as HTMLButtonElement;
expect(cruiserBtn).toBeDisabled();
expect(cruiserBtn).toHaveAttribute(
"title",
expect.stringContaining("2"),
);
expect(droneBtn).not.toBeDisabled();
expect(droneBtn).toHaveAttribute("title", "");
});
test("new button requests a fresh calculator design", async () => {
const ui = mountTable(makeReport([]));
const before = calculatorLoadRequest.token;
+312
View File
@@ -0,0 +1,312 @@
// Vitest coverage for the F8-10 ship-groups table active view.
// Mounts the component against a synthetic `RenderedReportSource`
// and a real `SelectionStore`; the click → focus contract (planet
// for on-orbit groups, ship-group ref for in-space) is exercised
// directly through the store.
import "@testing-library/jest-dom/vitest";
import { fireEvent, render } from "@testing-library/svelte";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { i18n } from "../src/lib/i18n/index.svelte";
import type {
GameReport,
ReportLocalShipGroup,
ReportOtherShipGroup,
ReportPlanet,
} from "../src/api/game-state";
import { RENDERED_REPORT_CONTEXT_KEY } from "../src/lib/rendered-report.svelte";
import {
SELECTION_CONTEXT_KEY,
SelectionStore,
} from "../src/lib/selection.svelte";
import { activeView } from "../src/lib/app-nav.svelte";
import { EMPTY_SHIP_GROUPS } from "./helpers/empty-ship-groups";
const pageMock = vi.hoisted(() => ({
url: new URL("http://localhost/games/g1/table/ship-groups"),
params: { id: "g1" } as Record<string, string>,
}));
const gotoMock = vi.hoisted(() => vi.fn());
vi.mock("$app/state", () => ({
page: pageMock,
}));
vi.mock("$app/navigation", () => ({
goto: gotoMock,
pushState: vi.fn(),
replaceState: vi.fn(),
}));
import TableShipGroups from "../src/lib/active-view/table-ship-groups.svelte";
let selection: SelectionStore;
beforeEach(() => {
selection = new SelectionStore();
i18n.resetForTests("en");
pageMock.params = { id: "g1" };
gotoMock.mockClear();
activeView.reset();
});
afterEach(() => {
selection.dispose();
});
function planet(num: number, name?: string): ReportPlanet {
return {
number: num,
name: name ?? `P${num}`,
x: 0,
y: 0,
kind: "local",
owner: null,
size: null,
resources: null,
industryStockpile: null,
materialsStockpile: null,
industry: null,
population: null,
colonists: null,
production: null,
freeIndustry: null,
};
}
function localGroup(
overrides: Partial<ReportLocalShipGroup> &
Pick<ReportLocalShipGroup, "id" | "class" | "destination">,
): ReportLocalShipGroup {
return {
state: "In_Orbit",
fleet: null,
count: 1,
tech: { drive: 0, weapons: 0, shields: 0, cargo: 0 },
cargo: "NONE",
load: 0,
origin: null,
range: null,
speed: 0,
mass: 0,
race: "Me",
...overrides,
};
}
function otherGroup(
overrides: Partial<ReportOtherShipGroup> &
Pick<ReportOtherShipGroup, "class" | "destination" | "race">,
): ReportOtherShipGroup {
return {
count: 1,
tech: { drive: 0, weapons: 0, shields: 0, cargo: 0 },
cargo: "NONE",
load: 0,
origin: null,
range: null,
speed: 0,
mass: 0,
...overrides,
};
}
function makeReport(opts: {
planets?: ReportPlanet[];
local?: ReportLocalShipGroup[];
other?: ReportOtherShipGroup[];
}): GameReport {
return {
turn: 1,
mapWidth: 1000,
mapHeight: 1000,
planetCount: opts.planets?.length ?? 0,
planets: opts.planets ?? [],
race: "Me",
localShipClass: [],
routes: [],
localPlayerDrive: 0,
localPlayerWeapons: 0,
localPlayerShields: 0,
localPlayerCargo: 0,
...EMPTY_SHIP_GROUPS,
localShipGroups: opts.local ?? [],
otherShipGroups: opts.other ?? [],
};
}
function mount(report: GameReport | null) {
const renderedReport = {
get report() {
return report;
},
};
const context = new Map<unknown, unknown>([
[RENDERED_REPORT_CONTEXT_KEY, renderedReport],
[SELECTION_CONTEXT_KEY, selection],
]);
return render(TableShipGroups, { context });
}
describe("ship-groups table", () => {
test("renders a loading placeholder before the report lands", () => {
const ui = mount(null);
expect(ui.getByTestId("ship-groups-loading")).toBeInTheDocument();
});
test("renders an empty placeholder when no groups are present", () => {
const ui = mount(makeReport({ planets: [planet(1)] }));
expect(ui.getByTestId("ship-groups-empty")).toBeInTheDocument();
});
test("renders local and foreign rows under one table", () => {
const ui = mount(
makeReport({
planets: [planet(1), planet(2)],
local: [localGroup({ id: "L1", class: "Cruiser", destination: 1 })],
other: [
otherGroup({ class: "Hunter", destination: 2, race: "Klingon" }),
],
}),
);
const rows = ui.getAllByTestId("ship-groups-row");
expect(rows).toHaveLength(2);
const owners = rows.map((r) => r.getAttribute("data-owner"));
expect(owners.sort()).toEqual(["foreign", "own"]);
});
test("owner checkboxes filter independently", async () => {
const ui = mount(
makeReport({
planets: [planet(1), planet(2)],
local: [localGroup({ id: "L1", class: "Cruiser", destination: 1 })],
other: [
otherGroup({ class: "Hunter", destination: 2, race: "Klingon" }),
],
}),
);
await fireEvent.click(ui.getByTestId("ship-groups-filter-foreign"));
const owners = ui
.getAllByTestId("ship-groups-row")
.map((r) => r.getAttribute("data-owner"));
expect(owners).toEqual(["own"]);
});
test("planet dropdown filters by destination OR origin", async () => {
const ui = mount(
makeReport({
planets: [planet(1), planet(2), planet(3)],
local: [
localGroup({ id: "L1", class: "C", destination: 1 }),
localGroup({
id: "L2",
class: "C",
destination: 3,
origin: 2,
range: 4,
state: "In_Space",
}),
localGroup({ id: "L3", class: "C", destination: 3 }),
],
}),
);
const sel = ui.getByTestId(
"ship-groups-filter-planet",
) as HTMLSelectElement;
await fireEvent.change(sel, { target: { value: "2" } });
// only L2 touches planet 2 (origin === 2)
const keys = ui
.getAllByTestId("ship-groups-row")
.map((r) => r.getAttribute("data-key"));
expect(keys).toEqual(["local:L2"]);
});
test("class dropdown filters by class name", async () => {
const ui = mount(
makeReport({
planets: [planet(1)],
local: [
localGroup({ id: "L1", class: "Cruiser", destination: 1 }),
localGroup({ id: "L2", class: "Drone", destination: 1 }),
],
}),
);
const sel = ui.getByTestId(
"ship-groups-filter-class",
) as HTMLSelectElement;
await fireEvent.change(sel, { target: { value: "Drone" } });
const keys = ui
.getAllByTestId("ship-groups-row")
.map((r) => r.getAttribute("data-key"));
expect(keys).toEqual(["local:L2"]);
});
test("click on on-planet group focuses the destination planet", async () => {
const ui = mount(
makeReport({
planets: [planet(7)],
local: [localGroup({ id: "L1", class: "Cruiser", destination: 7 })],
}),
);
await fireEvent.click(ui.getByTestId("ship-groups-row"));
expect(selection.selected).toEqual({ kind: "planet", id: 7 });
expect(selection.consumePendingFocus()).toEqual({
kind: "planet",
id: 7,
});
expect(activeView.view).toBe("map");
});
test("click on in-space local group focuses the ship-group ref", async () => {
const ui = mount(
makeReport({
planets: [planet(1), planet(2)],
local: [
localGroup({
id: "L1",
class: "Cruiser",
destination: 2,
origin: 1,
range: 3,
state: "In_Space",
}),
],
}),
);
await fireEvent.click(ui.getByTestId("ship-groups-row"));
expect(selection.selected).toEqual({
kind: "shipGroup",
ref: { variant: "local", id: "L1" },
});
expect(selection.consumePendingFocus()).toEqual({
kind: "shipGroup",
ref: { variant: "local", id: "L1" },
});
expect(activeView.view).toBe("map");
});
test("click on in-space foreign group focuses other variant by index", async () => {
const ui = mount(
makeReport({
planets: [planet(1), planet(2)],
other: [
otherGroup({
class: "Hunter",
destination: 2,
origin: 1,
range: 5,
race: "Klingon",
}),
],
}),
);
await fireEvent.click(ui.getByTestId("ship-groups-row"));
expect(selection.selected).toEqual({
kind: "shipGroup",
ref: { variant: "other", index: 0 },
});
expect(activeView.view).toBe("map");
});
});