ui/phase-17: ship-class CRUD without calc
Phase 17 lights up the ship-class table and designer active views, extends the order-draft pipeline with createShipClass and removeShipClass commands, and projects pending Save/Delete actions through applyOrderOverlay so the table reflects the player's intent before auto-sync lands. The plan is corrected in the same patch: per game/rules.txt, ship classes are designed once and cannot be edited — the engine has no Update command, so the UI exposes only Create + Delete. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
+49
-17
@@ -1947,35 +1947,67 @@ Decisions baked into Phase 16 (vs. the original stage description):
|
||||
|
||||
Status: pending.
|
||||
|
||||
Goal: list, view, and edit ship classes through a dedicated table view
|
||||
and a designer view; numeric calculations are stubbed pending Phase
|
||||
18.
|
||||
Goal: list, view, create, and delete ship classes through a
|
||||
dedicated table view and a designer view; numeric calculations are
|
||||
stubbed pending Phase 18.
|
||||
|
||||
Per `game/rules.txt`, ship classes are designed once and cannot be
|
||||
modified after creation — values are baked into existing ships at
|
||||
build time. The future "upgrade" command (Phase 19/20,
|
||||
`CommandShipGroupUpgrade`) raises an existing ship group's tech
|
||||
levels but does not edit the class blueprint. Phase 17 therefore
|
||||
exposes only Create and Delete; an "edit" affordance is
|
||||
deliberately absent and the designer renders an existing class
|
||||
read-only.
|
||||
|
||||
Artifacts:
|
||||
|
||||
- `ui/frontend/src/routes/games/[id]/table/ship-classes/+page.svelte`
|
||||
table of ship classes with sort and filter
|
||||
- `ui/frontend/src/routes/games/[id]/designer/ship-class/[id]/+page.svelte`
|
||||
designer form with all five fields (Drive, Armament, Weapons,
|
||||
Shields, Cargo) plus name; validation rules from [`rules.txt`](../game/rules.txt)
|
||||
(each field 0 or ≥1; armament integer; weapons and armament both
|
||||
zero or both nonzero)
|
||||
- `ui/frontend/src/lib/active-view/table-ship-classes.svelte`
|
||||
table of ship classes with sort and filter, plus per-row Delete
|
||||
affordance (the existing `routes/games/[id]/table/[entity]/+page.svelte`
|
||||
already wires this active view through the `[entity]` parameter,
|
||||
so no new route file lands).
|
||||
- `ui/frontend/src/lib/active-view/designer-ship-class.svelte`
|
||||
rewritten from the Phase 10 stub: empty form for the Create flow
|
||||
(name plus the five fields Drive, Armament, Weapons, Shields,
|
||||
Cargo) and read-only view + Delete affordance for an existing
|
||||
class. Validation rules from [`rules.txt`](../game/rules.txt) live
|
||||
in `lib/util/ship-class-validation.ts` (TS port of
|
||||
`pkg/calc/validator.go.ValidateShipTypeValues`): each of drive /
|
||||
weapons / shields / cargo is 0 or ≥ 1; armament is a non-negative
|
||||
integer; armament and weapons are both zero or both nonzero;
|
||||
not all five values may be zero. The existing
|
||||
`routes/games/[id]/designer/ship-class/[[classId]]/+page.svelte`
|
||||
is already wired and consumes the optional `classId` URL segment
|
||||
through `page.params`.
|
||||
- `ui/frontend/src/sync/order-types.ts` extends with
|
||||
`CreateShipClass` and `UpdateShipClass` command variants
|
||||
`CreateShipClassCommand` and `RemoveShipClassCommand` variants
|
||||
(mapped to `CommandShipClassCreate` and `CommandShipClassRemove`
|
||||
on the wire by `sync/submit.ts` and `sync/order-load.ts`).
|
||||
- `ui/frontend/src/api/game-state.ts` widens `ShipClassSummary`
|
||||
to carry the full attribute set; `applyOrderOverlay` projects
|
||||
pending Save / Delete actions onto `localShipClass` so the table
|
||||
reflects the player's intent before auto-sync lands.
|
||||
|
||||
Dependencies: Phase 14.
|
||||
|
||||
Acceptance criteria:
|
||||
|
||||
- the user can create, list, edit, and delete ship classes;
|
||||
- field validation matches [`rules.txt`](../game/rules.txt) constraints with disabled
|
||||
Submit + tooltip when invalid;
|
||||
- double-tapping a row in the ship-classes table opens its designer.
|
||||
- the user can create, list, view, and delete ship classes;
|
||||
- field validation matches [`rules.txt`](../game/rules.txt)
|
||||
constraints with disabled Submit + tooltip when invalid;
|
||||
- double-tapping a row in the ship-classes table opens its
|
||||
designer (read-only view of the existing class).
|
||||
|
||||
Targeted tests:
|
||||
|
||||
- Vitest component tests for designer field validation;
|
||||
- Playwright e2e: create a class, list it, edit it, delete it.
|
||||
- Vitest component tests for designer field validation
|
||||
(`tests/designer-ship-class.test.ts`) and the table
|
||||
(`tests/table-ship-classes.test.ts`); Vitest unit tests for the
|
||||
validator (`tests/ship-class-validation.test.ts`);
|
||||
- Playwright e2e (`tests/e2e/ship-classes.spec.ts`): create a
|
||||
class, list it, delete it; rejected-submit kept; field-validation
|
||||
kept (Save disabled with localised tooltip).
|
||||
|
||||
## Phase 18. Ship Classes — Calc Bridge
|
||||
|
||||
|
||||
+15
-8
@@ -20,23 +20,30 @@ separate dispatch component.
|
||||
|
||||
| URL | Active view component | Phase that fills it |
|
||||
| ------------------------------------- | ---------------------------------------------- | ----------------------- |
|
||||
| URL | Active view component | Phase that fills it |
|
||||
| ------------------------------------------ | ---------------------------------------------- | ----------------------- |
|
||||
| `/games/:id/map` | `lib/active-view/map.svelte` | Phase 11 |
|
||||
| `/games/:id/table/:entity` | `lib/active-view/table.svelte` | Phase 11 / 17 / 19 / 22 |
|
||||
| `/games/:id/report` | `lib/active-view/report.svelte` | Phase 23 |
|
||||
| `/games/:id/battle/:battleId?` | `lib/active-view/battle.svelte` | Phase 27 |
|
||||
| `/games/:id/mail` | `lib/active-view/mail.svelte` | Phase 28 |
|
||||
| `/games/:id/designer/ship-class/:id?` | `lib/active-view/designer-ship-class.svelte` | Phase 17 / 18 |
|
||||
| `/games/:id/designer/science/:id?` | `lib/active-view/designer-science.svelte` | Phase 21 |
|
||||
| `/games/:id/designer/ship-class/:classId?` | `lib/active-view/designer-ship-class.svelte` | Phase 17 (CRUD) / 18 (calc preview) |
|
||||
| `/games/:id/designer/science/:scienceId?` | `lib/active-view/designer-science.svelte` | Phase 21 |
|
||||
|
||||
`/games/:id` (no trailing view) redirects to `/games/:id/map`. The
|
||||
optional `:id?` segments on the designer routes match SvelteKit's
|
||||
`[[id]]` syntax — they accept both the new-draft and editing URLs;
|
||||
later phases read the param when wiring real content.
|
||||
optional `:classId?` / `:scienceId?` segments on the designer
|
||||
routes match SvelteKit's `[[classId]]` syntax — `/designer/ship-class`
|
||||
opens the empty new-class form, `/designer/ship-class/{name}`
|
||||
opens the read-only view of the named class with the Delete
|
||||
affordance. Phase 17 lights up the ship-class CRUD path; Phase 18
|
||||
adds the live `pkg/calc/`-backed preview pane on top.
|
||||
|
||||
The `entity` slug on the table route is kebab-case (`planets`,
|
||||
`ship-classes`, `ship-groups`, `fleets`, `sciences`, `races`); the
|
||||
table stub maps it to the matching `game.view.table.<snake>` i18n
|
||||
key.
|
||||
`ship-classes`, `ship-groups`, `fleets`, `sciences`, `races`).
|
||||
`table.svelte` is the active-view router: it dispatches by slug to
|
||||
the per-entity component (`ship-classes` → `table-ship-classes.svelte`
|
||||
in Phase 17; the others fall back to the Phase 10 stub copy until
|
||||
their respective phases land).
|
||||
|
||||
## Sidebar tools and state preservation
|
||||
|
||||
|
||||
@@ -16,10 +16,15 @@
|
||||
// report so the player sees their intent reflected immediately,
|
||||
// without waiting for the next turn cutoff.
|
||||
//
|
||||
// Phase 15 extends the projection with a minimal `localShipClass`
|
||||
// summary so the planet inspector's Build-Ship sub-picker has data
|
||||
// to render. Phase 17 (ship-class CRUD) widens `ShipClassSummary`
|
||||
// when the designer ships need the full attribute set.
|
||||
// Phase 15 added a name-only `localShipClass` projection so the
|
||||
// planet inspector's Build-Ship sub-picker had data to render.
|
||||
// Phase 17 widens `ShipClassSummary` to the full attribute set
|
||||
// (drive / armament / weapons / shields / cargo) so the ship-class
|
||||
// table and designer can render every documented field, and
|
||||
// extends `applyOrderOverlay` with the `createShipClass` /
|
||||
// `removeShipClass` variants — pending Save / Delete actions are
|
||||
// reflected in the table immediately, without waiting for the
|
||||
// auto-sync round-trip.
|
||||
|
||||
import { Builder, ByteBuffer } from "flatbuffers";
|
||||
|
||||
@@ -73,15 +78,22 @@ export interface ReportPlanet {
|
||||
}
|
||||
|
||||
/**
|
||||
* ShipClassSummary is the slim projection of `report.ShipClass` the
|
||||
* planet inspector's Build-Ship sub-picker needs in Phase 15. Only
|
||||
* the human-visible `name` is carried — the engine command shape
|
||||
* (`CommandPlanetProduce.subject`) takes the class name, not its
|
||||
* underlying tech values. Phase 17 widens this type when the ship
|
||||
* designer needs the full attribute set.
|
||||
* ShipClassSummary is the projection of `report.ShipClass` the
|
||||
* ship-class table and designer render. Phase 15 carried just the
|
||||
* `name` for the Build-Ship sub-picker; Phase 17 added the five
|
||||
* tech-derived numbers so the table can sort / filter on them and
|
||||
* the designer can populate read-only previews. The numeric ranges
|
||||
* mirror `pkg/calc/validator.go.ValidateShipTypeValues` exactly:
|
||||
* each of `drive`, `weapons`, `shields`, `cargo` is either zero or
|
||||
* ≥ 1, and `armament` is a non-negative integer.
|
||||
*/
|
||||
export interface ShipClassSummary {
|
||||
name: string;
|
||||
drive: number;
|
||||
armament: number;
|
||||
weapons: number;
|
||||
shields: number;
|
||||
cargo: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -266,7 +278,14 @@ function decodeReport(report: Report): GameReport {
|
||||
for (let i = 0; i < report.localShipClassLength(); i++) {
|
||||
const sc = report.localShipClass(i);
|
||||
if (sc === null) continue;
|
||||
localShipClass.push({ name: sc.name() ?? "" });
|
||||
localShipClass.push({
|
||||
name: sc.name() ?? "",
|
||||
drive: sc.drive(),
|
||||
armament: Number(sc.armament()),
|
||||
weapons: sc.weapons(),
|
||||
shields: sc.shields(),
|
||||
cargo: sc.cargo(),
|
||||
});
|
||||
}
|
||||
|
||||
const raceName = report.race() ?? "";
|
||||
@@ -380,11 +399,12 @@ export function uuidToHiLo(value: string): [bigint, bigint] {
|
||||
* applyOrderOverlay returns a copy of `report` with every locally-
|
||||
* valid or still-in-flight or applied command from `commands`
|
||||
* projected on top. Phase 14 introduced the overlay for
|
||||
* `planetRename`; Phase 15 extends it to `setProductionType` so the
|
||||
* inspector segment / map label reflect the chosen production target
|
||||
* before the engine confirms it. Other variants pass through. The
|
||||
* function is pure: callers re-derive the overlay whenever the draft
|
||||
* or the report change.
|
||||
* `planetRename`; Phase 15 extended it to `setProductionType`;
|
||||
* Phase 16 to `setCargoRoute` / `removeCargoRoute`; Phase 17 to
|
||||
* `createShipClass` / `removeShipClass` so the ship-class table
|
||||
* shows pending Save / Delete actions immediately. Other variants
|
||||
* pass through. The function is pure: callers re-derive the overlay
|
||||
* whenever the draft or the report change.
|
||||
*
|
||||
* `statuses` maps command id → status. Entries with `valid`,
|
||||
* `submitting`, or `applied` participate in the overlay — together
|
||||
@@ -402,6 +422,7 @@ export function applyOrderOverlay(
|
||||
if (commands.length === 0) return report;
|
||||
let mutatedPlanets: ReportPlanet[] | null = null;
|
||||
let mutatedRoutes: ReportRoute[] | null = null;
|
||||
let mutatedShipClass: ShipClassSummary[] | null = null;
|
||||
for (const cmd of commands) {
|
||||
const status = statuses[cmd.id];
|
||||
if (
|
||||
@@ -456,12 +477,48 @@ export function applyOrderOverlay(
|
||||
deleteRouteEntry(mutatedRoutes, cmd.sourcePlanetNumber, cmd.loadType);
|
||||
continue;
|
||||
}
|
||||
if (cmd.kind === "createShipClass") {
|
||||
if (mutatedShipClass === null) {
|
||||
mutatedShipClass = [...report.localShipClass];
|
||||
}
|
||||
// Skip duplicates: the engine refuses them server-side and
|
||||
// the designer's local validator prevents them client-side,
|
||||
// but a stale draft could still carry a row whose name now
|
||||
// collides with the server snapshot. Keeping the projection
|
||||
// unique avoids two rows in the table for the same name.
|
||||
if (mutatedShipClass.some((cls) => cls.name === cmd.name)) continue;
|
||||
mutatedShipClass.push({
|
||||
name: cmd.name,
|
||||
drive: cmd.drive,
|
||||
armament: cmd.armament,
|
||||
weapons: cmd.weapons,
|
||||
shields: cmd.shields,
|
||||
cargo: cmd.cargo,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (cmd.kind === "removeShipClass") {
|
||||
if (mutatedShipClass === null) {
|
||||
mutatedShipClass = [...report.localShipClass];
|
||||
}
|
||||
const idx = mutatedShipClass.findIndex((cls) => cls.name === cmd.name);
|
||||
if (idx < 0) continue;
|
||||
mutatedShipClass.splice(idx, 1);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (
|
||||
mutatedPlanets === null &&
|
||||
mutatedRoutes === null &&
|
||||
mutatedShipClass === null
|
||||
) {
|
||||
return report;
|
||||
}
|
||||
if (mutatedPlanets === null && mutatedRoutes === null) return report;
|
||||
return {
|
||||
...report,
|
||||
planets: mutatedPlanets ?? report.planets,
|
||||
routes: mutatedRoutes ?? report.routes,
|
||||
localShipClass: mutatedShipClass ?? report.localShipClass,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,28 +1,434 @@
|
||||
<!--
|
||||
Phase 10 stub for the ship-class designer active view. Phase 17 wires
|
||||
the CRUD list and Phase 18 the calc bridge. The optional `classId`
|
||||
URL segment is accepted but ignored at this point.
|
||||
Phase 17 ship-class designer. Two modes driven by the optional
|
||||
`classId` URL segment:
|
||||
|
||||
- **new (no classId)** — empty form with five numeric fields
|
||||
plus name. Save is disabled until `validateShipClass` returns
|
||||
`ok`; the localised tooltip mirrors `validateEntityName`'s
|
||||
invalid-reason messages and the value-rule mirrors of
|
||||
`pkg/calc/validator.go.ValidateShipTypeValues`. Save adds a
|
||||
`createShipClass` to the local order draft and returns to the
|
||||
table.
|
||||
- **view (classId set)** — read-only render of the matching row
|
||||
from the optimistic overlay. Ship classes are designed once
|
||||
and cannot be modified after creation (per
|
||||
`game/rules.txt`); the in-game upgrade story lives elsewhere
|
||||
(`CommandShipGroupUpgrade`, Phase 19/20). The view exposes a
|
||||
Delete affordance (engine-side checks ensure the class is not
|
||||
referenced by active production / ship groups) and a Back
|
||||
button.
|
||||
|
||||
Phase 18 wires `pkg/calc/` into the form for live mass / speed /
|
||||
range / cargo previews; the markup keeps a placeholder slot near
|
||||
the value fields so the diff in Phase 18 stays minimal.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { i18n } from "$lib/i18n/index.svelte";
|
||||
import { getContext, tick } from "svelte";
|
||||
import { goto } from "$app/navigation";
|
||||
import { page } from "$app/state";
|
||||
|
||||
import type { ShipClassSummary } from "../../api/game-state";
|
||||
import { i18n, type TranslationKey } from "$lib/i18n/index.svelte";
|
||||
import {
|
||||
RENDERED_REPORT_CONTEXT_KEY,
|
||||
type RenderedReportSource,
|
||||
} from "$lib/rendered-report.svelte";
|
||||
import {
|
||||
ORDER_DRAFT_CONTEXT_KEY,
|
||||
OrderDraftStore,
|
||||
} from "../../sync/order-draft.svelte";
|
||||
import {
|
||||
validateShipClass,
|
||||
type ShipClassInvalidReason,
|
||||
} from "$lib/util/ship-class-validation";
|
||||
|
||||
const rendered = getContext<RenderedReportSource | undefined>(
|
||||
RENDERED_REPORT_CONTEXT_KEY,
|
||||
);
|
||||
const draft = getContext<OrderDraftStore | undefined>(
|
||||
ORDER_DRAFT_CONTEXT_KEY,
|
||||
);
|
||||
|
||||
const gameId = $derived(page.params.id ?? "");
|
||||
const classId = $derived(page.params.classId ?? "");
|
||||
const isViewMode = $derived(classId !== "");
|
||||
|
||||
const localShipClass = $derived<ShipClassSummary[]>(
|
||||
rendered?.report?.localShipClass ?? [],
|
||||
);
|
||||
const existingNames = $derived(localShipClass.map((cls) => cls.name));
|
||||
const viewing = $derived(
|
||||
isViewMode
|
||||
? localShipClass.find((cls) => cls.name === classId) ?? null
|
||||
: null,
|
||||
);
|
||||
|
||||
let name = $state("");
|
||||
let drive = $state(0);
|
||||
let armament = $state(0);
|
||||
let weapons = $state(0);
|
||||
let shields = $state(0);
|
||||
let cargo = $state(0);
|
||||
let nameInputEl: HTMLInputElement | null = $state(null);
|
||||
|
||||
const invalidReasonKeyMap: Record<ShipClassInvalidReason, TranslationKey> = {
|
||||
empty: "game.designer.ship_class.invalid.empty",
|
||||
too_long: "game.designer.ship_class.invalid.too_long",
|
||||
starts_with_special: "game.designer.ship_class.invalid.starts_with_special",
|
||||
ends_with_special: "game.designer.ship_class.invalid.ends_with_special",
|
||||
consecutive_specials:
|
||||
"game.designer.ship_class.invalid.consecutive_specials",
|
||||
whitespace: "game.designer.ship_class.invalid.whitespace",
|
||||
disallowed_character:
|
||||
"game.designer.ship_class.invalid.disallowed_character",
|
||||
duplicate_name: "game.designer.ship_class.invalid.duplicate_name",
|
||||
drive_value: "game.designer.ship_class.invalid.drive_value",
|
||||
armament_value: "game.designer.ship_class.invalid.armament_value",
|
||||
armament_not_integer:
|
||||
"game.designer.ship_class.invalid.armament_not_integer",
|
||||
weapons_value: "game.designer.ship_class.invalid.weapons_value",
|
||||
shields_value: "game.designer.ship_class.invalid.shields_value",
|
||||
cargo_value: "game.designer.ship_class.invalid.cargo_value",
|
||||
armament_weapons_pair:
|
||||
"game.designer.ship_class.invalid.armament_weapons_pair",
|
||||
all_zero: "game.designer.ship_class.invalid.all_zero",
|
||||
};
|
||||
|
||||
const validation = $derived(
|
||||
validateShipClass(
|
||||
{ name, drive, armament, weapons, shields, cargo },
|
||||
{ existingNames },
|
||||
),
|
||||
);
|
||||
const invalidMessage = $derived(
|
||||
validation.ok ? "" : i18n.t(invalidReasonKeyMap[validation.reason]),
|
||||
);
|
||||
const canSave = $derived(validation.ok && draft !== undefined);
|
||||
|
||||
$effect(() => {
|
||||
if (!isViewMode) {
|
||||
void tick().then(() => nameInputEl?.focus());
|
||||
}
|
||||
});
|
||||
|
||||
function formatNumber(value: number): string {
|
||||
return value.toLocaleString(undefined, { maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
function backToTable(): void {
|
||||
void goto(`/games/${gameId}/table/ship-classes`);
|
||||
}
|
||||
|
||||
async function save(): Promise<void> {
|
||||
if (!validation.ok || draft === undefined) return;
|
||||
await draft.add({
|
||||
kind: "createShipClass",
|
||||
id: crypto.randomUUID(),
|
||||
name: validation.value.name,
|
||||
drive: validation.value.drive,
|
||||
armament: validation.value.armament,
|
||||
weapons: validation.value.weapons,
|
||||
shields: validation.value.shields,
|
||||
cargo: validation.value.cargo,
|
||||
});
|
||||
backToTable();
|
||||
}
|
||||
|
||||
async function deleteThis(): Promise<void> {
|
||||
if (viewing === null || draft === undefined) return;
|
||||
await draft.add({
|
||||
kind: "removeShipClass",
|
||||
id: crypto.randomUUID(),
|
||||
name: viewing.name,
|
||||
});
|
||||
backToTable();
|
||||
}
|
||||
</script>
|
||||
|
||||
<section class="active-view" data-testid="active-view-designer-ship-class">
|
||||
<section
|
||||
class="active-view"
|
||||
data-testid="active-view-designer-ship-class"
|
||||
data-mode={isViewMode ? "view" : "new"}
|
||||
>
|
||||
{#if isViewMode}
|
||||
{#if viewing === null}
|
||||
<h2>{i18n.t("game.view.designer.ship_class")}</h2>
|
||||
<p>{i18n.t("game.shell.coming_soon")}</p>
|
||||
<p class="not-found" data-testid="designer-ship-class-not-found">
|
||||
{i18n.t("game.designer.ship_class.not_found", { name: classId })}
|
||||
</p>
|
||||
<div class="actions">
|
||||
<button
|
||||
type="button"
|
||||
data-testid="designer-ship-class-back"
|
||||
onclick={backToTable}
|
||||
>
|
||||
{i18n.t("game.designer.ship_class.action.back")}
|
||||
</button>
|
||||
</div>
|
||||
{:else}
|
||||
<h2 data-testid="designer-ship-class-title">
|
||||
{i18n.t("game.designer.ship_class.title.view", { name: viewing.name })}
|
||||
</h2>
|
||||
<p class="notice" data-testid="designer-ship-class-notice">
|
||||
{i18n.t("game.designer.ship_class.read_only_notice")}
|
||||
</p>
|
||||
<dl class="fields">
|
||||
<div class="field">
|
||||
<dt>{i18n.t("game.designer.ship_class.field.name")}</dt>
|
||||
<dd data-testid="designer-ship-class-view-name">{viewing.name}</dd>
|
||||
</div>
|
||||
<div class="field">
|
||||
<dt>{i18n.t("game.designer.ship_class.field.drive")}</dt>
|
||||
<dd data-testid="designer-ship-class-view-drive">
|
||||
{formatNumber(viewing.drive)}
|
||||
</dd>
|
||||
</div>
|
||||
<div class="field">
|
||||
<dt>{i18n.t("game.designer.ship_class.field.armament")}</dt>
|
||||
<dd data-testid="designer-ship-class-view-armament">
|
||||
{viewing.armament}
|
||||
</dd>
|
||||
</div>
|
||||
<div class="field">
|
||||
<dt>{i18n.t("game.designer.ship_class.field.weapons")}</dt>
|
||||
<dd data-testid="designer-ship-class-view-weapons">
|
||||
{formatNumber(viewing.weapons)}
|
||||
</dd>
|
||||
</div>
|
||||
<div class="field">
|
||||
<dt>{i18n.t("game.designer.ship_class.field.shields")}</dt>
|
||||
<dd data-testid="designer-ship-class-view-shields">
|
||||
{formatNumber(viewing.shields)}
|
||||
</dd>
|
||||
</div>
|
||||
<div class="field">
|
||||
<dt>{i18n.t("game.designer.ship_class.field.cargo")}</dt>
|
||||
<dd data-testid="designer-ship-class-view-cargo">
|
||||
{formatNumber(viewing.cargo)}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<div class="actions">
|
||||
<button
|
||||
type="button"
|
||||
class="back"
|
||||
data-testid="designer-ship-class-back"
|
||||
onclick={backToTable}
|
||||
>
|
||||
{i18n.t("game.designer.ship_class.action.back")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="delete"
|
||||
data-testid="designer-ship-class-delete"
|
||||
disabled={draft === undefined}
|
||||
onclick={() => void deleteThis()}
|
||||
>
|
||||
{i18n.t("game.designer.ship_class.action.delete")}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
{:else}
|
||||
<h2 data-testid="designer-ship-class-title">
|
||||
{i18n.t("game.designer.ship_class.title.new")}
|
||||
</h2>
|
||||
<p class="hint" data-testid="designer-ship-class-hint">
|
||||
{i18n.t("game.designer.ship_class.hint.values")}
|
||||
</p>
|
||||
<form
|
||||
class="form"
|
||||
data-testid="designer-ship-class-form"
|
||||
onsubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void save();
|
||||
}}
|
||||
>
|
||||
<label class="row">
|
||||
<span>{i18n.t("game.designer.ship_class.field.name")}</span>
|
||||
<input
|
||||
type="text"
|
||||
bind:this={nameInputEl}
|
||||
bind:value={name}
|
||||
data-testid="designer-ship-class-input-name"
|
||||
aria-invalid={validation.ok ? "false" : "true"}
|
||||
/>
|
||||
</label>
|
||||
<label class="row">
|
||||
<span>{i18n.t("game.designer.ship_class.field.drive")}</span>
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
bind:value={drive}
|
||||
data-testid="designer-ship-class-input-drive"
|
||||
/>
|
||||
</label>
|
||||
<label class="row">
|
||||
<span>{i18n.t("game.designer.ship_class.field.armament")}</span>
|
||||
<input
|
||||
type="number"
|
||||
step="1"
|
||||
min="0"
|
||||
bind:value={armament}
|
||||
data-testid="designer-ship-class-input-armament"
|
||||
/>
|
||||
</label>
|
||||
<label class="row">
|
||||
<span>{i18n.t("game.designer.ship_class.field.weapons")}</span>
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
bind:value={weapons}
|
||||
data-testid="designer-ship-class-input-weapons"
|
||||
/>
|
||||
</label>
|
||||
<label class="row">
|
||||
<span>{i18n.t("game.designer.ship_class.field.shields")}</span>
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
bind:value={shields}
|
||||
data-testid="designer-ship-class-input-shields"
|
||||
/>
|
||||
</label>
|
||||
<label class="row">
|
||||
<span>{i18n.t("game.designer.ship_class.field.cargo")}</span>
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
bind:value={cargo}
|
||||
data-testid="designer-ship-class-input-cargo"
|
||||
/>
|
||||
</label>
|
||||
{#if !validation.ok}
|
||||
<p class="error" data-testid="designer-ship-class-error">
|
||||
{invalidMessage}
|
||||
</p>
|
||||
{/if}
|
||||
<div class="actions">
|
||||
<button
|
||||
type="button"
|
||||
class="cancel"
|
||||
data-testid="designer-ship-class-cancel"
|
||||
onclick={backToTable}
|
||||
>
|
||||
{i18n.t("game.designer.ship_class.action.cancel")}
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
class="save"
|
||||
data-testid="designer-ship-class-save"
|
||||
disabled={!canSave}
|
||||
title={canSave ? "" : invalidMessage}
|
||||
>
|
||||
{i18n.t("game.designer.ship_class.action.save")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.active-view {
|
||||
padding: 1.5rem;
|
||||
font-family: system-ui, sans-serif;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.85rem;
|
||||
}
|
||||
.active-view h2 {
|
||||
margin: 0 0 0.5rem;
|
||||
margin: 0;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
.active-view p {
|
||||
.notice,
|
||||
.hint,
|
||||
.not-found {
|
||||
margin: 0;
|
||||
color: #555;
|
||||
color: #888;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.55rem;
|
||||
max-width: 30rem;
|
||||
}
|
||||
.row {
|
||||
display: grid;
|
||||
grid-template-columns: 8rem 1fr;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
.row span {
|
||||
color: #aab;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.row input {
|
||||
font: inherit;
|
||||
padding: 0.3rem 0.5rem;
|
||||
background: #0a0e1a;
|
||||
color: #e8eaf6;
|
||||
border: 1px solid #2a3150;
|
||||
border-radius: 3px;
|
||||
}
|
||||
.row input[aria-invalid="true"] {
|
||||
border-color: #d97a7a;
|
||||
}
|
||||
.error {
|
||||
margin: 0;
|
||||
font-size: 0.8rem;
|
||||
color: #d97a7a;
|
||||
}
|
||||
.fields {
|
||||
margin: 0;
|
||||
display: grid;
|
||||
grid-template-columns: max-content 1fr;
|
||||
row-gap: 0.25rem;
|
||||
column-gap: 0.75rem;
|
||||
max-width: 30rem;
|
||||
}
|
||||
.field {
|
||||
display: contents;
|
||||
}
|
||||
.field dt {
|
||||
color: #aab;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.field dd {
|
||||
margin: 0;
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.actions button {
|
||||
font: inherit;
|
||||
font-size: 0.9rem;
|
||||
padding: 0.3rem 0.7rem;
|
||||
background: transparent;
|
||||
color: #aab;
|
||||
border: 1px solid #2a3150;
|
||||
border-radius: 3px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.actions button:not(:disabled):hover {
|
||||
color: #e8eaf6;
|
||||
border-color: #6d8cff;
|
||||
}
|
||||
.actions button:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.5;
|
||||
}
|
||||
.actions .delete {
|
||||
color: #d97a7a;
|
||||
}
|
||||
.actions .delete:not(:disabled):hover {
|
||||
border-color: #d97a7a;
|
||||
color: #f0a0a0;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
<!--
|
||||
Phase 17 ship-classes table. Renders the player's designed ship
|
||||
classes with sort, filter, double-tap-to-open-designer, and a
|
||||
per-row Delete action. Source data is the optimistic overlay
|
||||
(`RenderedReportSource.report.localShipClass`) so a freshly
|
||||
queued `createShipClass` shows up immediately and a freshly
|
||||
queued `removeShipClass` disappears immediately — both before the
|
||||
auto-sync round-trip lands.
|
||||
|
||||
The component sits inside the active-view slot owned by
|
||||
`routes/games/[id]/+layout.svelte`, so it inherits the per-game
|
||||
`OrderDraftStore` and `RenderedReportSource` through context. No
|
||||
data fetching is performed here — the layout is responsible.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { getContext } from "svelte";
|
||||
import { goto } from "$app/navigation";
|
||||
import { page } from "$app/state";
|
||||
|
||||
import type { ShipClassSummary } from "../../api/game-state";
|
||||
import { i18n, type TranslationKey } from "$lib/i18n/index.svelte";
|
||||
import {
|
||||
RENDERED_REPORT_CONTEXT_KEY,
|
||||
type RenderedReportSource,
|
||||
} from "$lib/rendered-report.svelte";
|
||||
import {
|
||||
ORDER_DRAFT_CONTEXT_KEY,
|
||||
OrderDraftStore,
|
||||
} from "../../sync/order-draft.svelte";
|
||||
|
||||
type SortColumn =
|
||||
| "name"
|
||||
| "drive"
|
||||
| "armament"
|
||||
| "weapons"
|
||||
| "shields"
|
||||
| "cargo";
|
||||
type SortDirection = "asc" | "desc";
|
||||
|
||||
const COLUMN_LABELS: Record<SortColumn, TranslationKey> = {
|
||||
name: "game.table.ship_classes.column.name",
|
||||
drive: "game.table.ship_classes.column.drive",
|
||||
armament: "game.table.ship_classes.column.armament",
|
||||
weapons: "game.table.ship_classes.column.weapons",
|
||||
shields: "game.table.ship_classes.column.shields",
|
||||
cargo: "game.table.ship_classes.column.cargo",
|
||||
};
|
||||
|
||||
const COLUMNS: readonly SortColumn[] = [
|
||||
"name",
|
||||
"drive",
|
||||
"armament",
|
||||
"weapons",
|
||||
"shields",
|
||||
"cargo",
|
||||
];
|
||||
|
||||
const rendered = getContext<RenderedReportSource | undefined>(
|
||||
RENDERED_REPORT_CONTEXT_KEY,
|
||||
);
|
||||
const draft = getContext<OrderDraftStore | undefined>(
|
||||
ORDER_DRAFT_CONTEXT_KEY,
|
||||
);
|
||||
|
||||
const gameId = $derived(page.params.id ?? "");
|
||||
|
||||
let sortColumn: SortColumn = $state("name");
|
||||
let sortDirection: SortDirection = $state("asc");
|
||||
let filter: string = $state("");
|
||||
|
||||
const localShipClass = $derived<ShipClassSummary[]>(
|
||||
rendered?.report?.localShipClass ?? [],
|
||||
);
|
||||
const reportLoaded = $derived(rendered?.report !== null && rendered?.report !== undefined);
|
||||
|
||||
const filtered = $derived.by(() => {
|
||||
const needle = filter.trim().toLowerCase();
|
||||
if (needle === "") return localShipClass;
|
||||
return localShipClass.filter((cls) =>
|
||||
cls.name.toLowerCase().includes(needle),
|
||||
);
|
||||
});
|
||||
|
||||
const sorted = $derived.by(() => {
|
||||
const list = [...filtered];
|
||||
const dir = sortDirection === "asc" ? 1 : -1;
|
||||
list.sort((a, b) => {
|
||||
if (sortColumn === "name") {
|
||||
return a.name.localeCompare(b.name) * dir;
|
||||
}
|
||||
return (a[sortColumn] - b[sortColumn]) * dir;
|
||||
});
|
||||
return list;
|
||||
});
|
||||
|
||||
function toggleSort(column: SortColumn): void {
|
||||
if (sortColumn === column) {
|
||||
sortDirection = sortDirection === "asc" ? "desc" : "asc";
|
||||
return;
|
||||
}
|
||||
sortColumn = column;
|
||||
sortDirection = "asc";
|
||||
}
|
||||
|
||||
function ariaSort(column: SortColumn): "ascending" | "descending" | "none" {
|
||||
if (sortColumn !== column) return "none";
|
||||
return sortDirection === "asc" ? "ascending" : "descending";
|
||||
}
|
||||
|
||||
function formatNumber(value: number): string {
|
||||
return value.toLocaleString(undefined, { maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
function openDesigner(name: string): void {
|
||||
void goto(
|
||||
`/games/${gameId}/designer/ship-class/${encodeURIComponent(name)}`,
|
||||
);
|
||||
}
|
||||
|
||||
function newShipClass(): void {
|
||||
void goto(`/games/${gameId}/designer/ship-class`);
|
||||
}
|
||||
|
||||
async function deleteShipClass(name: string): Promise<void> {
|
||||
if (draft === undefined) return;
|
||||
await draft.add({
|
||||
kind: "removeShipClass",
|
||||
id: crypto.randomUUID(),
|
||||
name,
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<section
|
||||
class="active-view"
|
||||
data-testid="active-view-table"
|
||||
data-entity="ship-classes"
|
||||
>
|
||||
<header>
|
||||
<h2>{i18n.t("game.table.ship_classes.title")}</h2>
|
||||
<div class="controls">
|
||||
<input
|
||||
type="search"
|
||||
class="filter"
|
||||
data-testid="ship-classes-filter"
|
||||
placeholder={i18n.t("game.table.ship_classes.filter.placeholder")}
|
||||
bind:value={filter}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="new"
|
||||
data-testid="ship-classes-new"
|
||||
onclick={newShipClass}
|
||||
>
|
||||
{i18n.t("game.table.ship_classes.action.new")}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{#if !reportLoaded}
|
||||
<p class="status" data-testid="ship-classes-loading">
|
||||
{i18n.t("game.table.ship_classes.loading")}
|
||||
</p>
|
||||
{:else if localShipClass.length === 0}
|
||||
<p class="status" data-testid="ship-classes-empty">
|
||||
{i18n.t("game.table.ship_classes.empty")}
|
||||
</p>
|
||||
{:else}
|
||||
<table class="grid" data-testid="ship-classes-table">
|
||||
<thead>
|
||||
<tr>
|
||||
{#each COLUMNS as column (column)}
|
||||
<th aria-sort={ariaSort(column)}>
|
||||
<button
|
||||
type="button"
|
||||
class="sort"
|
||||
data-testid="ship-classes-column-{column}"
|
||||
onclick={() => toggleSort(column)}
|
||||
>
|
||||
{i18n.t(COLUMN_LABELS[column])}
|
||||
{#if sortColumn === column}
|
||||
<span class="sort-indicator" aria-hidden="true">
|
||||
{sortDirection === "asc" ? "▲" : "▼"}
|
||||
</span>
|
||||
{/if}
|
||||
</button>
|
||||
</th>
|
||||
{/each}
|
||||
<th>{i18n.t("game.table.ship_classes.column.actions")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{#each sorted as cls (cls.name)}
|
||||
<tr
|
||||
data-testid="ship-classes-row"
|
||||
data-name={cls.name}
|
||||
ondblclick={() => openDesigner(cls.name)}
|
||||
>
|
||||
<td data-testid="ship-classes-cell-name">{cls.name}</td>
|
||||
<td data-testid="ship-classes-cell-drive">{formatNumber(cls.drive)}</td>
|
||||
<td data-testid="ship-classes-cell-armament">{cls.armament}</td>
|
||||
<td data-testid="ship-classes-cell-weapons">{formatNumber(cls.weapons)}</td>
|
||||
<td data-testid="ship-classes-cell-shields">{formatNumber(cls.shields)}</td>
|
||||
<td data-testid="ship-classes-cell-cargo">{formatNumber(cls.cargo)}</td>
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
class="delete"
|
||||
data-testid="ship-classes-delete"
|
||||
onclick={() => void deleteShipClass(cls.name)}
|
||||
>
|
||||
{i18n.t("game.table.ship_classes.action.delete")}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.active-view {
|
||||
padding: 1.5rem;
|
||||
font-family: system-ui, sans-serif;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
header {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
header h2 {
|
||||
margin: 0;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
.controls {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.filter {
|
||||
font: inherit;
|
||||
padding: 0.3rem 0.5rem;
|
||||
background: #0a0e1a;
|
||||
color: #e8eaf6;
|
||||
border: 1px solid #2a3150;
|
||||
border-radius: 3px;
|
||||
flex: 1 1 12rem;
|
||||
min-width: 8rem;
|
||||
}
|
||||
.new {
|
||||
font: inherit;
|
||||
font-size: 0.9rem;
|
||||
padding: 0.3rem 0.7rem;
|
||||
background: transparent;
|
||||
color: #aab;
|
||||
border: 1px solid #2a3150;
|
||||
border-radius: 3px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.new:hover {
|
||||
color: #e8eaf6;
|
||||
border-color: #6d8cff;
|
||||
}
|
||||
.status {
|
||||
margin: 0;
|
||||
color: #888;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
.grid {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.grid th,
|
||||
.grid td {
|
||||
padding: 0.4rem 0.6rem;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #1c2240;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
.grid th {
|
||||
color: #aab;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.grid tbody tr {
|
||||
cursor: pointer;
|
||||
}
|
||||
.grid tbody tr:hover {
|
||||
background: #11172a;
|
||||
}
|
||||
.sort {
|
||||
font: inherit;
|
||||
font-size: inherit;
|
||||
text-transform: inherit;
|
||||
letter-spacing: inherit;
|
||||
color: inherit;
|
||||
background: transparent;
|
||||
border: none;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
display: inline-flex;
|
||||
gap: 0.3rem;
|
||||
align-items: baseline;
|
||||
}
|
||||
.sort-indicator {
|
||||
font-size: 0.7em;
|
||||
}
|
||||
.delete {
|
||||
font: inherit;
|
||||
font-size: 0.85rem;
|
||||
padding: 0.15rem 0.5rem;
|
||||
background: transparent;
|
||||
color: #d97a7a;
|
||||
border: 1px solid #2a3150;
|
||||
border-radius: 3px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.delete:hover {
|
||||
border-color: #d97a7a;
|
||||
}
|
||||
</style>
|
||||
@@ -1,11 +1,15 @@
|
||||
<!--
|
||||
Phase 10 stub for the entity-table active view. Phase 11+ wires real
|
||||
list data per entity (planets in Phase 11, ship-classes in Phase 17,
|
||||
etc.). Until then, the stub renders the localised entity title plus a
|
||||
`coming soon` body so navigation can be exercised end-to-end.
|
||||
Active-view router for the per-entity tables. Phase 17 lights up
|
||||
the ship-classes table; the other slugs (planets, ship-groups,
|
||||
fleets, sciences, races) keep the Phase 10 stub copy until their
|
||||
respective phases land. The wrapper preserves
|
||||
`data-testid="active-view-table"` and `data-entity={entity}` for
|
||||
both branches so the navigation e2e specs (`game-shell.spec.ts`,
|
||||
`view-menu`) keep matching.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { i18n, type TranslationKey } from "$lib/i18n/index.svelte";
|
||||
import TableShipClasses from "./table-ship-classes.svelte";
|
||||
|
||||
type Props = { entity: string };
|
||||
let { entity }: Props = $props();
|
||||
@@ -16,12 +20,20 @@ etc.). Until then, the stub renders the localised entity title plus a
|
||||
}
|
||||
</script>
|
||||
|
||||
<section class="active-view" data-testid="active-view-table" data-entity={entity}>
|
||||
{#if entity === "ship-classes"}
|
||||
<TableShipClasses />
|
||||
{:else}
|
||||
<section
|
||||
class="active-view"
|
||||
data-testid="active-view-table"
|
||||
data-entity={entity}
|
||||
>
|
||||
<h2>
|
||||
{i18n.t("game.view.table")}: {i18n.t(entityKey(entity))}
|
||||
</h2>
|
||||
<p>{i18n.t("game.shell.coming_soon")}</p>
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.active-view {
|
||||
|
||||
@@ -192,6 +192,52 @@ const en = {
|
||||
"game.inspector.planet.cargo.pick.no_destinations": "no reachable destinations within {reach} world units",
|
||||
"game.sidebar.order.label.cargo_route_set": "set {loadType} route from planet {source} → planet {destination}",
|
||||
"game.sidebar.order.label.cargo_route_remove": "remove {loadType} route from planet {source}",
|
||||
"game.sidebar.order.label.ship_class_create": "design ship class {name}",
|
||||
"game.sidebar.order.label.ship_class_remove": "remove ship class {name}",
|
||||
"game.table.ship_classes.title": "ship classes",
|
||||
"game.table.ship_classes.column.name": "name",
|
||||
"game.table.ship_classes.column.drive": "drive",
|
||||
"game.table.ship_classes.column.armament": "armament",
|
||||
"game.table.ship_classes.column.weapons": "weapons",
|
||||
"game.table.ship_classes.column.shields": "shields",
|
||||
"game.table.ship_classes.column.cargo": "cargo",
|
||||
"game.table.ship_classes.column.actions": "actions",
|
||||
"game.table.ship_classes.empty": "no ship classes designed yet",
|
||||
"game.table.ship_classes.filter.placeholder": "filter by name",
|
||||
"game.table.ship_classes.action.new": "+ new ship class",
|
||||
"game.table.ship_classes.action.delete": "delete",
|
||||
"game.table.ship_classes.loading": "loading ship classes…",
|
||||
"game.designer.ship_class.title.new": "design new ship class",
|
||||
"game.designer.ship_class.title.view": "ship class {name}",
|
||||
"game.designer.ship_class.field.name": "name",
|
||||
"game.designer.ship_class.field.drive": "drive",
|
||||
"game.designer.ship_class.field.armament": "armament",
|
||||
"game.designer.ship_class.field.weapons": "weapons",
|
||||
"game.designer.ship_class.field.shields": "shields",
|
||||
"game.designer.ship_class.field.cargo": "cargo",
|
||||
"game.designer.ship_class.action.save": "save",
|
||||
"game.designer.ship_class.action.cancel": "cancel",
|
||||
"game.designer.ship_class.action.delete": "delete",
|
||||
"game.designer.ship_class.action.back": "back",
|
||||
"game.designer.ship_class.hint.values": "each value is either 0 or ≥ 1; armament is a non-negative integer; armament and weapons are both zero or both nonzero",
|
||||
"game.designer.ship_class.read_only_notice": "ship classes are designed once; values cannot be edited after creation",
|
||||
"game.designer.ship_class.not_found": "ship class \"{name}\" does not exist",
|
||||
"game.designer.ship_class.invalid.empty": "name cannot be empty",
|
||||
"game.designer.ship_class.invalid.too_long": "name is too long (30 characters max)",
|
||||
"game.designer.ship_class.invalid.starts_with_special": "name cannot start with a special character",
|
||||
"game.designer.ship_class.invalid.ends_with_special": "name cannot end with a special character",
|
||||
"game.designer.ship_class.invalid.consecutive_specials": "too many special characters in a row",
|
||||
"game.designer.ship_class.invalid.whitespace": "name cannot contain spaces",
|
||||
"game.designer.ship_class.invalid.disallowed_character": "name contains disallowed characters",
|
||||
"game.designer.ship_class.invalid.duplicate_name": "a ship class with this name already exists",
|
||||
"game.designer.ship_class.invalid.drive_value": "drive must be 0 or ≥ 1",
|
||||
"game.designer.ship_class.invalid.armament_value": "armament must be 0 or a positive integer",
|
||||
"game.designer.ship_class.invalid.armament_not_integer": "armament must be an integer",
|
||||
"game.designer.ship_class.invalid.weapons_value": "weapons must be 0 or ≥ 1",
|
||||
"game.designer.ship_class.invalid.shields_value": "shields must be 0 or ≥ 1",
|
||||
"game.designer.ship_class.invalid.cargo_value": "cargo must be 0 or ≥ 1",
|
||||
"game.designer.ship_class.invalid.armament_weapons_pair": "armament and weapons must be both zero or both nonzero",
|
||||
"game.designer.ship_class.invalid.all_zero": "at least one value must be nonzero",
|
||||
} as const;
|
||||
|
||||
export default en;
|
||||
|
||||
@@ -193,6 +193,52 @@ const ru: Record<keyof typeof en, string> = {
|
||||
"game.inspector.planet.cargo.pick.no_destinations": "нет планет в зоне полёта {reach} ед.",
|
||||
"game.sidebar.order.label.cargo_route_set": "маршрут {loadType} с планеты {source} → планета {destination}",
|
||||
"game.sidebar.order.label.cargo_route_remove": "удалить маршрут {loadType} с планеты {source}",
|
||||
"game.sidebar.order.label.ship_class_create": "сконструировать класс корабля {name}",
|
||||
"game.sidebar.order.label.ship_class_remove": "удалить класс корабля {name}",
|
||||
"game.table.ship_classes.title": "классы кораблей",
|
||||
"game.table.ship_classes.column.name": "название",
|
||||
"game.table.ship_classes.column.drive": "двигатель",
|
||||
"game.table.ship_classes.column.armament": "вооружённость",
|
||||
"game.table.ship_classes.column.weapons": "оружие",
|
||||
"game.table.ship_classes.column.shields": "защита",
|
||||
"game.table.ship_classes.column.cargo": "трюм",
|
||||
"game.table.ship_classes.column.actions": "действия",
|
||||
"game.table.ship_classes.empty": "классы кораблей ещё не спроектированы",
|
||||
"game.table.ship_classes.filter.placeholder": "фильтр по названию",
|
||||
"game.table.ship_classes.action.new": "+ новый класс корабля",
|
||||
"game.table.ship_classes.action.delete": "удалить",
|
||||
"game.table.ship_classes.loading": "загрузка классов кораблей…",
|
||||
"game.designer.ship_class.title.new": "конструктор нового класса корабля",
|
||||
"game.designer.ship_class.title.view": "класс корабля {name}",
|
||||
"game.designer.ship_class.field.name": "название",
|
||||
"game.designer.ship_class.field.drive": "двигатель",
|
||||
"game.designer.ship_class.field.armament": "вооружённость",
|
||||
"game.designer.ship_class.field.weapons": "оружие",
|
||||
"game.designer.ship_class.field.shields": "защита",
|
||||
"game.designer.ship_class.field.cargo": "трюм",
|
||||
"game.designer.ship_class.action.save": "сохранить",
|
||||
"game.designer.ship_class.action.cancel": "отмена",
|
||||
"game.designer.ship_class.action.delete": "удалить",
|
||||
"game.designer.ship_class.action.back": "назад",
|
||||
"game.designer.ship_class.hint.values": "каждое значение — 0 либо ≥ 1; вооружённость — целое неотрицательное; вооружённость и оружие должны быть оба нулевыми либо оба ненулевыми",
|
||||
"game.designer.ship_class.read_only_notice": "классы кораблей проектируются один раз; характеристики нельзя изменить после создания",
|
||||
"game.designer.ship_class.not_found": "класса \"{name}\" не существует",
|
||||
"game.designer.ship_class.invalid.empty": "название не может быть пустым",
|
||||
"game.designer.ship_class.invalid.too_long": "название слишком длинное (максимум 30 символов)",
|
||||
"game.designer.ship_class.invalid.starts_with_special": "название не может начинаться со спецсимвола",
|
||||
"game.designer.ship_class.invalid.ends_with_special": "название не может заканчиваться спецсимволом",
|
||||
"game.designer.ship_class.invalid.consecutive_specials": "слишком много спецсимволов подряд",
|
||||
"game.designer.ship_class.invalid.whitespace": "название не может содержать пробелы",
|
||||
"game.designer.ship_class.invalid.disallowed_character": "название содержит недопустимые символы",
|
||||
"game.designer.ship_class.invalid.duplicate_name": "класс с таким названием уже существует",
|
||||
"game.designer.ship_class.invalid.drive_value": "двигатель должен быть 0 или ≥ 1",
|
||||
"game.designer.ship_class.invalid.armament_value": "вооружённость должна быть 0 или положительным целым",
|
||||
"game.designer.ship_class.invalid.armament_not_integer": "вооружённость должна быть целым числом",
|
||||
"game.designer.ship_class.invalid.weapons_value": "оружие должно быть 0 или ≥ 1",
|
||||
"game.designer.ship_class.invalid.shields_value": "защита должна быть 0 или ≥ 1",
|
||||
"game.designer.ship_class.invalid.cargo_value": "трюм должен быть 0 или ≥ 1",
|
||||
"game.designer.ship_class.invalid.armament_weapons_pair": "вооружённость и оружие должны быть оба нулевыми или оба ненулевыми",
|
||||
"game.designer.ship_class.invalid.all_zero": "хотя бы одно значение должно быть ненулевым",
|
||||
};
|
||||
|
||||
export default ru;
|
||||
|
||||
@@ -69,6 +69,14 @@ Tests exercise the tab through `__galaxyDebug.seedOrderDraft`
|
||||
loadType: cmd.loadType,
|
||||
source: String(cmd.sourcePlanetNumber),
|
||||
});
|
||||
case "createShipClass":
|
||||
return i18n.t("game.sidebar.order.label.ship_class_create", {
|
||||
name: cmd.name,
|
||||
});
|
||||
case "removeShipClass":
|
||||
return i18n.t("game.sidebar.order.label.ship_class_remove", {
|
||||
name: cmd.name,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
// TS port of `pkg/calc/validator.go.ValidateShipTypeValues` plus a
|
||||
// thin wrapper that runs the entity-name rules and a duplicate-name
|
||||
// check against the live `localShipClass` projection. The validator
|
||||
// is reused by the ship-class designer (`active-view/designer-ship-class.svelte`)
|
||||
// for inline error messages and by `OrderDraftStore.validateCommand`
|
||||
// to gate auto-sync, so the local invariants match the engine's
|
||||
// (`game/internal/controller/ship_class.go.ShipClassCreate`).
|
||||
//
|
||||
// Engine rules (from `pkg/calc/validator.go` and `game/rules.txt`):
|
||||
//
|
||||
// - drive, weapons, shields, cargo: float, equal to 0 or >= 1;
|
||||
// - armament: integer, >= 0;
|
||||
// - either both `armament` and `weapons` are zero or both nonzero;
|
||||
// - not all five values may be zero at once;
|
||||
// - name must satisfy `validateEntityName` (`pkg/util/string.go`).
|
||||
//
|
||||
// The duplicate-name check is a UX-only addition — the engine raises
|
||||
// `EntityDuplicateIdentifierError` for a duplicate `Create` and the
|
||||
// auto-sync pipeline would surface that as a `rejected` row, but
|
||||
// catching it locally keeps the Save button disabled with a clear
|
||||
// hint instead of a red badge after a wire round-trip.
|
||||
|
||||
import {
|
||||
validateEntityName,
|
||||
type EntityNameInvalidReason,
|
||||
} from "./entity-name";
|
||||
|
||||
/**
|
||||
* ShipClassInvalidReason enumerates every reason
|
||||
* `validateShipClass` can refuse a draft. Name-derived reasons are
|
||||
* the same identifiers `validateEntityName` returns, so the
|
||||
* designer's `aria-describedby` mapping reuses the existing
|
||||
* translation keys for those branches and adds new keys only for
|
||||
* the value-derived ones.
|
||||
*/
|
||||
export type ShipClassInvalidReason =
|
||||
| EntityNameInvalidReason
|
||||
| "duplicate_name"
|
||||
| "drive_value"
|
||||
| "armament_value"
|
||||
| "armament_not_integer"
|
||||
| "weapons_value"
|
||||
| "shields_value"
|
||||
| "cargo_value"
|
||||
| "armament_weapons_pair"
|
||||
| "all_zero";
|
||||
|
||||
/**
|
||||
* ShipClassDraft is the structural shape the designer composes. The
|
||||
* five numeric fields carry the player's typed values verbatim;
|
||||
* `validateShipClass` is responsible for refusing non-finite or
|
||||
* out-of-range entries.
|
||||
*/
|
||||
export interface ShipClassDraft {
|
||||
name: string;
|
||||
drive: number;
|
||||
armament: number;
|
||||
weapons: number;
|
||||
shields: number;
|
||||
cargo: number;
|
||||
}
|
||||
|
||||
export type ShipClassValidation =
|
||||
| { ok: true; value: ShipClassDraft }
|
||||
| { ok: false; reason: ShipClassInvalidReason };
|
||||
|
||||
/**
|
||||
* validateShipClass mirrors `ValidateShipTypeValues` plus the
|
||||
* entity-name rules. `existingNames` is the optimistic projection of
|
||||
* already-designed ship classes (from `localShipClass` after
|
||||
* `applyOrderOverlay`). When the trimmed name matches any entry,
|
||||
* the validator returns `duplicate_name` so the designer's Save
|
||||
* button stays disabled. Pass an empty array (or omit the option)
|
||||
* to skip the duplicate check — useful for unit tests of the
|
||||
* value-only rules.
|
||||
*/
|
||||
export function validateShipClass(
|
||||
draft: ShipClassDraft,
|
||||
options: { existingNames?: readonly string[] } = {},
|
||||
): ShipClassValidation {
|
||||
const nameResult = validateEntityName(draft.name);
|
||||
if (!nameResult.ok) {
|
||||
return { ok: false, reason: nameResult.reason };
|
||||
}
|
||||
const trimmedName = nameResult.value;
|
||||
|
||||
if (!isValidDWSC(draft.drive)) {
|
||||
return { ok: false, reason: "drive_value" };
|
||||
}
|
||||
if (!Number.isFinite(draft.armament) || draft.armament < 0) {
|
||||
return { ok: false, reason: "armament_value" };
|
||||
}
|
||||
if (!Number.isInteger(draft.armament)) {
|
||||
return { ok: false, reason: "armament_not_integer" };
|
||||
}
|
||||
if (!isValidDWSC(draft.weapons)) {
|
||||
return { ok: false, reason: "weapons_value" };
|
||||
}
|
||||
if (!isValidDWSC(draft.shields)) {
|
||||
return { ok: false, reason: "shields_value" };
|
||||
}
|
||||
if (!isValidDWSC(draft.cargo)) {
|
||||
return { ok: false, reason: "cargo_value" };
|
||||
}
|
||||
if (
|
||||
(draft.armament === 0 && draft.weapons !== 0) ||
|
||||
(draft.armament !== 0 && draft.weapons === 0)
|
||||
) {
|
||||
return { ok: false, reason: "armament_weapons_pair" };
|
||||
}
|
||||
if (
|
||||
draft.drive === 0 &&
|
||||
draft.armament === 0 &&
|
||||
draft.weapons === 0 &&
|
||||
draft.shields === 0 &&
|
||||
draft.cargo === 0
|
||||
) {
|
||||
return { ok: false, reason: "all_zero" };
|
||||
}
|
||||
|
||||
const existing = options.existingNames ?? [];
|
||||
if (existing.some((existingName) => existingName === trimmedName)) {
|
||||
return { ok: false, reason: "duplicate_name" };
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
value: { ...draft, name: trimmedName },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* isValidDWSC mirrors `pkg/calc/validator.go.CheckShipTypeValueDWSC`:
|
||||
* a Drive / Weapons / Shields / Cargo value is acceptable only when
|
||||
* it is exactly zero or at least one. NaN, infinity, and negative
|
||||
* numbers are rejected.
|
||||
*/
|
||||
function isValidDWSC(value: number): boolean {
|
||||
if (!Number.isFinite(value)) return false;
|
||||
return value === 0 || value >= 1;
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import { fetchOrder } from "./order-load";
|
||||
import type { CommandStatus, OrderCommand } from "./order-types";
|
||||
import { submitOrder } from "./submit";
|
||||
import { validateEntityName } from "$lib/util/entity-name";
|
||||
import { validateShipClass } from "$lib/util/ship-class-validation";
|
||||
|
||||
const NAMESPACE = "order-drafts";
|
||||
const draftKey = (gameId: string): string => `${gameId}/draft`;
|
||||
@@ -487,6 +488,31 @@ function validateCommand(cmd: OrderCommand): CommandStatus {
|
||||
// which the inspector enforces by only mounting the
|
||||
// component on `kind === "local"`.
|
||||
return "valid";
|
||||
case "createShipClass":
|
||||
// Mirrors `pkg/calc/validator.go.ValidateShipTypeValues`
|
||||
// plus the entity-name rules. The duplicate-name check is
|
||||
// the designer's responsibility (it sees the live overlay
|
||||
// list); here the validator runs without `existingNames`
|
||||
// so a draft that was valid at creation time does not flip
|
||||
// to invalid just because another `createShipClass` for
|
||||
// the same name landed in the draft afterwards — both
|
||||
// rows ride out the wire and the engine arbitrates.
|
||||
return validateShipClass({
|
||||
name: cmd.name,
|
||||
drive: cmd.drive,
|
||||
armament: cmd.armament,
|
||||
weapons: cmd.weapons,
|
||||
shields: cmd.shields,
|
||||
cargo: cmd.cargo,
|
||||
}).ok
|
||||
? "valid"
|
||||
: "invalid";
|
||||
case "removeShipClass":
|
||||
// `removeShipClass` carries only the name; the engine
|
||||
// checks that the class exists and is not referenced by
|
||||
// active production / ship groups. Local validation only
|
||||
// guards the name shape.
|
||||
return validateEntityName(cmd.name).ok ? "valid" : "invalid";
|
||||
case "placeholder":
|
||||
// Phase 12 placeholder entries are content-free and never
|
||||
// transition out of `draft` — they are not submittable.
|
||||
|
||||
@@ -16,6 +16,8 @@ import {
|
||||
CommandPlanetRename,
|
||||
CommandPlanetRouteRemove,
|
||||
CommandPlanetRouteSet,
|
||||
CommandShipClassCreate,
|
||||
CommandShipClassRemove,
|
||||
PlanetProduction,
|
||||
PlanetRouteLoadType,
|
||||
UserGamesOrderGet,
|
||||
@@ -197,6 +199,29 @@ function decodeCommand(item: CommandItemView): OrderCommand | null {
|
||||
loadType,
|
||||
};
|
||||
}
|
||||
case CommandPayload.CommandShipClassCreate: {
|
||||
const inner = new CommandShipClassCreate();
|
||||
item.payload(inner);
|
||||
return {
|
||||
kind: "createShipClass",
|
||||
id,
|
||||
name: inner.name() ?? "",
|
||||
drive: inner.drive(),
|
||||
armament: Number(inner.armament()),
|
||||
weapons: inner.weapons(),
|
||||
shields: inner.shields(),
|
||||
cargo: inner.cargo(),
|
||||
};
|
||||
}
|
||||
case CommandPayload.CommandShipClassRemove: {
|
||||
const inner = new CommandShipClassRemove();
|
||||
item.payload(inner);
|
||||
return {
|
||||
kind: "removeShipClass",
|
||||
id,
|
||||
name: inner.name() ?? "",
|
||||
};
|
||||
}
|
||||
default:
|
||||
console.warn(
|
||||
`fetchOrder: skipping unknown command kind (payloadType=${payloadType})`,
|
||||
|
||||
@@ -127,6 +127,45 @@ export interface RemoveCargoRouteCommand {
|
||||
readonly loadType: CargoLoadType;
|
||||
}
|
||||
|
||||
/**
|
||||
* CreateShipClassCommand designs a new ship class with the five
|
||||
* tech-derived numbers plus a name. The numeric fields obey
|
||||
* `pkg/calc/validator.go.ValidateShipTypeValues`: each of `drive`,
|
||||
* `weapons`, `shields`, `cargo` is either zero or ≥ 1; `armament`
|
||||
* is a non-negative integer; `armament` and `weapons` are both zero
|
||||
* or both nonzero; not all five values may be zero. The TS-side
|
||||
* mirror lives in `lib/util/ship-class-validation.ts`. Phase 17
|
||||
* lands the CRUD UI; Phase 18 wires `pkg/calc/` for live previews.
|
||||
*
|
||||
* No collapse rule applies — each create is a distinct user-visible
|
||||
* action and the engine refuses duplicate names server-side.
|
||||
*/
|
||||
export interface CreateShipClassCommand {
|
||||
readonly kind: "createShipClass";
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly drive: number;
|
||||
readonly armament: number;
|
||||
readonly weapons: number;
|
||||
readonly shields: number;
|
||||
readonly cargo: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* RemoveShipClassCommand drops a designed ship class by name. The
|
||||
* engine refuses removals when the class is referenced by an active
|
||||
* planet production target or by an existing ship group
|
||||
* (`game/internal/controller/ship_class.go.shipClassRemove`); both
|
||||
* surface as `cmdApplied=false` on the response and the order tab
|
||||
* row reads `rejected`. No client-side pre-check is needed — Phase
|
||||
* 17 has no projection of ship groups yet.
|
||||
*/
|
||||
export interface RemoveShipClassCommand {
|
||||
readonly kind: "removeShipClass";
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* OrderCommand is the discriminated union of every command shape the
|
||||
* local order draft can hold. The `kind` field is the discriminator;
|
||||
@@ -138,7 +177,9 @@ export type OrderCommand =
|
||||
| PlanetRenameCommand
|
||||
| SetProductionTypeCommand
|
||||
| SetCargoRouteCommand
|
||||
| RemoveCargoRouteCommand;
|
||||
| RemoveCargoRouteCommand
|
||||
| CreateShipClassCommand
|
||||
| RemoveShipClassCommand;
|
||||
|
||||
/**
|
||||
* PRODUCTION_TYPE_VALUES is the canonical tuple of `ProductionType`
|
||||
|
||||
@@ -31,6 +31,8 @@ import {
|
||||
CommandPlanetRename,
|
||||
CommandPlanetRouteRemove,
|
||||
CommandPlanetRouteSet,
|
||||
CommandShipClassCreate,
|
||||
CommandShipClassRemove,
|
||||
PlanetProduction,
|
||||
PlanetRouteLoadType,
|
||||
UserGamesOrder,
|
||||
@@ -193,6 +195,33 @@ function encodeCommandPayload(
|
||||
payloadOffset: offset,
|
||||
};
|
||||
}
|
||||
case "createShipClass": {
|
||||
const nameOffset = builder.createString(cmd.name);
|
||||
const offset = CommandShipClassCreate.createCommandShipClassCreate(
|
||||
builder,
|
||||
nameOffset,
|
||||
cmd.drive,
|
||||
BigInt(cmd.armament),
|
||||
cmd.weapons,
|
||||
cmd.shields,
|
||||
cmd.cargo,
|
||||
);
|
||||
return {
|
||||
payloadType: CommandPayload.CommandShipClassCreate,
|
||||
payloadOffset: offset,
|
||||
};
|
||||
}
|
||||
case "removeShipClass": {
|
||||
const nameOffset = builder.createString(cmd.name);
|
||||
const offset = CommandShipClassRemove.createCommandShipClassRemove(
|
||||
builder,
|
||||
nameOffset,
|
||||
);
|
||||
return {
|
||||
payloadType: CommandPayload.CommandShipClassRemove,
|
||||
payloadOffset: offset,
|
||||
};
|
||||
}
|
||||
case "placeholder":
|
||||
throw new SubmitError(
|
||||
"invalid_request",
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
// Vitest coverage for the Phase 17 ship-class designer. Drives the
|
||||
// component against a real `OrderDraftStore` (with `fake-indexeddb`
|
||||
// standing in for the browser's IDB factory) so the local-validation
|
||||
// + auto-sync side-effects are exercised end-to-end. The optimistic
|
||||
// overlay arrives through a synthetic `RenderedReportSource` instead
|
||||
// of a live report so the tests do not have to thread a full
|
||||
// `GameStateStore` boot.
|
||||
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import "fake-indexeddb/auto";
|
||||
import { fireEvent, render, waitFor } from "@testing-library/svelte";
|
||||
import {
|
||||
afterEach,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
test,
|
||||
vi,
|
||||
} from "vitest";
|
||||
|
||||
import { i18n } from "../src/lib/i18n/index.svelte";
|
||||
import type { GameReport, ShipClassSummary } from "../src/api/game-state";
|
||||
import {
|
||||
ORDER_DRAFT_CONTEXT_KEY,
|
||||
OrderDraftStore,
|
||||
} from "../src/sync/order-draft.svelte";
|
||||
import { RENDERED_REPORT_CONTEXT_KEY } from "../src/lib/rendered-report.svelte";
|
||||
import { IDBCache } from "../src/platform/store/idb-cache";
|
||||
import { openGalaxyDB, type GalaxyDB } from "../src/platform/store/idb";
|
||||
import type { Cache } from "../src/platform/store/index";
|
||||
import type { IDBPDatabase } from "idb";
|
||||
|
||||
const GAME_ID = "11111111-2222-3333-4444-555555555555";
|
||||
|
||||
const pageMock = vi.hoisted(() => ({
|
||||
url: new URL("http://localhost/games/g1/designer/ship-class"),
|
||||
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,
|
||||
}));
|
||||
|
||||
import DesignerShipClass from "../src/lib/active-view/designer-ship-class.svelte";
|
||||
|
||||
let db: IDBPDatabase<GalaxyDB>;
|
||||
let dbName: string;
|
||||
let cache: Cache;
|
||||
let draft: OrderDraftStore;
|
||||
|
||||
beforeEach(async () => {
|
||||
dbName = `galaxy-designer-${crypto.randomUUID()}`;
|
||||
db = await openGalaxyDB(dbName);
|
||||
cache = new IDBCache(db);
|
||||
draft = new OrderDraftStore();
|
||||
await draft.init({ cache, gameId: GAME_ID });
|
||||
i18n.resetForTests("en");
|
||||
pageMock.params = { id: "g1" };
|
||||
gotoMock.mockClear();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
draft.dispose();
|
||||
db.close();
|
||||
await new Promise<void>((resolve) => {
|
||||
const req = indexedDB.deleteDatabase(dbName);
|
||||
req.onsuccess = () => resolve();
|
||||
req.onerror = () => resolve();
|
||||
req.onblocked = () => resolve();
|
||||
});
|
||||
});
|
||||
|
||||
function shipClass(
|
||||
overrides: Partial<ShipClassSummary> & Pick<ShipClassSummary, "name">,
|
||||
): ShipClassSummary {
|
||||
return {
|
||||
drive: 0,
|
||||
armament: 0,
|
||||
weapons: 0,
|
||||
shields: 0,
|
||||
cargo: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeReport(localShipClass: ShipClassSummary[] = []): GameReport {
|
||||
return {
|
||||
turn: 1,
|
||||
mapWidth: 1000,
|
||||
mapHeight: 1000,
|
||||
planetCount: 0,
|
||||
planets: [],
|
||||
race: "",
|
||||
localShipClass,
|
||||
routes: [],
|
||||
localPlayerDrive: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function mountDesigner(opts: {
|
||||
classId?: string;
|
||||
report?: GameReport | null;
|
||||
}) {
|
||||
const report = opts.report ?? makeReport();
|
||||
pageMock.params = opts.classId
|
||||
? { id: "g1", classId: opts.classId }
|
||||
: { id: "g1" };
|
||||
const renderedReport = { get report() { return report; } };
|
||||
const context = new Map<unknown, unknown>([
|
||||
[ORDER_DRAFT_CONTEXT_KEY, draft],
|
||||
[RENDERED_REPORT_CONTEXT_KEY, renderedReport],
|
||||
]);
|
||||
return render(DesignerShipClass, { context });
|
||||
}
|
||||
|
||||
describe("ship-class designer (new mode)", () => {
|
||||
test("renders the form with a Save button disabled by default", () => {
|
||||
const ui = mountDesigner({});
|
||||
expect(
|
||||
ui.getByTestId("active-view-designer-ship-class"),
|
||||
).toHaveAttribute("data-mode", "new");
|
||||
expect(ui.getByTestId("designer-ship-class-save")).toBeDisabled();
|
||||
expect(ui.getByTestId("designer-ship-class-error")).toHaveTextContent(
|
||||
"name cannot be empty",
|
||||
);
|
||||
});
|
||||
|
||||
test("Save adds a createShipClass to the draft after a valid edit", async () => {
|
||||
const ui = mountDesigner({});
|
||||
const nameInput = ui.getByTestId("designer-ship-class-input-name");
|
||||
await fireEvent.input(nameInput, { target: { value: "Drone" } });
|
||||
const driveInput = ui.getByTestId("designer-ship-class-input-drive");
|
||||
await fireEvent.input(driveInput, { target: { value: "1" } });
|
||||
|
||||
await waitFor(() =>
|
||||
expect(ui.getByTestId("designer-ship-class-save")).not.toBeDisabled(),
|
||||
);
|
||||
await fireEvent.click(ui.getByTestId("designer-ship-class-save"));
|
||||
await waitFor(() => expect(draft.commands).toHaveLength(1));
|
||||
const cmd = draft.commands[0]!;
|
||||
if (cmd.kind !== "createShipClass") throw new Error("wrong kind");
|
||||
expect(cmd.name).toBe("Drone");
|
||||
expect(cmd.drive).toBe(1);
|
||||
expect(cmd.armament).toBe(0);
|
||||
await waitFor(() =>
|
||||
expect(gotoMock).toHaveBeenCalledWith("/games/g1/table/ship-classes"),
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects a duplicate name from the overlay before any sync", async () => {
|
||||
const ui = mountDesigner({
|
||||
report: makeReport([
|
||||
shipClass({ name: "Scout", drive: 1 }),
|
||||
]),
|
||||
});
|
||||
await fireEvent.input(
|
||||
ui.getByTestId("designer-ship-class-input-name"),
|
||||
{ target: { value: "Scout" } },
|
||||
);
|
||||
await fireEvent.input(
|
||||
ui.getByTestId("designer-ship-class-input-drive"),
|
||||
{ target: { value: "1" } },
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(ui.getByTestId("designer-ship-class-error")).toHaveTextContent(
|
||||
"already exists",
|
||||
),
|
||||
);
|
||||
expect(ui.getByTestId("designer-ship-class-save")).toBeDisabled();
|
||||
});
|
||||
|
||||
test("rejects nonzero armament with zero weapons", async () => {
|
||||
const ui = mountDesigner({});
|
||||
await fireEvent.input(
|
||||
ui.getByTestId("designer-ship-class-input-name"),
|
||||
{ target: { value: "Bad" } },
|
||||
);
|
||||
await fireEvent.input(
|
||||
ui.getByTestId("designer-ship-class-input-armament"),
|
||||
{ target: { value: "1" } },
|
||||
);
|
||||
await fireEvent.input(
|
||||
ui.getByTestId("designer-ship-class-input-drive"),
|
||||
{ target: { value: "1" } },
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(ui.getByTestId("designer-ship-class-error")).toHaveTextContent(
|
||||
"armament and weapons must be both zero or both nonzero",
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test("Cancel navigates back without mutating the draft", async () => {
|
||||
const ui = mountDesigner({});
|
||||
await fireEvent.click(ui.getByTestId("designer-ship-class-cancel"));
|
||||
expect(draft.commands).toHaveLength(0);
|
||||
expect(gotoMock).toHaveBeenCalledWith("/games/g1/table/ship-classes");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ship-class designer (view mode)", () => {
|
||||
test("renders the read-only summary plus Delete + Back affordances", () => {
|
||||
const ui = mountDesigner({
|
||||
classId: "Cruiser",
|
||||
report: makeReport([
|
||||
shipClass({
|
||||
name: "Cruiser",
|
||||
drive: 15,
|
||||
armament: 1,
|
||||
weapons: 15,
|
||||
shields: 15,
|
||||
cargo: 0,
|
||||
}),
|
||||
]),
|
||||
});
|
||||
expect(
|
||||
ui.getByTestId("active-view-designer-ship-class"),
|
||||
).toHaveAttribute("data-mode", "view");
|
||||
expect(ui.getByTestId("designer-ship-class-view-name")).toHaveTextContent(
|
||||
"Cruiser",
|
||||
);
|
||||
expect(ui.getByTestId("designer-ship-class-view-drive")).toHaveTextContent(
|
||||
"15",
|
||||
);
|
||||
expect(
|
||||
ui.getByTestId("designer-ship-class-view-armament"),
|
||||
).toHaveTextContent("1");
|
||||
expect(ui.getByTestId("designer-ship-class-delete")).toBeInTheDocument();
|
||||
expect(ui.getByTestId("designer-ship-class-back")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("Delete adds a removeShipClass and navigates back", async () => {
|
||||
const ui = mountDesigner({
|
||||
classId: "Cruiser",
|
||||
report: makeReport([shipClass({ name: "Cruiser", drive: 15 })]),
|
||||
});
|
||||
await fireEvent.click(ui.getByTestId("designer-ship-class-delete"));
|
||||
await waitFor(() => expect(draft.commands).toHaveLength(1));
|
||||
const cmd = draft.commands[0]!;
|
||||
if (cmd.kind !== "removeShipClass") throw new Error("wrong kind");
|
||||
expect(cmd.name).toBe("Cruiser");
|
||||
await waitFor(() =>
|
||||
expect(gotoMock).toHaveBeenCalledWith("/games/g1/table/ship-classes"),
|
||||
);
|
||||
});
|
||||
|
||||
test("renders a not-found message when the class is missing from the overlay", () => {
|
||||
const ui = mountDesigner({
|
||||
classId: "Ghost",
|
||||
report: makeReport([]),
|
||||
});
|
||||
expect(
|
||||
ui.getByTestId("designer-ship-class-not-found"),
|
||||
).toHaveTextContent("Ghost");
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,8 @@ import {
|
||||
CommandPlanetRename,
|
||||
CommandPlanetRouteRemove,
|
||||
CommandPlanetRouteSet,
|
||||
CommandShipClassCreate,
|
||||
CommandShipClassRemove,
|
||||
PlanetProduction,
|
||||
PlanetRouteLoadType,
|
||||
UserGamesOrder,
|
||||
@@ -65,11 +67,28 @@ export interface RemoveCargoRouteResultFixture
|
||||
loadType: "COL" | "CAP" | "MAT" | "EMP";
|
||||
}
|
||||
|
||||
export interface CreateShipClassResultFixture extends CommandResultFixtureBase {
|
||||
kind: "createShipClass";
|
||||
name: string;
|
||||
drive: number;
|
||||
armament: number;
|
||||
weapons: number;
|
||||
shields: number;
|
||||
cargo: number;
|
||||
}
|
||||
|
||||
export interface RemoveShipClassResultFixture extends CommandResultFixtureBase {
|
||||
kind: "removeShipClass";
|
||||
name: string;
|
||||
}
|
||||
|
||||
export type CommandResultFixture =
|
||||
| PlanetRenameResultFixture
|
||||
| SetProductionTypeResultFixture
|
||||
| SetCargoRouteResultFixture
|
||||
| RemoveCargoRouteResultFixture;
|
||||
| RemoveCargoRouteResultFixture
|
||||
| CreateShipClassResultFixture
|
||||
| RemoveShipClassResultFixture;
|
||||
|
||||
export function buildOrderResponsePayload(
|
||||
gameId: string,
|
||||
@@ -173,6 +192,29 @@ function encodeItem(builder: Builder, c: CommandResultFixture): number {
|
||||
payloadType = CommandPayload.CommandPlanetRouteRemove;
|
||||
break;
|
||||
}
|
||||
case "createShipClass": {
|
||||
const nameOffset = builder.createString(c.name);
|
||||
inner = CommandShipClassCreate.createCommandShipClassCreate(
|
||||
builder,
|
||||
nameOffset,
|
||||
c.drive,
|
||||
BigInt(c.armament),
|
||||
c.weapons,
|
||||
c.shields,
|
||||
c.cargo,
|
||||
);
|
||||
payloadType = CommandPayload.CommandShipClassCreate;
|
||||
break;
|
||||
}
|
||||
case "removeShipClass": {
|
||||
const nameOffset = builder.createString(c.name);
|
||||
inner = CommandShipClassRemove.createCommandShipClassRemove(
|
||||
builder,
|
||||
nameOffset,
|
||||
);
|
||||
payloadType = CommandPayload.CommandShipClassRemove;
|
||||
break;
|
||||
}
|
||||
}
|
||||
CommandItem.startCommandItem(builder);
|
||||
CommandItem.addCmdId(builder, cmdIdOffset);
|
||||
|
||||
@@ -53,6 +53,11 @@ export interface OtherPlanetFixture extends InhabitedFixture {
|
||||
|
||||
export interface ShipClassFixture {
|
||||
name: string;
|
||||
drive?: number;
|
||||
armament?: number;
|
||||
weapons?: number;
|
||||
shields?: number;
|
||||
cargo?: number;
|
||||
}
|
||||
|
||||
export interface PlayerFixture {
|
||||
@@ -165,6 +170,11 @@ export function buildReportPayload(fixture: ReportFixture): Uint8Array {
|
||||
const name = builder.createString(cls.name);
|
||||
ShipClass.startShipClass(builder);
|
||||
ShipClass.addName(builder, name);
|
||||
ShipClass.addDrive(builder, cls.drive ?? 0);
|
||||
ShipClass.addArmament(builder, BigInt(cls.armament ?? 0));
|
||||
ShipClass.addWeapons(builder, cls.weapons ?? 0);
|
||||
ShipClass.addShields(builder, cls.shields ?? 0);
|
||||
ShipClass.addCargo(builder, cls.cargo ?? 0);
|
||||
return ShipClass.endShipClass(builder);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,385 @@
|
||||
// Phase 17 end-to-end coverage for the ship-class CRUD flow. Boots
|
||||
// an authenticated session, mocks the gateway with a single local
|
||||
// planet plus an empty `localShipClass` projection, navigates to
|
||||
// the ship-classes table, opens the designer, fills the form, and
|
||||
// asserts that:
|
||||
//
|
||||
// 1. Save adds a `createShipClass` row to the local order draft,
|
||||
// auto-syncs through `user.games.order`, and the new class
|
||||
// appears in the table immediately (overlay) and in the
|
||||
// sidebar order tab as `applied`;
|
||||
// 2. invalid input keeps the Save button disabled and surfaces
|
||||
// the localised reason;
|
||||
// 3. Delete on a row adds a `removeShipClass` and the class
|
||||
// disappears from the table; the order tab reflects both rows;
|
||||
// 4. a rejected `createShipClass` (engine-side `cmdApplied=false`)
|
||||
// surfaces as `rejected` in the order tab and the table no
|
||||
// longer shows the optimistic class.
|
||||
|
||||
import { fromJson, type JsonValue } from "@bufbuild/protobuf";
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
import { ByteBuffer } from "flatbuffers";
|
||||
|
||||
import { ExecuteCommandRequestSchema } from "../../src/proto/galaxy/gateway/v1/edge_gateway_pb";
|
||||
import { UUID } from "../../src/proto/galaxy/fbs/common";
|
||||
import {
|
||||
CommandPayload,
|
||||
CommandShipClassCreate,
|
||||
CommandShipClassRemove,
|
||||
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,
|
||||
type ShipClassFixture,
|
||||
} from "./fixtures/report-fbs";
|
||||
import {
|
||||
buildOrderGetResponsePayload,
|
||||
buildOrderResponsePayload,
|
||||
type CommandResultFixture,
|
||||
} from "./fixtures/order-fbs";
|
||||
|
||||
const SESSION_ID = "phase-17-ship-class-session";
|
||||
const GAME_ID = "17171717-1717-1717-1717-171717171717";
|
||||
|
||||
interface MockOpts {
|
||||
createOutcome: "applied" | "rejected";
|
||||
initialClasses?: ShipClassFixture[];
|
||||
}
|
||||
|
||||
interface MockHandle {
|
||||
get lastCreate(): {
|
||||
name: string;
|
||||
drive: number;
|
||||
armament: number;
|
||||
weapons: number;
|
||||
shields: number;
|
||||
cargo: number;
|
||||
} | null;
|
||||
get lastRemove(): { name: string } | null;
|
||||
get submittedCount(): number;
|
||||
}
|
||||
|
||||
async function mockGateway(page: Page, opts: MockOpts): Promise<MockHandle> {
|
||||
const game: GameFixture = {
|
||||
gameId: GAME_ID,
|
||||
gameName: "Phase 17 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,
|
||||
};
|
||||
|
||||
let storedOrder: CommandResultFixture[] = [];
|
||||
let lastCreate: MockHandle["lastCreate"] = null;
|
||||
let lastRemove: MockHandle["lastRemove"] = null;
|
||||
let submittedCount = 0;
|
||||
const reportClasses: ShipClassFixture[] = [...(opts.initialClasses ?? [])];
|
||||
|
||||
await page.route(
|
||||
"**/galaxy.gateway.v1.EdgeGateway/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: 1,
|
||||
mapWidth: 4000,
|
||||
mapHeight: 4000,
|
||||
race: "Earthlings",
|
||||
players: [{ name: "Earthlings", drive: 1 }],
|
||||
localPlanets: [
|
||||
{
|
||||
number: 1,
|
||||
name: "Earth",
|
||||
x: 1000,
|
||||
y: 1000,
|
||||
size: 1000,
|
||||
resources: 5,
|
||||
population: 800,
|
||||
industry: 600,
|
||||
},
|
||||
],
|
||||
localShipClass: reportClasses,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "user.games.order": {
|
||||
const decoded = UserGamesOrder.getRootAsUserGamesOrder(
|
||||
new ByteBuffer(req.payloadBytes),
|
||||
);
|
||||
submittedCount += 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 payloadType = item.payloadType();
|
||||
if (payloadType === CommandPayload.CommandShipClassCreate) {
|
||||
const inner = new CommandShipClassCreate();
|
||||
item.payload(inner);
|
||||
lastCreate = {
|
||||
name: inner.name() ?? "",
|
||||
drive: inner.drive(),
|
||||
armament: Number(inner.armament()),
|
||||
weapons: inner.weapons(),
|
||||
shields: inner.shields(),
|
||||
cargo: inner.cargo(),
|
||||
};
|
||||
const applied = opts.createOutcome === "applied";
|
||||
fixtures.push({
|
||||
kind: "createShipClass",
|
||||
cmdId,
|
||||
name: lastCreate.name,
|
||||
drive: lastCreate.drive,
|
||||
armament: lastCreate.armament,
|
||||
weapons: lastCreate.weapons,
|
||||
shields: lastCreate.shields,
|
||||
cargo: lastCreate.cargo,
|
||||
applied,
|
||||
errorCode: applied ? null : 1,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (payloadType === CommandPayload.CommandShipClassRemove) {
|
||||
const inner = new CommandShipClassRemove();
|
||||
item.payload(inner);
|
||||
lastRemove = { name: inner.name() ?? "" };
|
||||
fixtures.push({
|
||||
kind: "removeShipClass",
|
||||
cmdId,
|
||||
name: lastRemove.name,
|
||||
applied: true,
|
||||
errorCode: null,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
storedOrder = fixtures;
|
||||
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(
|
||||
"**/galaxy.gateway.v1.EdgeGateway/SubscribeEvents",
|
||||
async () => {
|
||||
await new Promise<void>(() => {});
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
get lastCreate() {
|
||||
return lastCreate;
|
||||
},
|
||||
get lastRemove() {
|
||||
return lastRemove;
|
||||
},
|
||||
get submittedCount() {
|
||||
return submittedCount;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
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,
|
||||
);
|
||||
}
|
||||
|
||||
test("create / list / delete ship class via the table + designer", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test.skip(
|
||||
testInfo.project.name.startsWith("chromium-mobile"),
|
||||
"phase 17 spec covers desktop layout; mobile inherits the same store",
|
||||
);
|
||||
|
||||
const handle = await mockGateway(page, { createOutcome: "applied" });
|
||||
await bootSession(page);
|
||||
await page.goto(`/games/${GAME_ID}/table/ship-classes`);
|
||||
|
||||
const tableHost = page.getByTestId("active-view-table");
|
||||
await expect(tableHost).toBeVisible();
|
||||
await expect(page.getByTestId("ship-classes-empty")).toBeVisible();
|
||||
|
||||
await page.getByTestId("ship-classes-new").click();
|
||||
await expect(page.getByTestId("active-view-designer-ship-class")).toHaveAttribute(
|
||||
"data-mode",
|
||||
"new",
|
||||
);
|
||||
|
||||
await page.getByTestId("designer-ship-class-input-name").fill("Drone");
|
||||
await page.getByTestId("designer-ship-class-input-drive").fill("1");
|
||||
const save = page.getByTestId("designer-ship-class-save");
|
||||
await expect(save).toBeEnabled();
|
||||
await save.click();
|
||||
|
||||
// Returns to the table; the optimistic overlay shows the new class.
|
||||
await expect(page.getByTestId("ship-classes-table")).toBeVisible();
|
||||
const row = page.getByTestId("ship-classes-row");
|
||||
await expect(row).toHaveAttribute("data-name", "Drone");
|
||||
await expect(page.getByTestId("ship-classes-cell-drive")).toHaveText("1");
|
||||
|
||||
// The auto-sync round-trip lands as applied.
|
||||
await page.getByTestId("sidebar-tab-order").click();
|
||||
const orderTool = page.getByTestId("sidebar-tool-order");
|
||||
await expect(orderTool.getByTestId("order-command-label-0")).toContainText(
|
||||
"Drone",
|
||||
);
|
||||
await expect(orderTool.getByTestId("order-command-status-0")).toHaveText(
|
||||
"applied",
|
||||
);
|
||||
expect(handle.lastCreate?.name).toBe("Drone");
|
||||
expect(handle.lastCreate?.drive).toBe(1);
|
||||
|
||||
// Delete the class through the table action; the row disappears
|
||||
// and the order tab gets a second row.
|
||||
await page.getByTestId("sidebar-tab-inspector").click();
|
||||
await page.getByTestId("ship-classes-delete").click();
|
||||
await expect(page.getByTestId("ship-classes-empty")).toBeVisible();
|
||||
await page.getByTestId("sidebar-tab-order").click();
|
||||
await expect(orderTool.getByTestId("order-command-label-1")).toContainText(
|
||||
"Drone",
|
||||
);
|
||||
expect(handle.lastRemove?.name).toBe("Drone");
|
||||
});
|
||||
|
||||
test("designer keeps Save disabled while the form is invalid", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test.skip(
|
||||
testInfo.project.name.startsWith("chromium-mobile"),
|
||||
"phase 17 spec covers desktop layout; mobile inherits the same store",
|
||||
);
|
||||
|
||||
await mockGateway(page, { createOutcome: "applied" });
|
||||
await bootSession(page);
|
||||
await page.goto(`/games/${GAME_ID}/designer/ship-class`);
|
||||
|
||||
const save = page.getByTestId("designer-ship-class-save");
|
||||
await expect(save).toBeDisabled();
|
||||
|
||||
// Empty name surfaces the entity-name error.
|
||||
await expect(page.getByTestId("designer-ship-class-error")).toHaveText(
|
||||
"name cannot be empty",
|
||||
);
|
||||
|
||||
// Mismatched armament / weapons triggers the pair rule.
|
||||
await page.getByTestId("designer-ship-class-input-name").fill("Bad");
|
||||
await page.getByTestId("designer-ship-class-input-armament").fill("1");
|
||||
await page.getByTestId("designer-ship-class-input-drive").fill("1");
|
||||
await expect(page.getByTestId("designer-ship-class-error")).toHaveText(
|
||||
"armament and weapons must be both zero or both nonzero",
|
||||
);
|
||||
await expect(save).toBeDisabled();
|
||||
|
||||
// Filling weapons resolves the pair rule.
|
||||
await page.getByTestId("designer-ship-class-input-weapons").fill("1");
|
||||
await expect(save).toBeEnabled();
|
||||
});
|
||||
|
||||
test("rejected createShipClass keeps the table empty and surfaces the failure", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test.skip(
|
||||
testInfo.project.name.startsWith("chromium-mobile"),
|
||||
"phase 17 spec covers desktop layout; mobile inherits the same store",
|
||||
);
|
||||
|
||||
await mockGateway(page, { createOutcome: "rejected" });
|
||||
await bootSession(page);
|
||||
await page.goto(`/games/${GAME_ID}/designer/ship-class`);
|
||||
|
||||
await page.getByTestId("designer-ship-class-input-name").fill("Drone");
|
||||
await page.getByTestId("designer-ship-class-input-drive").fill("1");
|
||||
await page.getByTestId("designer-ship-class-save").click();
|
||||
|
||||
// Designer's save() calls SvelteKit `goto` to navigate back to
|
||||
// the table. SPA navigation keeps the per-game `OrderDraftStore`
|
||||
// alive so the auto-sync round-trip (which flips the status from
|
||||
// `submitting` to `rejected`) lands while the table is showing.
|
||||
// Order tab carries a `rejected` row; the optimistic overlay
|
||||
// drops the class once the engine answers `cmdApplied=false`.
|
||||
await page.getByTestId("sidebar-tab-order").click();
|
||||
const orderTool = page.getByTestId("sidebar-tool-order");
|
||||
await expect(orderTool.getByTestId("order-command-status-0")).toHaveText(
|
||||
"rejected",
|
||||
);
|
||||
await expect(orderTool.getByTestId("order-sync")).toHaveAttribute(
|
||||
"data-sync-status",
|
||||
"error",
|
||||
);
|
||||
|
||||
// Switch sidebar back to inspector so the active-view (table)
|
||||
// regains focus, and assert the optimistic class is gone.
|
||||
await page.getByTestId("sidebar-tab-inspector").click();
|
||||
await expect(page.getByTestId("ship-classes-empty")).toBeVisible();
|
||||
});
|
||||
@@ -1,9 +1,13 @@
|
||||
// Component tests for every Phase 10 active-view stub. Each stub
|
||||
// renders the localised view title plus the `coming soon` body copy
|
||||
// and exposes a stable `data-testid` so later phases can replace the
|
||||
// content without renaming the test hook. The table stub additionally
|
||||
// honours its `entity` prop and falls back to the snake_case i18n key
|
||||
// for an unknown slug.
|
||||
// Component tests for the remaining Phase 10 active-view stubs. Each
|
||||
// stub renders the localised view title plus the `coming soon` body
|
||||
// copy and exposes a stable `data-testid` so later phases can replace
|
||||
// the content without renaming the test hook. Phase 17 lit up the
|
||||
// ship-classes table and the ship-class designer, so the assertions
|
||||
// for those slugs / components moved to the dedicated suites
|
||||
// (`table-ship-classes.test.ts`, `designer-ship-class.test.ts`); the
|
||||
// `table.svelte` router still falls back to the stub for the
|
||||
// not-yet-implemented entities (planets, ship-groups, fleets,
|
||||
// sciences, races) and that fallback is exercised here.
|
||||
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { render } from "@testing-library/svelte";
|
||||
@@ -16,7 +20,6 @@ import TableView from "../src/lib/active-view/table.svelte";
|
||||
import ReportView from "../src/lib/active-view/report.svelte";
|
||||
import BattleView from "../src/lib/active-view/battle.svelte";
|
||||
import MailView from "../src/lib/active-view/mail.svelte";
|
||||
import DesignerShipClass from "../src/lib/active-view/designer-ship-class.svelte";
|
||||
import DesignerScience from "../src/lib/active-view/designer-science.svelte";
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -38,20 +41,22 @@ describe("active-view stubs", () => {
|
||||
expect(ui.getByTestId("map-canvas-wrap")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("table stub maps a kebab-case entity to the right i18n title", () => {
|
||||
const ui = render(TableView, { props: { entity: "ship-classes" } });
|
||||
test("table stub falls back for not-yet-implemented entities", () => {
|
||||
const ui = render(TableView, { props: { entity: "planets" } });
|
||||
const node = ui.getByTestId("active-view-table");
|
||||
expect(node).toHaveAttribute("data-entity", "ship-classes");
|
||||
expect(node).toHaveTextContent("ship classes");
|
||||
expect(node).toHaveAttribute("data-entity", "planets");
|
||||
expect(node).toHaveTextContent("planets");
|
||||
expect(node).toHaveTextContent("coming soon");
|
||||
});
|
||||
|
||||
test("table stub also handles a single-word entity", () => {
|
||||
const ui = render(TableView, { props: { entity: "planets" } });
|
||||
expect(ui.getByTestId("active-view-table")).toHaveTextContent("planets");
|
||||
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 / mail / designer stubs render their localised titles", () => {
|
||||
test("report / mail / designer-science stubs render their localised titles", () => {
|
||||
const r = render(ReportView);
|
||||
expect(r.getByTestId("active-view-report")).toHaveTextContent(
|
||||
"turn report",
|
||||
@@ -62,11 +67,6 @@ describe("active-view stubs", () => {
|
||||
"diplomatic mail",
|
||||
);
|
||||
|
||||
const sc = render(DesignerShipClass);
|
||||
expect(
|
||||
sc.getByTestId("active-view-designer-ship-class"),
|
||||
).toHaveTextContent("ship-class designer");
|
||||
|
||||
const sci = render(DesignerScience);
|
||||
expect(
|
||||
sci.getByTestId("active-view-designer-science"),
|
||||
|
||||
@@ -98,12 +98,21 @@ interface PlanetFixture {
|
||||
y: number;
|
||||
}
|
||||
|
||||
interface ShipClassFixture {
|
||||
name: string;
|
||||
drive?: number;
|
||||
armament?: number;
|
||||
weapons?: number;
|
||||
shields?: number;
|
||||
cargo?: number;
|
||||
}
|
||||
|
||||
function buildReportPayload(opts: {
|
||||
turn: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
planets?: PlanetFixture[];
|
||||
shipClasses?: { name: string }[];
|
||||
shipClasses?: ShipClassFixture[];
|
||||
}): Uint8Array {
|
||||
const builder = new Builder(256);
|
||||
const planetOffsets = (opts.planets ?? []).map((planet) => {
|
||||
@@ -121,6 +130,11 @@ function buildReportPayload(opts: {
|
||||
const name = builder.createString(cls.name);
|
||||
ShipClass.startShipClass(builder);
|
||||
ShipClass.addName(builder, name);
|
||||
ShipClass.addDrive(builder, cls.drive ?? 0);
|
||||
ShipClass.addArmament(builder, BigInt(cls.armament ?? 0));
|
||||
ShipClass.addWeapons(builder, cls.weapons ?? 0);
|
||||
ShipClass.addShields(builder, cls.shields ?? 0);
|
||||
ShipClass.addCargo(builder, cls.cargo ?? 0);
|
||||
return ShipClass.endShipClass(builder);
|
||||
});
|
||||
const localPlanetVec =
|
||||
@@ -277,21 +291,45 @@ describe("GameStateStore", () => {
|
||||
expect(store.error).toBe("device session missing");
|
||||
});
|
||||
|
||||
test("decodeReport surfaces the localShipClass projection by name", async () => {
|
||||
test("decodeReport surfaces the localShipClass projection with full attributes", async () => {
|
||||
listMyGamesSpy.mockResolvedValue([makeGameSummary(1)]);
|
||||
const client = makeFakeClient(async () => ({
|
||||
resultCode: "ok",
|
||||
payloadBytes: buildReportPayload({
|
||||
turn: 1,
|
||||
planets: [{ number: 1, name: "Earth", x: 100, y: 100 }],
|
||||
shipClasses: [{ name: "Scout" }, { name: "Destroyer" }],
|
||||
shipClasses: [
|
||||
{
|
||||
name: "Scout",
|
||||
drive: 1,
|
||||
armament: 0,
|
||||
weapons: 0,
|
||||
shields: 0,
|
||||
cargo: 0,
|
||||
},
|
||||
{
|
||||
name: "Destroyer",
|
||||
drive: 6,
|
||||
armament: 1,
|
||||
weapons: 8,
|
||||
shields: 4,
|
||||
cargo: 0,
|
||||
},
|
||||
],
|
||||
}),
|
||||
}));
|
||||
const store = new GameStateStore();
|
||||
await store.init({ client, cache, gameId: GAME_ID });
|
||||
expect(store.report?.localShipClass).toEqual([
|
||||
{ name: "Scout" },
|
||||
{ name: "Destroyer" },
|
||||
{ name: "Scout", drive: 1, armament: 0, weapons: 0, shields: 0, cargo: 0 },
|
||||
{
|
||||
name: "Destroyer",
|
||||
drive: 6,
|
||||
armament: 1,
|
||||
weapons: 8,
|
||||
shields: 4,
|
||||
cargo: 0,
|
||||
},
|
||||
]);
|
||||
store.dispose();
|
||||
});
|
||||
|
||||
@@ -78,6 +78,19 @@ function localPlanet(
|
||||
};
|
||||
}
|
||||
|
||||
function shipClass(
|
||||
overrides: Partial<ShipClassSummary> & Pick<ShipClassSummary, "name">,
|
||||
): ShipClassSummary {
|
||||
return {
|
||||
drive: 0,
|
||||
armament: 0,
|
||||
weapons: 0,
|
||||
shields: 0,
|
||||
cargo: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function mountProduction(
|
||||
planet: ReportPlanet,
|
||||
localShipClass: ShipClassSummary[] = [],
|
||||
@@ -167,8 +180,8 @@ describe("planet inspector — production controls", () => {
|
||||
|
||||
test("Build-Ship click on a class emits a SHIP setProductionType command", async () => {
|
||||
const ui = mountProduction(localPlanet({ number: 7 }), [
|
||||
{ name: "Scout" },
|
||||
{ name: "Destroyer" },
|
||||
shipClass({ name: "Scout" }),
|
||||
shipClass({ name: "Destroyer" }),
|
||||
]);
|
||||
await fireEvent.click(
|
||||
ui.getByTestId("inspector-planet-production-segment-ship"),
|
||||
@@ -185,7 +198,7 @@ describe("planet inspector — production controls", () => {
|
||||
|
||||
test("re-clicks on the same planet collapse to the latest entry via the store", async () => {
|
||||
const ui = mountProduction(localPlanet({ number: 7 }), [
|
||||
{ name: "Scout" },
|
||||
shipClass({ name: "Scout" }),
|
||||
]);
|
||||
await fireEvent.click(
|
||||
ui.getByTestId("inspector-planet-production-segment-industry"),
|
||||
@@ -224,7 +237,7 @@ describe("planet inspector — production controls", () => {
|
||||
for (const tc of cases) {
|
||||
const ui = mountProduction(
|
||||
localPlanet({ number: 1, production: tc.production }),
|
||||
[{ name: "Scout" }],
|
||||
[shipClass({ name: "Scout" })],
|
||||
);
|
||||
const ids: ReadonlyArray<
|
||||
"industry" | "materials" | "research" | "ship"
|
||||
@@ -268,7 +281,7 @@ describe("planet inspector — production controls", () => {
|
||||
test("ship class sub-row matches when production equals a class name", async () => {
|
||||
const ui = mountProduction(
|
||||
localPlanet({ number: 1, production: "Scout" }),
|
||||
[{ name: "Scout" }, { name: "Destroyer" }],
|
||||
[shipClass({ name: "Scout" }), shipClass({ name: "Destroyer" })],
|
||||
);
|
||||
expect(
|
||||
ui.getByTestId("inspector-planet-production-ship-Scout").classList
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
// Vitest coverage for `lib/util/ship-class-validation.ts`. The
|
||||
// validator is a TS port of `pkg/calc/validator.go` plus the
|
||||
// `validateEntityName` rules and a UX-only duplicate-name check.
|
||||
// Each branch is exercised explicitly so a future engine
|
||||
// validator change cannot drift silently.
|
||||
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import {
|
||||
validateShipClass,
|
||||
type ShipClassDraft,
|
||||
} from "../src/lib/util/ship-class-validation";
|
||||
|
||||
function draft(overrides: Partial<ShipClassDraft>): ShipClassDraft {
|
||||
return {
|
||||
name: "Scout",
|
||||
drive: 1,
|
||||
armament: 0,
|
||||
weapons: 0,
|
||||
shields: 0,
|
||||
cargo: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("validateShipClass", () => {
|
||||
test("accepts a minimal valid drone-style class", () => {
|
||||
const result = validateShipClass(
|
||||
draft({ name: "Drone", drive: 1, armament: 0, weapons: 0 }),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.name).toBe("Drone");
|
||||
});
|
||||
|
||||
test("trims surrounding whitespace from the name", () => {
|
||||
const result = validateShipClass(draft({ name: " Scout " }));
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.name).toBe("Scout");
|
||||
});
|
||||
|
||||
test("rejects empty name", () => {
|
||||
const result = validateShipClass(draft({ name: "" }));
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.reason).toBe("empty");
|
||||
});
|
||||
|
||||
test("rejects name longer than 30 runes", () => {
|
||||
const result = validateShipClass(draft({ name: "a".repeat(31) }));
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.reason).toBe("too_long");
|
||||
});
|
||||
|
||||
test("rejects name with whitespace inside", () => {
|
||||
const result = validateShipClass(draft({ name: "Big Ship" }));
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.reason).toBe("whitespace");
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ value: 0.5, reason: "drive_value" as const, field: "drive" as const },
|
||||
{ value: -1, reason: "drive_value" as const, field: "drive" as const },
|
||||
{
|
||||
value: Number.POSITIVE_INFINITY,
|
||||
reason: "drive_value" as const,
|
||||
field: "drive" as const,
|
||||
},
|
||||
{ value: 0.5, reason: "weapons_value" as const, field: "weapons" as const },
|
||||
{ value: 0.5, reason: "shields_value" as const, field: "shields" as const },
|
||||
{ value: 0.5, reason: "cargo_value" as const, field: "cargo" as const },
|
||||
])(
|
||||
"rejects $field = $value with reason $reason",
|
||||
({ value, reason, field }) => {
|
||||
// Make sure both armament/weapons stay coupled (both nonzero or both zero) so we
|
||||
// trip the per-field rule before the pair rule kicks in.
|
||||
const overrides: Partial<ShipClassDraft> = {
|
||||
drive: 1,
|
||||
armament: 0,
|
||||
weapons: 0,
|
||||
shields: 0,
|
||||
cargo: 0,
|
||||
};
|
||||
if (field === "weapons") {
|
||||
overrides.armament = 1;
|
||||
}
|
||||
(overrides as Record<typeof field, number>)[field] = value;
|
||||
const result = validateShipClass(draft(overrides));
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.reason).toBe(reason);
|
||||
},
|
||||
);
|
||||
|
||||
test("rejects negative armament", () => {
|
||||
const result = validateShipClass(draft({ armament: -1 }));
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.reason).toBe("armament_value");
|
||||
});
|
||||
|
||||
test("rejects fractional armament", () => {
|
||||
const result = validateShipClass(draft({ armament: 1.5, weapons: 1 }));
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.reason).toBe("armament_not_integer");
|
||||
});
|
||||
|
||||
test("rejects nonzero armament with zero weapons", () => {
|
||||
const result = validateShipClass(draft({ armament: 2, weapons: 0 }));
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.reason).toBe("armament_weapons_pair");
|
||||
});
|
||||
|
||||
test("rejects zero armament with nonzero weapons", () => {
|
||||
const result = validateShipClass(draft({ armament: 0, weapons: 5 }));
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.reason).toBe("armament_weapons_pair");
|
||||
});
|
||||
|
||||
test("rejects all-zero values", () => {
|
||||
const result = validateShipClass(
|
||||
draft({
|
||||
drive: 0,
|
||||
armament: 0,
|
||||
weapons: 0,
|
||||
shields: 0,
|
||||
cargo: 0,
|
||||
}),
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.reason).toBe("all_zero");
|
||||
});
|
||||
|
||||
test("accepts the canonical Cruiser fixture from rules.txt", () => {
|
||||
const result = validateShipClass(
|
||||
draft({
|
||||
name: "Cruiser",
|
||||
drive: 15,
|
||||
armament: 1,
|
||||
weapons: 15,
|
||||
shields: 15,
|
||||
cargo: 0,
|
||||
}),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
});
|
||||
|
||||
test("accepts the canonical Megafreighter fixture", () => {
|
||||
const result = validateShipClass(
|
||||
draft({
|
||||
name: "Megafreighter",
|
||||
drive: 80,
|
||||
armament: 2,
|
||||
weapons: 2,
|
||||
shields: 30,
|
||||
cargo: 100,
|
||||
}),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
});
|
||||
|
||||
test("flags duplicate names against existingNames", () => {
|
||||
const result = validateShipClass(draft({ name: "Scout" }), {
|
||||
existingNames: ["Scout", "Destroyer"],
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.reason).toBe("duplicate_name");
|
||||
});
|
||||
|
||||
test("compares duplicate names after trimming", () => {
|
||||
const result = validateShipClass(draft({ name: " Scout " }), {
|
||||
existingNames: ["Scout"],
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.reason).toBe("duplicate_name");
|
||||
});
|
||||
|
||||
test("does not flag duplicates when existingNames is empty", () => {
|
||||
const result = validateShipClass(draft({ name: "Scout" }), {
|
||||
existingNames: [],
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,210 @@
|
||||
// Vitest coverage for the Phase 17 ship-classes table active view.
|
||||
// The component renders against a synthetic `RenderedReportSource`
|
||||
// (so the suite does not need a live `GameStateStore`) and a real
|
||||
// `OrderDraftStore` (so the per-row Delete affordance exercises
|
||||
// the `removeShipClass` add path including persistence).
|
||||
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import "fake-indexeddb/auto";
|
||||
import { fireEvent, render, waitFor } from "@testing-library/svelte";
|
||||
import {
|
||||
afterEach,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
test,
|
||||
vi,
|
||||
} from "vitest";
|
||||
|
||||
import { i18n } from "../src/lib/i18n/index.svelte";
|
||||
import type { GameReport, ShipClassSummary } from "../src/api/game-state";
|
||||
import {
|
||||
ORDER_DRAFT_CONTEXT_KEY,
|
||||
OrderDraftStore,
|
||||
} from "../src/sync/order-draft.svelte";
|
||||
import { RENDERED_REPORT_CONTEXT_KEY } from "../src/lib/rendered-report.svelte";
|
||||
import { IDBCache } from "../src/platform/store/idb-cache";
|
||||
import { openGalaxyDB, type GalaxyDB } from "../src/platform/store/idb";
|
||||
import type { Cache } from "../src/platform/store/index";
|
||||
import type { IDBPDatabase } from "idb";
|
||||
|
||||
const GAME_ID = "11111111-2222-3333-4444-555555555555";
|
||||
|
||||
const pageMock = vi.hoisted(() => ({
|
||||
url: new URL("http://localhost/games/g1/table/ship-classes"),
|
||||
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,
|
||||
}));
|
||||
|
||||
import TableShipClasses from "../src/lib/active-view/table-ship-classes.svelte";
|
||||
|
||||
let db: IDBPDatabase<GalaxyDB>;
|
||||
let dbName: string;
|
||||
let cache: Cache;
|
||||
let draft: OrderDraftStore;
|
||||
|
||||
beforeEach(async () => {
|
||||
dbName = `galaxy-table-ship-classes-${crypto.randomUUID()}`;
|
||||
db = await openGalaxyDB(dbName);
|
||||
cache = new IDBCache(db);
|
||||
draft = new OrderDraftStore();
|
||||
await draft.init({ cache, gameId: GAME_ID });
|
||||
i18n.resetForTests("en");
|
||||
pageMock.params = { id: "g1" };
|
||||
gotoMock.mockClear();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
draft.dispose();
|
||||
db.close();
|
||||
await new Promise<void>((resolve) => {
|
||||
const req = indexedDB.deleteDatabase(dbName);
|
||||
req.onsuccess = () => resolve();
|
||||
req.onerror = () => resolve();
|
||||
req.onblocked = () => resolve();
|
||||
});
|
||||
});
|
||||
|
||||
function shipClass(
|
||||
overrides: Partial<ShipClassSummary> & Pick<ShipClassSummary, "name">,
|
||||
): ShipClassSummary {
|
||||
return {
|
||||
drive: 0,
|
||||
armament: 0,
|
||||
weapons: 0,
|
||||
shields: 0,
|
||||
cargo: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeReport(localShipClass: ShipClassSummary[]): GameReport {
|
||||
return {
|
||||
turn: 1,
|
||||
mapWidth: 1000,
|
||||
mapHeight: 1000,
|
||||
planetCount: 0,
|
||||
planets: [],
|
||||
race: "",
|
||||
localShipClass,
|
||||
routes: [],
|
||||
localPlayerDrive: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function mountTable(report: GameReport | null) {
|
||||
const renderedReport = { get report() { return report; } };
|
||||
const context = new Map<unknown, unknown>([
|
||||
[ORDER_DRAFT_CONTEXT_KEY, draft],
|
||||
[RENDERED_REPORT_CONTEXT_KEY, renderedReport],
|
||||
]);
|
||||
return render(TableShipClasses, { context });
|
||||
}
|
||||
|
||||
describe("ship-classes table", () => {
|
||||
test("renders a loading placeholder before the report lands", () => {
|
||||
const ui = mountTable(null);
|
||||
expect(ui.getByTestId("ship-classes-loading")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("renders an empty placeholder when no classes are designed", () => {
|
||||
const ui = mountTable(makeReport([]));
|
||||
expect(ui.getByTestId("ship-classes-empty")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("renders one row per ship class with full attributes", () => {
|
||||
const ui = mountTable(
|
||||
makeReport([
|
||||
shipClass({
|
||||
name: "Cruiser",
|
||||
drive: 15,
|
||||
armament: 1,
|
||||
weapons: 15,
|
||||
shields: 15,
|
||||
cargo: 0,
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const rows = ui.getAllByTestId("ship-classes-row");
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toHaveAttribute("data-name", "Cruiser");
|
||||
expect(ui.getByTestId("ship-classes-cell-drive")).toHaveTextContent("15");
|
||||
expect(ui.getByTestId("ship-classes-cell-armament")).toHaveTextContent("1");
|
||||
});
|
||||
|
||||
test("filters rows by case-insensitive name match", async () => {
|
||||
const ui = mountTable(
|
||||
makeReport([
|
||||
shipClass({ name: "Drone", drive: 1 }),
|
||||
shipClass({ name: "Cruiser", drive: 15, armament: 1, weapons: 15 }),
|
||||
]),
|
||||
);
|
||||
await fireEvent.input(ui.getByTestId("ship-classes-filter"), {
|
||||
target: { value: "cru" },
|
||||
});
|
||||
const rows = ui.getAllByTestId("ship-classes-row");
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toHaveAttribute("data-name", "Cruiser");
|
||||
});
|
||||
|
||||
test("toggles sort direction when the same column is clicked twice", async () => {
|
||||
const ui = mountTable(
|
||||
makeReport([
|
||||
shipClass({ name: "Drone", drive: 1 }),
|
||||
shipClass({
|
||||
name: "Cruiser",
|
||||
drive: 15,
|
||||
armament: 1,
|
||||
weapons: 15,
|
||||
shields: 15,
|
||||
}),
|
||||
shipClass({ name: "Battleship", drive: 25 }),
|
||||
]),
|
||||
);
|
||||
const driveHeader = ui.getByTestId("ship-classes-column-drive");
|
||||
await fireEvent.click(driveHeader);
|
||||
let names = ui
|
||||
.getAllByTestId("ship-classes-row")
|
||||
.map((row) => row.getAttribute("data-name"));
|
||||
expect(names).toEqual(["Drone", "Cruiser", "Battleship"]);
|
||||
await fireEvent.click(driveHeader);
|
||||
names = ui
|
||||
.getAllByTestId("ship-classes-row")
|
||||
.map((row) => row.getAttribute("data-name"));
|
||||
expect(names).toEqual(["Battleship", "Cruiser", "Drone"]);
|
||||
});
|
||||
|
||||
test("dblclick on a row navigates to the designer for that class", async () => {
|
||||
const ui = mountTable(
|
||||
makeReport([shipClass({ name: "Drone", drive: 1 })]),
|
||||
);
|
||||
await fireEvent.dblClick(ui.getByTestId("ship-classes-row"));
|
||||
expect(gotoMock).toHaveBeenCalledWith("/games/g1/designer/ship-class/Drone");
|
||||
});
|
||||
|
||||
test("delete button adds a removeShipClass to the draft", async () => {
|
||||
const ui = mountTable(
|
||||
makeReport([shipClass({ name: "Drone", drive: 1 })]),
|
||||
);
|
||||
await fireEvent.click(ui.getByTestId("ship-classes-delete"));
|
||||
await waitFor(() => expect(draft.commands).toHaveLength(1));
|
||||
const cmd = draft.commands[0]!;
|
||||
if (cmd.kind !== "removeShipClass") throw new Error("wrong kind");
|
||||
expect(cmd.name).toBe("Drone");
|
||||
});
|
||||
|
||||
test("new button navigates to the empty designer", async () => {
|
||||
const ui = mountTable(makeReport([]));
|
||||
await fireEvent.click(ui.getByTestId("ship-classes-new"));
|
||||
expect(gotoMock).toHaveBeenCalledWith("/games/g1/designer/ship-class");
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user