ui: plan 01-27 done #1

Merged
developer merged 120 commits from ai/ui-client into main 2026-05-13 18:55:14 +00:00
31 changed files with 2751 additions and 71 deletions
Showing only changes of commit 7bea22b0b5 - Show all commits
+67 -21
View File
@@ -2307,43 +2307,89 @@ Decisions during stage:
delta. Implemented in `ui/frontend/src/map/ship-groups.ts` delta. Implemented in `ui/frontend/src/map/ship-groups.ts`
alongside the existing in-space point primitive. alongside the existing in-space point primitive.
## Phase 21. Sciences — CRUD List + Designer ## ~~Phase 21. Sciences — CRUD List + Designer~~
Status: pending. Status: done (local-ci run TBD).
Goal: define and manage sciences (named mixes of tech proportions Goal: define and manage sciences (named mixes of tech proportions
summing to 1.0) through a table view and a designer. summing to 1.0) through a table view and a designer, plus surface
them in the planet production picker.
Artifacts: Artifacts:
- `ui/frontend/src/routes/games/[id]/table/sciences/+page.svelte` - `ui/frontend/src/lib/active-view/table-sciences.svelte` — sciences
list of sciences with name and four tech proportions list with sort / filter / Delete, mounted by the existing
- `ui/frontend/src/routes/games/[id]/designer/science/[id]/+page.svelte` `routes/games/[id]/table/[entity]` catch-all when `entity ===
designer with four numeric inputs that auto-normalise to 1.0 and a "sciences"`.
name field - `ui/frontend/src/lib/active-view/designer-science.svelte` —
designer with four percent inputs (`step="0.1"`, range
`[0, 100]`), live sum readout, strict sum-equals-100 gate, and a
read-only view mode for the existing
`routes/games/[id]/designer/science/[[scienceId]]` route.
- `ui/frontend/src/sync/order-types.ts` extends with `CreateScience` - `ui/frontend/src/sync/order-types.ts` extends with `CreateScience`
and `UpdateScience` command variants and `RemoveScience` command variants (the original plan mentioned
- topic doc `ui/docs/science-designer-ux.md` covering `UpdateScience`; the wire only carries Create + Remove, so the
auto-normalisation, validation, and the relationship to the planet decision below replaces Update with Remove).
production picker (Phase 15) - `ui/frontend/src/lib/util/science-validation.ts` — the TS-side
mirror of `pkg/calc/validator.go.ValidateScienceValues` plus the
entity-name rules and the percent → fraction conversion.
- `ui/frontend/src/api/game-state.ts` — adds `ScienceSummary`,
`localScience` on `GameReport`, decoder, and overlay branches for
`createScience` / `removeScience`.
- `ui/frontend/src/lib/inspectors/planet/production.svelte` — the
Research sub-row gains one button per defined science; click
emits `setProductionType("SCIENCE", "<name>")`.
- topic doc `ui/docs/science-designer-ux.md` covering the percent
input model, validation, and the planet-production-picker
integration.
Dependencies: Phase 17. Dependencies: Phase 17.
Decisions during stage:
1. `UpdateScience` was a planning error: the wire schema
(`pkg/schema/fbs/order.fbs`) only carries
`CommandScienceCreate` + `CommandScienceRemove`. Sciences are
write-once on the wire — the designer's view mode therefore has
no Save-edits affordance, and an "edit" is a Remove + Create
sequence the player drives manually. Mirrors Phase 17's
ship-class pattern.
2. The production-picker integration places science buttons inside
the existing Research sub-row, alongside the four tech buttons,
instead of adding a fifth top-level segment. A science wins
over a same-named tech display when the engine sends an
ambiguous production string (a science named `Drive` shadows
the Drive tech button).
3. Designer inputs are percentages (`step="0.1"`, `[0, 100]`) with
a strict sum-equals-100 gate (`SUM_EPSILON_PERCENT = 1e-3`),
not auto-rebalanced fractions. The user controls the sum; the
designer converts to fractions only on Save before dispatching
`createScience`.
Acceptance criteria: Acceptance criteria:
- the user can create, edit, and delete sciences; - the user can create and delete sciences (no in-place edit — see
- proportions auto-normalise on edit so the sum is always 1.0; decision 1);
- proportions are entered as one-decimal percentages and the four
must sum to exactly `100` for Save to enable;
- the planet production picker (Phase 15) lists the user's sciences - the planet production picker (Phase 15) lists the user's sciences
and lets the user select one for research production; in the Research sub-row and lets the user select one for research
- name validation matches [`rules.txt`](../game/rules.txt) constraints (length, allowed production;
characters, special characters not at start/end, no triple repeats). - name validation matches [`rules.txt`](../game/rules.txt)
constraints (length, allowed characters, special characters not
at start/end, no triple repeats).
Targeted tests: Targeted tests:
- Vitest unit tests for proportion normalisation; - Vitest unit tests for percent-range validation, sum-equals-100
- Vitest unit tests for science name validation; gate, and percent → fraction conversion
- Playwright e2e: create a science, set a planet to research it, (`tests/science-validation.test.ts`);
submit, confirm. - Vitest component tests for the table
(`tests/table-sciences.test.ts`) and the designer
(`tests/designer-science.test.ts`);
- Playwright e2e: create a science, set a planet's production to it
via the Research sub-row, delete it
(`tests/e2e/sciences.spec.ts`).
## Phase 22. Races View — War/Peace Toggle and Votes ## Phase 22. Races View — War/Peace Toggle and Votes
+106
View File
@@ -0,0 +1,106 @@
# Science designer UX
A *science* is a named mix of four tech proportions —
`drive`, `weapons`, `shields`, `cargo` — that sum to `1.0`. When a
planet's production is set to a science, the planet's industry
output for that turn is split between the four tech research tracks
in those proportions
(`game/internal/controller/planet/production.go.runScienceResearch`).
Phase 21 lights up the CRUD list, the designer, and the
production-picker integration. The wire and the engine validation
are unchanged from earlier phases — only the UI is new.
## Engine semantics in one paragraph
`pkg/schema/fbs/order.fbs.CommandScienceCreate` carries
`name + drive + weapons + shields + cargo` as four `float64`
proportions. The engine validator
(`pkg/calc/validator.go.ValidateScienceValues`) refuses any value
outside `[0, 1]` and any sum that drifts further than its float
tolerance from `1.0`. Names follow the universal entity-name rules
(`pkg/util/string.go.ValidateTypeName`): trimmed, non-empty, ≤ 30
runes, only letters / digits / combining marks / the allowed special
set `!@#$%^*-_=+~()[]{}`, no special at start or end, ≤ 2 specials
in a row, no whitespace. There is no `CommandScienceUpdate` on the
wire — sciences are write-once, and an "edit" is a Remove + Create
sequence.
## Percent input model
The designer presents the four proportions as percentages
(`step="0.1"`, range `[0, 100]`) so the player can type and reason
about whole-number splits — closer to how `game/rules.txt` describes
sciences (`game/rules.txt:345-362`: "10 parts Drive, 5 parts
Weapons, 30 parts Shields, 0 parts Cargo, …"). The wire shape is
still fractions; conversion happens inside `validateScience` only on
Save (`value / 100` for each of the four).
The four inputs are *not* auto-rebalanced. The validator refuses a
draft whose sum drifts further than `SUM_EPSILON_PERCENT` (`1e-3`)
from `100`, and the form's Save button stays disabled until the sum
matches. A live readout under the inputs displays the running total
so the player can chase it down without trial-and-error guessing.
The strict-sum gate is a Phase 21 decision (alternatives —
auto-rebalance, raw-parts-with-engine-normalisation — were
considered and rejected): keeping the input model close to "what
gets sent on the wire" minimises surprises when the engine returns
the science exactly as typed. See `lib/util/science-validation.ts`
for the validator and the conversion helper.
## Name validation
`validateScience` runs `validateEntityName` first and returns its
invalid-reason verbatim, so the designer's `aria-describedby`
mapping reuses the existing translation keys for `empty`,
`too_long`, `starts_with_special`, `ends_with_special`,
`consecutive_specials`, `whitespace`, `disallowed_character`. A
new key `duplicate_name` covers the UX-only check against the
optimistic-overlay `localScience` projection — the engine would
refuse the duplicate at submit time, but catching it locally keeps
the Save button disabled with a clear hint instead of letting a
red-badge `rejected` row land in the order tab.
## Read-only view mode
A `scienceId`-bearing URL renders the designer in view mode: a
read-only table of the four percentages plus name, with Back and
Delete affordances. Sciences are write-once on the wire, so there
is no Save-edits affordance — to change a science, the player
deletes it and creates a new one. Delete dispatches a
`removeScience` order command; the engine refuses removals when the
science is referenced by an active production target on any planet,
which surfaces as `rejected` in the order tab.
## Production-picker integration
The planet inspector's Research sub-row
(`lib/inspectors/planet/production.svelte`) renders the four tech
buttons and one extra button per defined science from the player's
`localScience` overlay. A click on a science button dispatches
`setProductionType("SCIENCE", "<scienceName>")`, mirroring the
wire-level `CommandPlanetProduce` shape
(`pkg/schema/fbs/order.fbs.CommandPlanetProduce`).
The active highlight is derived from `planet.production` — the
display string the engine emits in the report. A science name
shadows the matching tech display string when they collide (a
science deliberately named `Drive` wins over the Drive tech
button), because the wire string is ambiguous and the user clearly
intended the named science. This is a pragmatic accept; a
structured production tag on the wire would let us disambiguate
without the shadow rule, but that is a separate backend concern.
## Tests
- `tests/science-validation.test.ts` — validator branches, percent
→ fraction conversion, sum tolerance, duplicate-name detection.
- `tests/table-sciences.test.ts` — table rendering, filter, sort,
Delete dispatches `removeScience`, navigation to the designer.
- `tests/designer-science.test.ts` — empty form Save disabled,
live sum readout, valid Save dispatches `createScience` with
fractions, view-mode Delete dispatches `removeScience`,
duplicate-name guard against the overlay.
- `tests/e2e/sciences.spec.ts` — full Playwright walkthrough:
create → list → set planet production via the Research sub-row
→ delete.
+89 -4
View File
@@ -25,6 +25,13 @@
// `removeShipClass` variants — pending Save / Delete actions are // `removeShipClass` variants — pending Save / Delete actions are
// reflected in the table immediately, without waiting for the // reflected in the table immediately, without waiting for the
// auto-sync round-trip. // auto-sync round-trip.
//
// Phase 21 adds `localScience` (a list of `ScienceSummary` rows
// decoded from `Report.local_science`) so the sciences table and
// designer have data to render, and extends `applyOrderOverlay` with
// the `createScience` / `removeScience` variants — pending Save /
// Delete actions surface in the table and the planet production
// picker's Research sub-row immediately.
import { Builder, ByteBuffer } from "flatbuffers"; import { Builder, ByteBuffer } from "flatbuffers";
@@ -101,6 +108,25 @@ export interface ShipClassSummary {
cargo: number; cargo: number;
} }
/**
* ScienceSummary is the projection of `report.Science` the sciences
* table and designer render. The four tech proportions are fractions
* in `[0, 1]` summing to `1.0`, mirroring
* `pkg/calc/validator.go.ValidateScienceValues` exactly. The designer
* presents them as percentages (`value * 100`) so users can type and
* reason about whole-number proportions; the wire shape stays
* fractional. Used by `lib/active-view/table-sciences.svelte`,
* `lib/active-view/designer-science.svelte`, and the planet
* production picker (`lib/inspectors/planet/production.svelte`).
*/
export interface ScienceSummary {
name: string;
drive: number;
weapons: number;
shields: number;
cargo: number;
}
/** /**
* ReportRouteEntry is one slot of a planet's cargo-route table — * ReportRouteEntry is one slot of a planet's cargo-route table —
* a (loadType, destinationPlanetNumber) pair. The engine stores * a (loadType, destinationPlanetNumber) pair. The engine stores
@@ -233,6 +259,16 @@ export interface GameReport {
* empty. * empty.
*/ */
localShipClass: ShipClassSummary[]; localShipClass: ShipClassSummary[];
/**
* localScience enumerates the player's own defined sciences. Each
* entry carries the four tech proportions as fractions in `[0, 1]`
* summing to `1.0`. Empty until at least one science is created
* (`CommandScienceCreate`, Phase 21). The sciences table and the
* planet production picker's Research sub-row read from this
* projection (after `applyOrderOverlay`) so freshly-queued
* `createScience` / `removeScience` actions surface immediately.
*/
localScience: ScienceSummary[];
/** /**
* routes lists every cargo route the player has configured. * routes lists every cargo route the player has configured.
* Each entry is keyed by source planet; the per-planet * Each entry is keyed by source planet; the per-planet
@@ -414,6 +450,19 @@ function decodeReport(report: Report): GameReport {
}); });
} }
const localScience: ScienceSummary[] = [];
for (let i = 0; i < report.localScienceLength(); i++) {
const s = report.localScience(i);
if (s === null) continue;
localScience.push({
name: s.name() ?? "",
drive: s.drive(),
weapons: s.weapons(),
shields: s.shields(),
cargo: s.cargo(),
});
}
const raceName = report.race() ?? ""; const raceName = report.race() ?? "";
const routes = decodeReportRoutes(report); const routes = decodeReportRoutes(report);
const localTech = findLocalPlayerTech(report, raceName); const localTech = findLocalPlayerTech(report, raceName);
@@ -432,6 +481,7 @@ function decodeReport(report: Report): GameReport {
planets, planets,
race: raceName, race: raceName,
localShipClass, localShipClass,
localScience,
routes, routes,
localPlayerDrive: localTech.drive, localPlayerDrive: localTech.drive,
localPlayerWeapons: localTech.weapons, localPlayerWeapons: localTech.weapons,
@@ -766,9 +816,12 @@ export function uuidToHiLo(value: string): [bigint, bigint] {
* `planetRename`; Phase 15 extended it to `setProductionType`; * `planetRename`; Phase 15 extended it to `setProductionType`;
* Phase 16 to `setCargoRoute` / `removeCargoRoute`; Phase 17 to * Phase 16 to `setCargoRoute` / `removeCargoRoute`; Phase 17 to
* `createShipClass` / `removeShipClass` so the ship-class table * `createShipClass` / `removeShipClass` so the ship-class table
* shows pending Save / Delete actions immediately. Other variants * shows pending Save / Delete actions immediately; Phase 21 to
* pass through. The function is pure: callers re-derive the overlay * `createScience` / `removeScience` so the sciences table and the
* whenever the draft or the report change. * planet production picker's Research sub-row mirror pending Save /
* Delete actions. 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`, * `statuses` maps command id → status. Entries with `valid`,
* `submitting`, or `applied` participate in the overlay — together * `submitting`, or `applied` participate in the overlay — together
@@ -787,6 +840,7 @@ export function applyOrderOverlay(
let mutatedPlanets: ReportPlanet[] | null = null; let mutatedPlanets: ReportPlanet[] | null = null;
let mutatedRoutes: ReportRoute[] | null = null; let mutatedRoutes: ReportRoute[] | null = null;
let mutatedShipClass: ShipClassSummary[] | null = null; let mutatedShipClass: ShipClassSummary[] | null = null;
let mutatedScience: ScienceSummary[] | null = null;
for (const cmd of commands) { for (const cmd of commands) {
const status = statuses[cmd.id]; const status = statuses[cmd.id];
if ( if (
@@ -870,11 +924,41 @@ export function applyOrderOverlay(
mutatedShipClass.splice(idx, 1); mutatedShipClass.splice(idx, 1);
continue; continue;
} }
if (cmd.kind === "createScience") {
if (mutatedScience === null) {
mutatedScience = [...report.localScience];
}
// Skip duplicates by name: the engine refuses duplicates
// server-side and the designer's local validator pre-checks
// against the live overlay, but a stale draft could still
// carry an entry whose name now collides with the server
// snapshot. Keeping the projection unique avoids two rows in
// the table for the same name.
if (mutatedScience.some((sci) => sci.name === cmd.name)) continue;
mutatedScience.push({
name: cmd.name,
drive: cmd.drive,
weapons: cmd.weapons,
shields: cmd.shields,
cargo: cmd.cargo,
});
continue;
}
if (cmd.kind === "removeScience") {
if (mutatedScience === null) {
mutatedScience = [...report.localScience];
}
const idx = mutatedScience.findIndex((sci) => sci.name === cmd.name);
if (idx < 0) continue;
mutatedScience.splice(idx, 1);
continue;
}
} }
if ( if (
mutatedPlanets === null && mutatedPlanets === null &&
mutatedRoutes === null && mutatedRoutes === null &&
mutatedShipClass === null mutatedShipClass === null &&
mutatedScience === null
) { ) {
return report; return report;
} }
@@ -883,6 +967,7 @@ export function applyOrderOverlay(
planets: mutatedPlanets ?? report.planets, planets: mutatedPlanets ?? report.planets,
routes: mutatedRoutes ?? report.routes, routes: mutatedRoutes ?? report.routes,
localShipClass: mutatedShipClass ?? report.localShipClass, localShipClass: mutatedShipClass ?? report.localShipClass,
localScience: mutatedScience ?? report.localScience,
}; };
} }
+19
View File
@@ -27,6 +27,7 @@ import type {
ReportPlanet, ReportPlanet,
ReportRoute, ReportRoute,
ReportUnidentifiedShipGroup, ReportUnidentifiedShipGroup,
ScienceSummary,
ShipClassSummary, ShipClassSummary,
ShipGroupTech, ShipGroupTech,
} from "./game-state"; } from "./game-state";
@@ -144,6 +145,14 @@ interface SyntheticLocalFleet {
state?: string; state?: string;
} }
interface SyntheticScience {
name?: string;
drive?: number;
weapons?: number;
shields?: number;
cargo?: number;
}
interface SyntheticReportRoot { interface SyntheticReportRoot {
turn?: number; turn?: number;
mapWidth?: number; mapWidth?: number;
@@ -156,6 +165,7 @@ interface SyntheticReportRoot {
uninhabitedPlanet?: SyntheticPlanet[]; uninhabitedPlanet?: SyntheticPlanet[];
unidentifiedPlanet?: SyntheticPlanet[]; unidentifiedPlanet?: SyntheticPlanet[];
localShipClass?: SyntheticShipClass[]; localShipClass?: SyntheticShipClass[];
localScience?: SyntheticScience[];
localGroup?: SyntheticShipGroup[]; localGroup?: SyntheticShipGroup[];
otherGroup?: SyntheticShipGroup[]; otherGroup?: SyntheticShipGroup[];
incomingGroup?: SyntheticIncomingGroup[]; incomingGroup?: SyntheticIncomingGroup[];
@@ -194,6 +204,14 @@ function decodeSyntheticReport(json: unknown): GameReport {
}), }),
); );
const localScience: ScienceSummary[] = (root.localScience ?? []).map((sc) => ({
name: typeof sc.name === "string" ? sc.name : "",
drive: numOr0(sc.drive),
weapons: numOr0(sc.weapons),
shields: numOr0(sc.shields),
cargo: numOr0(sc.cargo),
}));
const race = typeof root.race === "string" ? root.race : ""; const race = typeof root.race === "string" ? root.race : "";
const tech = findLocalPlayerTech(root.player ?? [], race); const tech = findLocalPlayerTech(root.player ?? [], race);
@@ -260,6 +278,7 @@ function decodeSyntheticReport(json: unknown): GameReport {
planets, planets,
race, race,
localShipClass, localShipClass,
localScience,
routes, routes,
localPlayerDrive: tech.drive, localPlayerDrive: tech.drive,
localPlayerWeapons: tech.weapons, localPlayerWeapons: tech.weapons,
@@ -1,28 +1,448 @@
<!-- <!--
Phase 10 stub for the science designer active view. Phase 21 wires Phase 21 science designer. Two modes driven by the optional
the CRUD list and designer. The optional `scienceId` URL segment is `scienceId` URL segment:
accepted but ignored at this point.
- **new (no scienceId)** — empty form with four percent fields
plus name. Save is disabled until `validateScience` returns
`ok`; the localised tooltip mirrors `validateEntityName`'s
invalid-reason messages and the value-rule mirrors the engine's
`pkg/calc/validator.go.ValidateScienceValues`. Save adds a
`createScience` to the local order draft (with the four
percentages converted to fractions in `[0, 1]`) and returns to
the table.
- **view (scienceId set)** — read-only render of the matching row
from the optimistic overlay. Sciences are defined once and
cannot be modified after creation (Phase 21 decision: the wire
has only Create + Remove, no Update); the view exposes a Delete
affordance (engine-side checks ensure the science is not
referenced by an active production target) and a Back button.
The four tech proportions are entered as percentages (`step="0.1"`)
with a strict sum-equals-100 gate. The running sum is shown live so
the player can chase it down; conversion to wire fractions happens
inside `validateScience` only on Save. The choice of percent vs.
fractions is a Phase 21 decision documented in
`ui/docs/science-designer-ux.md`.
--> -->
<script lang="ts"> <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 { ScienceSummary } 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 {
fractionsToPercent,
validateScience,
type ScienceInvalidReason,
} from "$lib/util/science-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 scienceId = $derived(page.params.scienceId ?? "");
const isViewMode = $derived(scienceId !== "");
const localScience = $derived<ScienceSummary[]>(
rendered?.report?.localScience ?? [],
);
const existingNames = $derived(localScience.map((sci) => sci.name));
const viewing = $derived(
isViewMode
? (localScience.find((sci) => sci.name === scienceId) ?? null)
: null,
);
const viewingPercent = $derived(
viewing === null ? null : fractionsToPercent(viewing),
);
let name = $state("");
let drive = $state(0);
let weapons = $state(0);
let shields = $state(0);
let cargo = $state(0);
let nameInputEl: HTMLInputElement | null = $state(null);
const invalidReasonKeyMap: Record<ScienceInvalidReason, TranslationKey> = {
empty: "game.designer.science.invalid.empty",
too_long: "game.designer.science.invalid.too_long",
starts_with_special: "game.designer.science.invalid.starts_with_special",
ends_with_special: "game.designer.science.invalid.ends_with_special",
consecutive_specials: "game.designer.science.invalid.consecutive_specials",
whitespace: "game.designer.science.invalid.whitespace",
disallowed_character: "game.designer.science.invalid.disallowed_character",
duplicate_name: "game.designer.science.invalid.duplicate_name",
drive_value: "game.designer.science.invalid.drive_value",
weapons_value: "game.designer.science.invalid.weapons_value",
shields_value: "game.designer.science.invalid.shields_value",
cargo_value: "game.designer.science.invalid.cargo_value",
sum_not_hundred: "game.designer.science.invalid.sum_not_hundred",
};
const validation = $derived(
validateScience(
{ name, drive, weapons, shields, cargo },
{ existingNames },
),
);
const invalidMessage = $derived(
validation.ok ? "" : i18n.t(invalidReasonKeyMap[validation.reason]),
);
const canSave = $derived(validation.ok && draft !== undefined);
const sumPercent = $derived(drive + weapons + shields + cargo);
const sumDisplay = $derived(
sumPercent.toLocaleString(undefined, {
minimumFractionDigits: 0,
maximumFractionDigits: 1,
}),
);
$effect(() => {
if (!isViewMode) {
void tick().then(() => nameInputEl?.focus());
}
});
function formatPercent(fraction: number): string {
return (fraction * 100).toLocaleString(undefined, {
minimumFractionDigits: 0,
maximumFractionDigits: 1,
});
}
function backToTable(): void {
void goto(`/games/${gameId}/table/sciences`);
}
async function save(): Promise<void> {
if (!validation.ok || draft === undefined) return;
await draft.add({
kind: "createScience",
id: crypto.randomUUID(),
name: validation.value.name,
drive: validation.value.drive,
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: "removeScience",
id: crypto.randomUUID(),
name: viewing.name,
});
backToTable();
}
</script> </script>
<section class="active-view" data-testid="active-view-designer-science"> <section
class="active-view"
data-testid="active-view-designer-science"
data-mode={isViewMode ? "view" : "new"}
>
{#if isViewMode}
{#if viewing === null || viewingPercent === null}
<h2>{i18n.t("game.view.designer.science")}</h2> <h2>{i18n.t("game.view.designer.science")}</h2>
<p>{i18n.t("game.shell.coming_soon")}</p> <p class="not-found" data-testid="designer-science-not-found">
{i18n.t("game.designer.science.not_found", { name: scienceId })}
</p>
<div class="actions">
<button
type="button"
data-testid="designer-science-back"
onclick={backToTable}
>
{i18n.t("game.designer.science.action.back")}
</button>
</div>
{:else}
<h2 data-testid="designer-science-title">
{i18n.t("game.designer.science.title.view", { name: viewing.name })}
</h2>
<p class="notice" data-testid="designer-science-notice">
{i18n.t("game.designer.science.read_only_notice")}
</p>
<dl class="fields">
<div class="field">
<dt>{i18n.t("game.designer.science.field.name")}</dt>
<dd data-testid="designer-science-view-name">{viewing.name}</dd>
</div>
<div class="field">
<dt>{i18n.t("game.designer.science.field.drive")}</dt>
<dd data-testid="designer-science-view-drive">
{formatPercent(viewing.drive)}
</dd>
</div>
<div class="field">
<dt>{i18n.t("game.designer.science.field.weapons")}</dt>
<dd data-testid="designer-science-view-weapons">
{formatPercent(viewing.weapons)}
</dd>
</div>
<div class="field">
<dt>{i18n.t("game.designer.science.field.shields")}</dt>
<dd data-testid="designer-science-view-shields">
{formatPercent(viewing.shields)}
</dd>
</div>
<div class="field">
<dt>{i18n.t("game.designer.science.field.cargo")}</dt>
<dd data-testid="designer-science-view-cargo">
{formatPercent(viewing.cargo)}
</dd>
</div>
</dl>
<div class="actions">
<button
type="button"
class="back"
data-testid="designer-science-back"
onclick={backToTable}
>
{i18n.t("game.designer.science.action.back")}
</button>
<button
type="button"
class="delete"
data-testid="designer-science-delete"
disabled={draft === undefined}
onclick={() => void deleteThis()}
>
{i18n.t("game.designer.science.action.delete")}
</button>
</div>
{/if}
{:else}
<h2 data-testid="designer-science-title">
{i18n.t("game.designer.science.title.new")}
</h2>
<p class="hint" data-testid="designer-science-hint">
{i18n.t("game.designer.science.hint.values")}
</p>
<form
class="form"
data-testid="designer-science-form"
onsubmit={(event) => {
event.preventDefault();
void save();
}}
>
<label class="row">
<span>{i18n.t("game.designer.science.field.name")}</span>
<input
type="text"
bind:this={nameInputEl}
bind:value={name}
data-testid="designer-science-input-name"
maxlength="30"
aria-invalid={validation.ok ? "false" : "true"}
/>
</label>
<label class="row">
<span>{i18n.t("game.designer.science.field.drive")}</span>
<input
type="number"
step="0.1"
min="0"
max="100"
bind:value={drive}
data-testid="designer-science-input-drive"
/>
</label>
<label class="row">
<span>{i18n.t("game.designer.science.field.weapons")}</span>
<input
type="number"
step="0.1"
min="0"
max="100"
bind:value={weapons}
data-testid="designer-science-input-weapons"
/>
</label>
<label class="row">
<span>{i18n.t("game.designer.science.field.shields")}</span>
<input
type="number"
step="0.1"
min="0"
max="100"
bind:value={shields}
data-testid="designer-science-input-shields"
/>
</label>
<label class="row">
<span>{i18n.t("game.designer.science.field.cargo")}</span>
<input
type="number"
step="0.1"
min="0"
max="100"
bind:value={cargo}
data-testid="designer-science-input-cargo"
/>
</label>
<p
class="sum"
data-testid="designer-science-sum"
data-sum-ok={validation.ok || (validation.reason !== "sum_not_hundred")
? "true"
: "false"}
>
{i18n.t("game.designer.science.field.sum", { value: sumDisplay })}
</p>
{#if !validation.ok}
<p class="error" data-testid="designer-science-error">
{invalidMessage}
</p>
{/if}
<div class="actions">
<button
type="button"
class="cancel"
data-testid="designer-science-cancel"
onclick={backToTable}
>
{i18n.t("game.designer.science.action.cancel")}
</button>
<button
type="submit"
class="save"
data-testid="designer-science-save"
disabled={!canSave}
title={canSave ? "" : invalidMessage}
>
{i18n.t("game.designer.science.action.save")}
</button>
</div>
</form>
{/if}
</section> </section>
<style> <style>
.active-view { .active-view {
padding: 1.5rem; padding: 1.5rem;
font-family: system-ui, sans-serif; font-family: system-ui, sans-serif;
display: flex;
flex-direction: column;
gap: 0.85rem;
} }
.active-view h2 { .active-view h2 {
margin: 0 0 0.5rem; margin: 0;
font-size: 1.1rem; font-size: 1.1rem;
} }
.active-view p { .notice,
.hint,
.not-found {
margin: 0; 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;
}
.sum {
margin: 0;
font-size: 0.85rem;
color: #aab;
}
.sum[data-sum-ok="false"] {
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> </style>
@@ -0,0 +1,333 @@
<!--
Phase 21 sciences table. Renders the player's defined sciences with
sort, filter, double-tap-to-open-designer, and a per-row Delete
action. Source data is the optimistic overlay
(`RenderedReportSource.report.localScience`) so a freshly queued
`createScience` shows up immediately and a freshly queued
`removeScience` disappears immediately — both before the auto-sync
round-trip lands.
The four tech proportions are stored on the wire as fractions in
`[0, 1]` and surfaced here as percentages with one decimal so the
table matches the designer's input units.
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 { ScienceSummary } 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" | "weapons" | "shields" | "cargo";
type SortDirection = "asc" | "desc";
const COLUMN_LABELS: Record<SortColumn, TranslationKey> = {
name: "game.table.sciences.column.name",
drive: "game.table.sciences.column.drive",
weapons: "game.table.sciences.column.weapons",
shields: "game.table.sciences.column.shields",
cargo: "game.table.sciences.column.cargo",
};
const COLUMNS: readonly SortColumn[] = [
"name",
"drive",
"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 localScience = $derived<ScienceSummary[]>(
rendered?.report?.localScience ?? [],
);
const reportLoaded = $derived(
rendered?.report !== null && rendered?.report !== undefined,
);
const filtered = $derived.by(() => {
const needle = filter.trim().toLowerCase();
if (needle === "") return localScience;
return localScience.filter((sci) =>
sci.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";
}
// Render a fraction in `[0, 1]` as a one-decimal percent
// (`0.225` → `"22.5"`). The conversion is value-only — no `%`
// suffix — so callers can decorate independently.
function formatPercent(fraction: number): string {
return (fraction * 100).toLocaleString(undefined, {
minimumFractionDigits: 0,
maximumFractionDigits: 1,
});
}
function openDesigner(name: string): void {
void goto(`/games/${gameId}/designer/science/${encodeURIComponent(name)}`);
}
function newScience(): void {
void goto(`/games/${gameId}/designer/science`);
}
async function deleteScience(name: string): Promise<void> {
if (draft === undefined) return;
await draft.add({
kind: "removeScience",
id: crypto.randomUUID(),
name,
});
}
</script>
<section
class="active-view"
data-testid="active-view-table"
data-entity="sciences"
>
<header>
<h2>{i18n.t("game.table.sciences.title")}</h2>
<div class="controls">
<input
type="search"
class="filter"
data-testid="sciences-filter"
placeholder={i18n.t("game.table.sciences.filter.placeholder")}
bind:value={filter}
/>
<button
type="button"
class="new"
data-testid="sciences-new"
onclick={newScience}
>
{i18n.t("game.table.sciences.action.new")}
</button>
</div>
</header>
{#if !reportLoaded}
<p class="status" data-testid="sciences-loading">
{i18n.t("game.table.sciences.loading")}
</p>
{:else if localScience.length === 0}
<p class="status" data-testid="sciences-empty">
{i18n.t("game.table.sciences.empty")}
</p>
{:else}
<table class="grid" data-testid="sciences-table">
<thead>
<tr>
{#each COLUMNS as column (column)}
<th aria-sort={ariaSort(column)}>
<button
type="button"
class="sort"
data-testid="sciences-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.sciences.column.actions")}</th>
</tr>
</thead>
<tbody>
{#each sorted as sci (sci.name)}
<tr
data-testid="sciences-row"
data-name={sci.name}
ondblclick={() => openDesigner(sci.name)}
>
<td data-testid="sciences-cell-name">{sci.name}</td>
<td data-testid="sciences-cell-drive">{formatPercent(sci.drive)}</td>
<td data-testid="sciences-cell-weapons">
{formatPercent(sci.weapons)}
</td>
<td data-testid="sciences-cell-shields">
{formatPercent(sci.shields)}
</td>
<td data-testid="sciences-cell-cargo">{formatPercent(sci.cargo)}</td>
<td>
<button
type="button"
class="delete"
data-testid="sciences-delete"
onclick={() => void deleteScience(sci.name)}
>
{i18n.t("game.table.sciences.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>
+9 -5
View File
@@ -1,15 +1,17 @@
<!-- <!--
Active-view router for the per-entity tables. Phase 17 lights up Active-view router for the per-entity tables. Phase 17 lights up
the ship-classes table; the other slugs (planets, ship-groups, the ship-classes table; Phase 21 lights up the sciences table; the
fleets, sciences, races) keep the Phase 10 stub copy until their remaining slugs (planets, ship-groups, fleets, races) keep the
respective phases land. The wrapper preserves Phase 10 stub copy until their respective phases land. The wrapper
`data-testid="active-view-table"` and `data-entity={entity}` for preserves `data-testid="active-view-table"` and
both branches so the navigation e2e specs (`game-shell.spec.ts`, `data-entity={entity}` for every branch (each leaf component
mirrors them) so the navigation e2e specs (`game-shell.spec.ts`,
`view-menu`) keep matching. `view-menu`) keep matching.
--> -->
<script lang="ts"> <script lang="ts">
import { i18n, type TranslationKey } from "$lib/i18n/index.svelte"; import { i18n, type TranslationKey } from "$lib/i18n/index.svelte";
import TableShipClasses from "./table-ship-classes.svelte"; import TableShipClasses from "./table-ship-classes.svelte";
import TableSciences from "./table-sciences.svelte";
type Props = { entity: string }; type Props = { entity: string };
let { entity }: Props = $props(); let { entity }: Props = $props();
@@ -22,6 +24,8 @@ both branches so the navigation e2e specs (`game-shell.spec.ts`,
{#if entity === "ship-classes"} {#if entity === "ship-classes"}
<TableShipClasses /> <TableShipClasses />
{:else if entity === "sciences"}
<TableSciences />
{:else} {:else}
<section <section
class="active-view" class="active-view"
+43
View File
@@ -194,6 +194,8 @@ const en = {
"game.sidebar.order.label.cargo_route_remove": "remove {loadType} route from planet {source}", "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_create": "design ship class {name}",
"game.sidebar.order.label.ship_class_remove": "remove ship class {name}", "game.sidebar.order.label.ship_class_remove": "remove ship class {name}",
"game.sidebar.order.label.science_create": "define science {name}",
"game.sidebar.order.label.science_remove": "remove science {name}",
"game.sidebar.order.label.ship_group_break": "split group {group} → {quantity} ships into new group", "game.sidebar.order.label.ship_group_break": "split group {group} → {quantity} ships into new group",
"game.sidebar.order.label.ship_group_send": "send group {group} → planet {destination}", "game.sidebar.order.label.ship_group_send": "send group {group} → planet {destination}",
"game.sidebar.order.label.ship_group_load": "load {cargo} × {quantity} onto group {group}", "game.sidebar.order.label.ship_group_load": "load {cargo} × {quantity} onto group {group}",
@@ -254,6 +256,47 @@ const en = {
"game.designer.ship_class.preview.cargo_capacity": "cargo capacity per ship", "game.designer.ship_class.preview.cargo_capacity": "cargo capacity per ship",
"game.designer.ship_class.preview.unavailable": "—", "game.designer.ship_class.preview.unavailable": "—",
"game.table.sciences.title": "sciences",
"game.table.sciences.column.name": "name",
"game.table.sciences.column.drive": "drive %",
"game.table.sciences.column.weapons": "weapons %",
"game.table.sciences.column.shields": "shields %",
"game.table.sciences.column.cargo": "cargo %",
"game.table.sciences.column.actions": "actions",
"game.table.sciences.empty": "no sciences defined yet",
"game.table.sciences.filter.placeholder": "filter by name",
"game.table.sciences.action.new": "+ new science",
"game.table.sciences.action.delete": "delete",
"game.table.sciences.loading": "loading sciences…",
"game.designer.science.title.new": "define new science",
"game.designer.science.title.view": "science {name}",
"game.designer.science.field.name": "name",
"game.designer.science.field.drive": "drive %",
"game.designer.science.field.weapons": "weapons %",
"game.designer.science.field.shields": "shields %",
"game.designer.science.field.cargo": "cargo %",
"game.designer.science.field.sum": "sum: {value} % (must equal 100)",
"game.designer.science.action.save": "save",
"game.designer.science.action.cancel": "cancel",
"game.designer.science.action.delete": "delete",
"game.designer.science.action.back": "back",
"game.designer.science.hint.values": "each value is a percent in [0, 100] with one decimal; the four percentages must sum to exactly 100",
"game.designer.science.read_only_notice": "sciences are defined once; values cannot be edited after creation",
"game.designer.science.not_found": "science \"{name}\" does not exist",
"game.designer.science.invalid.empty": "name cannot be empty",
"game.designer.science.invalid.too_long": "name is too long (30 characters max)",
"game.designer.science.invalid.starts_with_special": "name cannot start with a special character",
"game.designer.science.invalid.ends_with_special": "name cannot end with a special character",
"game.designer.science.invalid.consecutive_specials": "too many special characters in a row",
"game.designer.science.invalid.whitespace": "name cannot contain spaces",
"game.designer.science.invalid.disallowed_character": "name contains disallowed characters",
"game.designer.science.invalid.duplicate_name": "a science with this name already exists",
"game.designer.science.invalid.drive_value": "drive % must be in [0, 100]",
"game.designer.science.invalid.weapons_value": "weapons % must be in [0, 100]",
"game.designer.science.invalid.shields_value": "shields % must be in [0, 100]",
"game.designer.science.invalid.cargo_value": "cargo % must be in [0, 100]",
"game.designer.science.invalid.sum_not_hundred": "the four percentages must sum to exactly 100",
"game.inspector.ship_group.kind.local": "your group", "game.inspector.ship_group.kind.local": "your group",
"game.inspector.ship_group.kind.other": "other race group", "game.inspector.ship_group.kind.other": "other race group",
"game.inspector.ship_group.kind.incoming": "incoming group", "game.inspector.ship_group.kind.incoming": "incoming group",
+43
View File
@@ -195,6 +195,8 @@ const ru: Record<keyof typeof en, string> = {
"game.sidebar.order.label.cargo_route_remove": "удалить маршрут {loadType} с планеты {source}", "game.sidebar.order.label.cargo_route_remove": "удалить маршрут {loadType} с планеты {source}",
"game.sidebar.order.label.ship_class_create": "сконструировать класс корабля {name}", "game.sidebar.order.label.ship_class_create": "сконструировать класс корабля {name}",
"game.sidebar.order.label.ship_class_remove": "удалить класс корабля {name}", "game.sidebar.order.label.ship_class_remove": "удалить класс корабля {name}",
"game.sidebar.order.label.science_create": "определить науку {name}",
"game.sidebar.order.label.science_remove": "удалить науку {name}",
"game.sidebar.order.label.ship_group_break": "разделить группу {group} → новая группа из {quantity} кораблей", "game.sidebar.order.label.ship_group_break": "разделить группу {group} → новая группа из {quantity} кораблей",
"game.sidebar.order.label.ship_group_send": "отправить группу {group} → планета {destination}", "game.sidebar.order.label.ship_group_send": "отправить группу {group} → планета {destination}",
"game.sidebar.order.label.ship_group_load": "загрузить {cargo} × {quantity} в группу {group}", "game.sidebar.order.label.ship_group_load": "загрузить {cargo} × {quantity} в группу {group}",
@@ -255,6 +257,47 @@ const ru: Record<keyof typeof en, string> = {
"game.designer.ship_class.preview.cargo_capacity": "грузоподъёмность одного корабля", "game.designer.ship_class.preview.cargo_capacity": "грузоподъёмность одного корабля",
"game.designer.ship_class.preview.unavailable": "—", "game.designer.ship_class.preview.unavailable": "—",
"game.table.sciences.title": "науки",
"game.table.sciences.column.name": "название",
"game.table.sciences.column.drive": "двигатель %",
"game.table.sciences.column.weapons": "оружие %",
"game.table.sciences.column.shields": "защита %",
"game.table.sciences.column.cargo": "трюм %",
"game.table.sciences.column.actions": "действия",
"game.table.sciences.empty": "науки ещё не определены",
"game.table.sciences.filter.placeholder": "фильтр по названию",
"game.table.sciences.action.new": "+ новая наука",
"game.table.sciences.action.delete": "удалить",
"game.table.sciences.loading": "загрузка наук…",
"game.designer.science.title.new": "определение новой науки",
"game.designer.science.title.view": "наука {name}",
"game.designer.science.field.name": "название",
"game.designer.science.field.drive": "двигатель %",
"game.designer.science.field.weapons": "оружие %",
"game.designer.science.field.shields": "защита %",
"game.designer.science.field.cargo": "трюм %",
"game.designer.science.field.sum": "сумма: {value} % (должно быть 100)",
"game.designer.science.action.save": "сохранить",
"game.designer.science.action.cancel": "отмена",
"game.designer.science.action.delete": "удалить",
"game.designer.science.action.back": "назад",
"game.designer.science.hint.values": "каждое значение — процент в [0, 100] с одним знаком после запятой; четыре процента должны давать в сумме ровно 100",
"game.designer.science.read_only_notice": "науки определяются один раз; характеристики нельзя изменить после создания",
"game.designer.science.not_found": "науки \"{name}\" не существует",
"game.designer.science.invalid.empty": "название не может быть пустым",
"game.designer.science.invalid.too_long": "название слишком длинное (максимум 30 символов)",
"game.designer.science.invalid.starts_with_special": "название не может начинаться со спецсимвола",
"game.designer.science.invalid.ends_with_special": "название не может заканчиваться спецсимволом",
"game.designer.science.invalid.consecutive_specials": "слишком много спецсимволов подряд",
"game.designer.science.invalid.whitespace": "название не может содержать пробелы",
"game.designer.science.invalid.disallowed_character": "название содержит недопустимые символы",
"game.designer.science.invalid.duplicate_name": "наука с таким названием уже существует",
"game.designer.science.invalid.drive_value": "двигатель % должен быть в [0, 100]",
"game.designer.science.invalid.weapons_value": "оружие % должно быть в [0, 100]",
"game.designer.science.invalid.shields_value": "защита % должна быть в [0, 100]",
"game.designer.science.invalid.cargo_value": "трюм % должен быть в [0, 100]",
"game.designer.science.invalid.sum_not_hundred": "сумма четырёх процентов должна быть ровно 100",
"game.inspector.ship_group.kind.local": "ваша группа", "game.inspector.ship_group.kind.local": "ваша группа",
"game.inspector.ship_group.kind.other": "группа другой расы", "game.inspector.ship_group.kind.other": "группа другой расы",
"game.inspector.ship_group.kind.incoming": "входящая группа", "game.inspector.ship_group.kind.incoming": "входящая группа",
@@ -16,6 +16,7 @@ dismiss from the IA section §6 land in Phase 35 polish.
ReportOtherShipGroup, ReportOtherShipGroup,
ReportPlanet, ReportPlanet,
ReportRoute, ReportRoute,
ScienceSummary,
ShipClassSummary, ShipClassSummary,
} from "../../api/game-state"; } from "../../api/game-state";
import { i18n } from "$lib/i18n/index.svelte"; import { i18n } from "$lib/i18n/index.svelte";
@@ -24,6 +25,7 @@ dismiss from the IA section §6 land in Phase 35 polish.
type Props = { type Props = {
planet: ReportPlanet | null; planet: ReportPlanet | null;
localShipClass: ShipClassSummary[]; localShipClass: ShipClassSummary[];
localScience: ScienceSummary[];
routes: ReportRoute[]; routes: ReportRoute[];
planets: ReportPlanet[]; planets: ReportPlanet[];
mapWidth: number; mapWidth: number;
@@ -38,6 +40,7 @@ dismiss from the IA section §6 land in Phase 35 polish.
let { let {
planet, planet,
localShipClass, localShipClass,
localScience,
routes, routes,
planets, planets,
mapWidth, mapWidth,
@@ -69,6 +72,7 @@ dismiss from the IA section §6 land in Phase 35 polish.
<Planet <Planet
{planet} {planet}
{localShipClass} {localShipClass}
{localScience}
{routes} {routes}
{planets} {planets}
{mapWidth} {mapWidth}
+4 -1
View File
@@ -19,6 +19,7 @@ field with five buttons.
ReportOtherShipGroup, ReportOtherShipGroup,
ReportPlanet, ReportPlanet,
ReportRoute, ReportRoute,
ScienceSummary,
ShipClassSummary, ShipClassSummary,
} from "../../api/game-state"; } from "../../api/game-state";
import { i18n, type TranslationKey } from "$lib/i18n/index.svelte"; import { i18n, type TranslationKey } from "$lib/i18n/index.svelte";
@@ -37,6 +38,7 @@ field with five buttons.
type Props = { type Props = {
planet: ReportPlanet; planet: ReportPlanet;
localShipClass: ShipClassSummary[]; localShipClass: ShipClassSummary[];
localScience: ScienceSummary[];
routes: ReportRoute[]; routes: ReportRoute[];
planets: ReportPlanet[]; planets: ReportPlanet[];
mapWidth: number; mapWidth: number;
@@ -49,6 +51,7 @@ field with five buttons.
let { let {
planet, planet,
localShipClass, localShipClass,
localScience,
routes, routes,
planets, planets,
mapWidth, mapWidth,
@@ -221,7 +224,7 @@ field with five buttons.
{/if} {/if}
{#if planet.kind === "local"} {#if planet.kind === "local"}
<Production {planet} {localShipClass} /> <Production {planet} {localShipClass} {localScience} />
<CargoRoutes <CargoRoutes
{planet} {planet}
{routes} {routes}
@@ -2,10 +2,11 @@
Phase 15 production-controls subsection of the planet inspector. Phase 15 production-controls subsection of the planet inspector.
Renders four main segments — industry / materials / research / build Renders four main segments — industry / materials / research / build
ship — and reveals a sub-row when the player picks a category that ship — and reveals a sub-row when the player picks a category that
needs a target (research → tech field, build ship → designed class). needs a target (research → tech field or science, build ship →
Every leaf click appends a `setProductionType` command to the local designed class). Every leaf click appends a `setProductionType`
order draft via `OrderDraftStore`; the collapse-by-`planetNumber` command to the local order draft via `OrderDraftStore`; the
rule inside `add` keeps at most one production choice per planet. collapse-by-`planetNumber` rule inside `add` keeps at most one
production choice per planet.
The currently-active segment is derived from `planet.production` The currently-active segment is derived from `planet.production`
through a parser that mirrors the engine's through a parser that mirrors the engine's
@@ -20,11 +21,21 @@ Phase 15 deliberately defers the per-type forecast number — see
`ui/docs/calc-bridge.md` for the gap analysis. The component does `ui/docs/calc-bridge.md` for the gap analysis. The component does
not render forecast text; the existing `freeIndustry` ("free not render forecast text; the existing `freeIndustry` ("free
production") row in the parent inspector is unchanged. production") row in the parent inspector is unchanged.
Phase 21 widens the Research sub-row: in addition to the four tech
buttons the player sees one extra button per defined science from
`localScience`. The active highlight prefers a science-name match
over the four tech display strings, so a science deliberately named
exactly "Drive" / "Weapons" / "Shields" / "Cargo" shadows the
matching tech button (the engine sends a single ambiguous display
string in `planet.production`; user-defined sciences win because
they carry more user intent).
--> -->
<script lang="ts"> <script lang="ts">
import { getContext } from "svelte"; import { getContext } from "svelte";
import type { import type {
ReportPlanet, ReportPlanet,
ScienceSummary,
ShipClassSummary, ShipClassSummary,
} from "../../../api/game-state"; } from "../../../api/game-state";
import { i18n, type TranslationKey } from "$lib/i18n/index.svelte"; import { i18n, type TranslationKey } from "$lib/i18n/index.svelte";
@@ -37,8 +48,9 @@ production") row in the parent inspector is unchanged.
type Props = { type Props = {
planet: ReportPlanet; planet: ReportPlanet;
localShipClass: ShipClassSummary[]; localShipClass: ShipClassSummary[];
localScience: ScienceSummary[];
}; };
let { planet, localShipClass }: Props = $props(); let { planet, localShipClass, localScience }: Props = $props();
type MainSegment = "industry" | "materials" | "research" | "ship"; type MainSegment = "industry" | "materials" | "research" | "ship";
@@ -49,9 +61,12 @@ production") row in the parent inspector is unchanged.
let expandedMain: MainSegment | null = $state(null); let expandedMain: MainSegment | null = $state(null);
const parsedMain = $derived(parseMain(planet.production, localShipClass)); const parsedMain = $derived(
parseMain(planet.production, localShipClass, localScience),
);
const selectedMain = $derived(expandedMain ?? parsedMain); const selectedMain = $derived(expandedMain ?? parsedMain);
const activeResearch = $derived(parseResearch(planet.production)); const activeResearch = $derived(parseResearch(planet.production, localScience));
const activeScience = $derived(parseScience(planet.production, localScience));
const activeShip = $derived(parseShip(planet.production, localShipClass)); const activeShip = $derived(parseShip(planet.production, localShipClass));
$effect(() => { $effect(() => {
@@ -92,8 +107,13 @@ production") row in the parent inspector is unchanged.
function parseMain( function parseMain(
value: string | null, value: string | null,
classes: ShipClassSummary[], classes: ShipClassSummary[],
sciences: ScienceSummary[],
): MainSegment | null { ): MainSegment | null {
if (value === null || value === "" || value === "-") return null; if (value === null || value === "" || value === "-") return null;
// Sciences first: a user-named "Drive" science wins over the
// Drive tech display string. If no science matches, fall through
// to tech / ship class detection.
if (sciences.some((s) => s.name === value)) return "research";
switch (value) { switch (value) {
case "Capital": case "Capital":
return "industry"; return "industry";
@@ -108,7 +128,14 @@ production") row in the parent inspector is unchanged.
return classes.some((c) => c.name === value) ? "ship" : null; return classes.some((c) => c.name === value) ? "ship" : null;
} }
function parseResearch(value: string | null): ProductionType | null { function parseResearch(
value: string | null,
sciences: ScienceSummary[],
): ProductionType | null {
// A science name shadows the four tech display strings — when a
// science matches we surface no tech-button highlight so the
// science button gets the active styling instead.
if (value !== null && sciences.some((s) => s.name === value)) return null;
switch (value) { switch (value) {
case "Drive": case "Drive":
return "DRIVE"; return "DRIVE";
@@ -123,6 +150,14 @@ production") row in the parent inspector is unchanged.
} }
} }
function parseScience(
value: string | null,
sciences: ScienceSummary[],
): string | null {
if (value === null || value === "") return null;
return sciences.some((s) => s.name === value) ? value : null;
}
function parseShip( function parseShip(
value: string | null, value: string | null,
classes: ShipClassSummary[], classes: ShipClassSummary[],
@@ -150,6 +185,11 @@ production") row in the parent inspector is unchanged.
expandedMain = null; expandedMain = null;
} }
function clickScience(name: string): void {
void emit("SCIENCE", name);
expandedMain = null;
}
function clickShip(name: string): void { function clickShip(name: string): void {
void emit("SHIP", name); void emit("SHIP", name);
expandedMain = null; expandedMain = null;
@@ -231,6 +271,18 @@ production") row in the parent inspector is unchanged.
{i18n.t(option.labelKey)} {i18n.t(option.labelKey)}
</button> </button>
{/each} {/each}
{#each localScience as sci (sci.name)}
<button
type="button"
class="sub-seg"
class:active={activeScience === sci.name}
data-testid={`inspector-planet-production-science-${sci.name}`}
disabled={disabled}
onclick={() => clickScience(sci.name)}
>
{sci.name}
</button>
{/each}
</div> </div>
{/if} {/if}
@@ -82,6 +82,7 @@ from the Phase 10 stub.
const localShipClass = $derived( const localShipClass = $derived(
renderedReport?.report?.localShipClass ?? [], renderedReport?.report?.localShipClass ?? [],
); );
const localScience = $derived(renderedReport?.report?.localScience ?? []);
const allPlanets = $derived(renderedReport?.report?.planets ?? []); const allPlanets = $derived(renderedReport?.report?.planets ?? []);
const routes = $derived(renderedReport?.report?.routes ?? []); const routes = $derived(renderedReport?.report?.routes ?? []);
const mapWidth = $derived(renderedReport?.report?.mapWidth ?? 1); const mapWidth = $derived(renderedReport?.report?.mapWidth ?? 1);
@@ -114,6 +115,7 @@ from the Phase 10 stub.
<Planet <Planet
planet={selectedPlanet} planet={selectedPlanet}
{localShipClass} {localShipClass}
{localScience}
{routes} {routes}
planets={allPlanets} planets={allPlanets}
{mapWidth} {mapWidth}
@@ -77,6 +77,14 @@ Tests exercise the tab through `__galaxyDebug.seedOrderDraft`
return i18n.t("game.sidebar.order.label.ship_class_remove", { return i18n.t("game.sidebar.order.label.ship_class_remove", {
name: cmd.name, name: cmd.name,
}); });
case "createScience":
return i18n.t("game.sidebar.order.label.science_create", {
name: cmd.name,
});
case "removeScience":
return i18n.t("game.sidebar.order.label.science_remove", {
name: cmd.name,
});
case "breakShipGroup": case "breakShipGroup":
return i18n.t("game.sidebar.order.label.ship_group_break", { return i18n.t("game.sidebar.order.label.ship_group_break", {
group: shortGroupId(cmd.groupId), group: shortGroupId(cmd.groupId),
@@ -0,0 +1,187 @@
// Validates a science draft and converts it to the wire-stable
// fraction form. Phase 21 mirrors the engine's
// `pkg/calc/validator.go.ValidateScienceValues` plus the
// `validateEntityName` rules and a UX-only duplicate-name check.
//
// The designer composes percentages (each value in `[0, 100]`, sum
// equal to `100` within float tolerance) so the user can type and
// reason about whole-number proportions; the validator converts the
// percentages to fractions (`value / 100`) on success so the
// `OrderCommand` payload always carries the canonical `[0, 1]`
// summing to `1.0` shape the FBS encoder ships on the wire.
//
// Engine rules (from `pkg/calc/validator.go` and `game/rules.txt`):
//
// - drive, weapons, shields, cargo: float in `[0, 1]`;
// - the four values sum to `1.0` (the engine accepts a small
// tolerance to absorb float rounding);
// - name must satisfy `validateEntityName`
// (`pkg/util/string.go.ValidateTypeName`).
//
// The designer's UI gate is stricter than the engine's: the four
// percent inputs use `step="0.1"` and the validator refuses anything
// outside `Math.abs(sum - 100) < SUM_EPSILON_PERCENT`. Snapping to one
// decimal at input time makes the float drift small enough that the
// epsilon below comfortably covers normal arithmetic without ever
// admitting a draft the engine would reject.
//
// 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";
/**
* SUM_EPSILON_PERCENT is the tolerance applied when checking that the
* four science percentages sum to exactly `100`. With one-decimal
* inputs (`step="0.1"`) the maximum cumulative float drift across four
* additions is well under `1e-6`; `1e-3` keeps the check robust to
* any float arithmetic the browser might do without ever accepting a
* sum that rounds to a value the engine would refuse.
*/
export const SUM_EPSILON_PERCENT = 1e-3;
/**
* ScienceInvalidReason enumerates every reason `validateScience` 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 ScienceInvalidReason =
| EntityNameInvalidReason
| "duplicate_name"
| "drive_value"
| "weapons_value"
| "shields_value"
| "cargo_value"
| "sum_not_hundred";
/**
* ScienceDraft is the structural shape the designer composes. The
* four numeric fields carry the player-typed percentages verbatim
* (each in `[0, 100]`); `validateScience` is responsible for refusing
* non-finite or out-of-range entries and the off-by-sum case.
*/
export interface ScienceDraft {
name: string;
drive: number;
weapons: number;
shields: number;
cargo: number;
}
/**
* ScienceValue is the canonical form a `createScience` order carries
* on the wire: `drive`, `weapons`, `shields`, and `cargo` are
* fractions in `[0, 1]` summing to `1.0`. Convert back to percentages
* with `fractionsToPercent`.
*/
export interface ScienceValue {
name: string;
drive: number;
weapons: number;
shields: number;
cargo: number;
}
export type ScienceValidation =
| { ok: true; value: ScienceValue }
| { ok: false; reason: ScienceInvalidReason };
/**
* validateScience runs the entity-name rules, the per-percent range
* check, and the sum-equals-100 gate. `existingNames` is the
* optimistic projection of already-defined sciences (from
* `localScience` 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, and for the order-draft store's
* post-add status recompute (which sees rolling-up duplicates as
* normal because the engine arbitrates them at submit time).
*/
export function validateScience(
draft: ScienceDraft,
options: { existingNames?: readonly string[] } = {},
): ScienceValidation {
const nameResult = validateEntityName(draft.name);
if (!nameResult.ok) {
return { ok: false, reason: nameResult.reason };
}
const trimmedName = nameResult.value;
if (!isValidPercent(draft.drive)) {
return { ok: false, reason: "drive_value" };
}
if (!isValidPercent(draft.weapons)) {
return { ok: false, reason: "weapons_value" };
}
if (!isValidPercent(draft.shields)) {
return { ok: false, reason: "shields_value" };
}
if (!isValidPercent(draft.cargo)) {
return { ok: false, reason: "cargo_value" };
}
const sum = draft.drive + draft.weapons + draft.shields + draft.cargo;
if (Math.abs(sum - 100) >= SUM_EPSILON_PERCENT) {
return { ok: false, reason: "sum_not_hundred" };
}
const existing = options.existingNames ?? [];
if (existing.some((existingName) => existingName === trimmedName)) {
return { ok: false, reason: "duplicate_name" };
}
return {
ok: true,
value: {
name: trimmedName,
drive: draft.drive / 100,
weapons: draft.weapons / 100,
shields: draft.shields / 100,
cargo: draft.cargo / 100,
},
};
}
/**
* fractionsToPercent inverts `validateScience`'s percent→fraction
* conversion: it takes a wire-stable `[0, 1]` quartet and returns a
* `[0, 100]` percentage quartet. The view-mode designer uses it to
* render an existing science back as the same percent values the
* player originally typed.
*/
export function fractionsToPercent(value: {
drive: number;
weapons: number;
shields: number;
cargo: number;
}): { drive: number; weapons: number; shields: number; cargo: number } {
return {
drive: value.drive * 100,
weapons: value.weapons * 100,
shields: value.shields * 100,
cargo: value.cargo * 100,
};
}
/**
* isValidPercent guards a single percent input. Each value must be a
* finite number in `[0, 100]`; NaN, infinity, and negative or
* over-100 entries are rejected. The designer's `step="0.1"` input
* keeps users on the one-decimal grid, but the validator does not
* round here — sub-decimal precision is harmless because the
* sum-equals-100 gate already absorbs any float drift the
* `SUM_EPSILON_PERCENT` allows.
*/
function isValidPercent(value: number): boolean {
if (!Number.isFinite(value)) return false;
return value >= 0 && value <= 100;
}
@@ -173,6 +173,7 @@ fresh.
const localShipClass = $derived( const localShipClass = $derived(
renderedReport.report?.localShipClass ?? [], renderedReport.report?.localShipClass ?? [],
); );
const localScience = $derived(renderedReport.report?.localScience ?? []);
const inspectorPlanets = $derived(renderedReport.report?.planets ?? []); const inspectorPlanets = $derived(renderedReport.report?.planets ?? []);
const inspectorRoutes = $derived(renderedReport.report?.routes ?? []); const inspectorRoutes = $derived(renderedReport.report?.routes ?? []);
const inspectorMapWidth = $derived(renderedReport.report?.mapWidth ?? 1); const inspectorMapWidth = $derived(renderedReport.report?.mapWidth ?? 1);
@@ -341,6 +342,7 @@ fresh.
<PlanetSheet <PlanetSheet
planet={selectedPlanet} planet={selectedPlanet}
{localShipClass} {localShipClass}
{localScience}
routes={inspectorRoutes} routes={inspectorRoutes}
planets={inspectorPlanets} planets={inspectorPlanets}
mapWidth={inspectorMapWidth} mapWidth={inspectorMapWidth}
@@ -33,6 +33,7 @@ import {
import { submitOrder } from "./submit"; import { submitOrder } from "./submit";
import { validateEntityName } from "$lib/util/entity-name"; import { validateEntityName } from "$lib/util/entity-name";
import { validateShipClass } from "$lib/util/ship-class-validation"; import { validateShipClass } from "$lib/util/ship-class-validation";
import { validateScience } from "$lib/util/science-validation";
const NAMESPACE = "order-drafts"; const NAMESPACE = "order-drafts";
const draftKey = (gameId: string): string => `${gameId}/draft`; const draftKey = (gameId: string): string => `${gameId}/draft`;
@@ -518,6 +519,27 @@ function validateCommand(cmd: OrderCommand): CommandStatus {
// active production / ship groups. Local validation only // active production / ship groups. Local validation only
// guards the name shape. // guards the name shape.
return validateEntityName(cmd.name).ok ? "valid" : "invalid"; return validateEntityName(cmd.name).ok ? "valid" : "invalid";
case "createScience":
// Mirrors `pkg/calc/validator.go.ValidateScienceValues`
// plus the entity-name rules. The wire shape is fractions
// (sum to 1.0); the validator runs without `existingNames`
// here for the same reason ship-class create does — a
// duplicate-name check is the designer's UX responsibility,
// not the draft store's.
return validateScience({
name: cmd.name,
drive: cmd.drive * 100,
weapons: cmd.weapons * 100,
shields: cmd.shields * 100,
cargo: cmd.cargo * 100,
}).ok
? "valid"
: "invalid";
case "removeScience":
// `removeScience` carries only the name; the engine checks
// that the science exists and is not referenced by active
// production. Local validation only guards the name shape.
return validateEntityName(cmd.name).ok ? "valid" : "invalid";
case "breakShipGroup": case "breakShipGroup":
// Engine rule (`controller/ship_group.go.breakGroup`): // Engine rule (`controller/ship_group.go.breakGroup`):
// quantity must be at least 1 and strictly less than the // quantity must be at least 1 and strictly less than the
+24
View File
@@ -16,6 +16,8 @@ import {
CommandPlanetRename, CommandPlanetRename,
CommandPlanetRouteRemove, CommandPlanetRouteRemove,
CommandPlanetRouteSet, CommandPlanetRouteSet,
CommandScienceCreate,
CommandScienceRemove,
CommandShipClassCreate, CommandShipClassCreate,
CommandShipClassRemove, CommandShipClassRemove,
CommandShipGroupBreak, CommandShipGroupBreak,
@@ -234,6 +236,28 @@ function decodeCommand(item: CommandItemView): OrderCommand | null {
name: inner.name() ?? "", name: inner.name() ?? "",
}; };
} }
case CommandPayload.CommandScienceCreate: {
const inner = new CommandScienceCreate();
item.payload(inner);
return {
kind: "createScience",
id,
name: inner.name() ?? "",
drive: inner.drive(),
weapons: inner.weapons(),
shields: inner.shields(),
cargo: inner.cargo(),
};
}
case CommandPayload.CommandScienceRemove: {
const inner = new CommandScienceRemove();
item.payload(inner);
return {
kind: "removeScience",
id,
name: inner.name() ?? "",
};
}
case CommandPayload.CommandShipGroupBreak: { case CommandPayload.CommandShipGroupBreak: {
const inner = new CommandShipGroupBreak(); const inner = new CommandShipGroupBreak();
item.payload(inner); item.payload(inner);
+42
View File
@@ -166,6 +166,46 @@ export interface RemoveShipClassCommand {
readonly name: string; readonly name: string;
} }
/**
* CreateScienceCommand defines a new science — a named mix of four
* tech proportions (`drive`, `weapons`, `shields`, `cargo`) that sums
* to 1.0. The TS-side mirror lives in `lib/util/science-validation.ts`;
* the designer enters the values as percentages (0..100) with a
* strict sum-equals-100 gate and converts them to fractions on
* dispatch, so wire entries always satisfy the engine's
* `pkg/calc/validator.go.ValidateScienceValues` invariant
* (every value in `[0, 1]`, sum `≈ 1.0` within float tolerance).
*
* No collapse rule applies — each create is a distinct user-visible
* action and the engine refuses duplicate names server-side
* (`game/internal/controller/science.go.scienceCreate`). Editing an
* existing science means dispatching a `removeScience` first and
* then a `createScience` with the new payload; there is no
* `UpdateScience` on the wire (Phase 21 decision).
*/
export interface CreateScienceCommand {
readonly kind: "createScience";
readonly id: string;
readonly name: string;
readonly drive: number;
readonly weapons: number;
readonly shields: number;
readonly cargo: number;
}
/**
* RemoveScienceCommand drops a defined science by name. The engine
* refuses removals when the science is referenced by an active planet
* production target (`game/internal/controller/science.go.scienceRemove`)
* — that surfaces as `cmdApplied=false` on the response and the order
* tab row reads `rejected`.
*/
export interface RemoveScienceCommand {
readonly kind: "removeScience";
readonly id: string;
readonly name: string;
}
/** /**
* ShipGroupCargo mirrors the engine `ShipGroupCargo` enum * ShipGroupCargo mirrors the engine `ShipGroupCargo` enum
* (`pkg/schema/fbs/order.fbs`). Three values: colonists, capital * (`pkg/schema/fbs/order.fbs`). Three values: colonists, capital
@@ -383,6 +423,8 @@ export type OrderCommand =
| RemoveCargoRouteCommand | RemoveCargoRouteCommand
| CreateShipClassCommand | CreateShipClassCommand
| RemoveShipClassCommand | RemoveShipClassCommand
| CreateScienceCommand
| RemoveScienceCommand
| BreakShipGroupCommand | BreakShipGroupCommand
| SendShipGroupCommand | SendShipGroupCommand
| LoadShipGroupCommand | LoadShipGroupCommand
+28
View File
@@ -31,6 +31,8 @@ import {
CommandPlanetRename, CommandPlanetRename,
CommandPlanetRouteRemove, CommandPlanetRouteRemove,
CommandPlanetRouteSet, CommandPlanetRouteSet,
CommandScienceCreate,
CommandScienceRemove,
CommandShipClassCreate, CommandShipClassCreate,
CommandShipClassRemove, CommandShipClassRemove,
CommandShipGroupBreak, CommandShipGroupBreak,
@@ -234,6 +236,32 @@ function encodeCommandPayload(
payloadOffset: offset, payloadOffset: offset,
}; };
} }
case "createScience": {
const nameOffset = builder.createString(cmd.name);
const offset = CommandScienceCreate.createCommandScienceCreate(
builder,
nameOffset,
cmd.drive,
cmd.weapons,
cmd.shields,
cmd.cargo,
);
return {
payloadType: CommandPayload.CommandScienceCreate,
payloadOffset: offset,
};
}
case "removeScience": {
const nameOffset = builder.createString(cmd.name);
const offset = CommandScienceRemove.createCommandScienceRemove(
builder,
nameOffset,
);
return {
payloadType: CommandPayload.CommandScienceRemove,
payloadOffset: offset,
};
}
case "breakShipGroup": { case "breakShipGroup": {
const idOffset = builder.createString(cmd.groupId); const idOffset = builder.createString(cmd.groupId);
const newIdOffset = builder.createString(cmd.newGroupId); const newIdOffset = builder.createString(cmd.newGroupId);
+302
View File
@@ -0,0 +1,302 @@
// Vitest coverage for the Phase 21 science 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, ScienceSummary } 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";
import { EMPTY_SHIP_GROUPS } from "./helpers/empty-ship-groups";
const GAME_ID = "11111111-2222-3333-4444-555555555555";
const pageMock = vi.hoisted(() => ({
url: new URL("http://localhost/games/g1/designer/science"),
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 DesignerScience from "../src/lib/active-view/designer-science.svelte";
let db: IDBPDatabase<GalaxyDB>;
let dbName: string;
let cache: Cache;
let draft: OrderDraftStore;
beforeEach(async () => {
dbName = `galaxy-designer-science-${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 science(
overrides: Partial<ScienceSummary> & Pick<ScienceSummary, "name">,
): ScienceSummary {
return {
drive: 0,
weapons: 0,
shields: 0,
cargo: 0,
...overrides,
};
}
function makeReport(localScience: ScienceSummary[] = []): GameReport {
return {
turn: 1,
mapWidth: 1000,
mapHeight: 1000,
planetCount: 0,
planets: [],
race: "",
localShipClass: [],
routes: [],
localPlayerDrive: 0,
localPlayerWeapons: 0,
localPlayerShields: 0,
localPlayerCargo: 0,
...EMPTY_SHIP_GROUPS,
localScience,
};
}
function mountDesigner(opts: {
scienceId?: string;
report?: GameReport | null;
}) {
const report = opts.report ?? makeReport();
pageMock.params = opts.scienceId
? { id: "g1", scienceId: opts.scienceId }
: { 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(DesignerScience, { context });
}
describe("science designer (new mode)", () => {
test("renders the form with Save disabled by default (empty name + zero sum)", () => {
const ui = mountDesigner({});
expect(ui.getByTestId("active-view-designer-science")).toHaveAttribute(
"data-mode",
"new",
);
expect(ui.getByTestId("designer-science-save")).toBeDisabled();
expect(ui.getByTestId("designer-science-error")).toHaveTextContent(
"name cannot be empty",
);
});
test("Save adds a createScience to the draft after a valid edit", async () => {
const ui = mountDesigner({});
await fireEvent.input(ui.getByTestId("designer-science-input-name"), {
target: { value: "Even" },
});
await fireEvent.input(ui.getByTestId("designer-science-input-drive"), {
target: { value: "25" },
});
await fireEvent.input(ui.getByTestId("designer-science-input-weapons"), {
target: { value: "25" },
});
await fireEvent.input(ui.getByTestId("designer-science-input-shields"), {
target: { value: "25" },
});
await fireEvent.input(ui.getByTestId("designer-science-input-cargo"), {
target: { value: "25" },
});
await waitFor(() =>
expect(ui.getByTestId("designer-science-save")).not.toBeDisabled(),
);
await fireEvent.click(ui.getByTestId("designer-science-save"));
await waitFor(() => expect(draft.commands).toHaveLength(1));
const cmd = draft.commands[0]!;
if (cmd.kind !== "createScience") throw new Error("wrong kind");
expect(cmd.name).toBe("Even");
expect(cmd.drive).toBeCloseTo(0.25, 12);
expect(cmd.weapons).toBeCloseTo(0.25, 12);
expect(cmd.shields).toBeCloseTo(0.25, 12);
expect(cmd.cargo).toBeCloseTo(0.25, 12);
await waitFor(() =>
expect(gotoMock).toHaveBeenCalledWith("/games/g1/table/sciences"),
);
});
test("sum readout reflects the live total", async () => {
const ui = mountDesigner({});
await fireEvent.input(ui.getByTestId("designer-science-input-drive"), {
target: { value: "30" },
});
await fireEvent.input(ui.getByTestId("designer-science-input-weapons"), {
target: { value: "20" },
});
await waitFor(() =>
expect(ui.getByTestId("designer-science-sum")).toHaveTextContent("50"),
);
});
test("rejects sum that does not equal 100", async () => {
const ui = mountDesigner({});
await fireEvent.input(ui.getByTestId("designer-science-input-name"), {
target: { value: "Bad" },
});
await fireEvent.input(ui.getByTestId("designer-science-input-drive"), {
target: { value: "50" },
});
await waitFor(() =>
expect(ui.getByTestId("designer-science-error")).toHaveTextContent(
"must sum to exactly 100",
),
);
expect(ui.getByTestId("designer-science-save")).toBeDisabled();
});
test("rejects a duplicate name from the overlay before any sync", async () => {
const ui = mountDesigner({
report: makeReport([
science({ name: "Even", drive: 0.25, weapons: 0.25, shields: 0.25, cargo: 0.25 }),
]),
});
await fireEvent.input(ui.getByTestId("designer-science-input-name"), {
target: { value: "Even" },
});
await fireEvent.input(ui.getByTestId("designer-science-input-drive"), {
target: { value: "25" },
});
await fireEvent.input(ui.getByTestId("designer-science-input-weapons"), {
target: { value: "25" },
});
await fireEvent.input(ui.getByTestId("designer-science-input-shields"), {
target: { value: "25" },
});
await fireEvent.input(ui.getByTestId("designer-science-input-cargo"), {
target: { value: "25" },
});
await waitFor(() =>
expect(ui.getByTestId("designer-science-error")).toHaveTextContent(
"already exists",
),
);
expect(ui.getByTestId("designer-science-save")).toBeDisabled();
});
test("Cancel navigates back without mutating the draft", async () => {
const ui = mountDesigner({});
await fireEvent.click(ui.getByTestId("designer-science-cancel"));
expect(draft.commands).toHaveLength(0);
expect(gotoMock).toHaveBeenCalledWith("/games/g1/table/sciences");
});
});
describe("science designer (view mode)", () => {
test("renders the read-only summary plus Delete + Back affordances", () => {
const ui = mountDesigner({
scienceId: "FirstStep",
report: makeReport([
science({
name: "FirstStep",
drive: 0.222,
weapons: 0.111,
shields: 0.667,
cargo: 0,
}),
]),
});
expect(ui.getByTestId("active-view-designer-science")).toHaveAttribute(
"data-mode",
"view",
);
expect(ui.getByTestId("designer-science-view-name")).toHaveTextContent(
"FirstStep",
);
expect(ui.getByTestId("designer-science-view-drive")).toHaveTextContent(
"22.2",
);
expect(ui.getByTestId("designer-science-view-shields")).toHaveTextContent(
"66.7",
);
expect(ui.getByTestId("designer-science-delete")).toBeInTheDocument();
expect(ui.getByTestId("designer-science-back")).toBeInTheDocument();
});
test("Delete adds a removeScience and navigates back", async () => {
const ui = mountDesigner({
scienceId: "FirstStep",
report: makeReport([
science({ name: "FirstStep", drive: 0.5, shields: 0.5 }),
]),
});
await fireEvent.click(ui.getByTestId("designer-science-delete"));
await waitFor(() => expect(draft.commands).toHaveLength(1));
const cmd = draft.commands[0]!;
if (cmd.kind !== "removeScience") throw new Error("wrong kind");
expect(cmd.name).toBe("FirstStep");
await waitFor(() =>
expect(gotoMock).toHaveBeenCalledWith("/games/g1/table/sciences"),
);
});
test("renders a not-found message when the science is missing from the overlay", () => {
const ui = mountDesigner({
scienceId: "Ghost",
report: makeReport([]),
});
expect(ui.getByTestId("designer-science-not-found")).toHaveTextContent(
"Ghost",
);
});
});
+41 -1
View File
@@ -16,6 +16,8 @@ import {
CommandPlanetRename, CommandPlanetRename,
CommandPlanetRouteRemove, CommandPlanetRouteRemove,
CommandPlanetRouteSet, CommandPlanetRouteSet,
CommandScienceCreate,
CommandScienceRemove,
CommandShipClassCreate, CommandShipClassCreate,
CommandShipClassRemove, CommandShipClassRemove,
PlanetProduction, PlanetProduction,
@@ -82,13 +84,29 @@ export interface RemoveShipClassResultFixture extends CommandResultFixtureBase {
name: string; name: string;
} }
export interface CreateScienceResultFixture extends CommandResultFixtureBase {
kind: "createScience";
name: string;
drive: number;
weapons: number;
shields: number;
cargo: number;
}
export interface RemoveScienceResultFixture extends CommandResultFixtureBase {
kind: "removeScience";
name: string;
}
export type CommandResultFixture = export type CommandResultFixture =
| PlanetRenameResultFixture | PlanetRenameResultFixture
| SetProductionTypeResultFixture | SetProductionTypeResultFixture
| SetCargoRouteResultFixture | SetCargoRouteResultFixture
| RemoveCargoRouteResultFixture | RemoveCargoRouteResultFixture
| CreateShipClassResultFixture | CreateShipClassResultFixture
| RemoveShipClassResultFixture; | RemoveShipClassResultFixture
| CreateScienceResultFixture
| RemoveScienceResultFixture;
export function buildOrderResponsePayload( export function buildOrderResponsePayload(
gameId: string, gameId: string,
@@ -215,6 +233,28 @@ function encodeItem(builder: Builder, c: CommandResultFixture): number {
payloadType = CommandPayload.CommandShipClassRemove; payloadType = CommandPayload.CommandShipClassRemove;
break; break;
} }
case "createScience": {
const nameOffset = builder.createString(c.name);
inner = CommandScienceCreate.createCommandScienceCreate(
builder,
nameOffset,
c.drive,
c.weapons,
c.shields,
c.cargo,
);
payloadType = CommandPayload.CommandScienceCreate;
break;
}
case "removeScience": {
const nameOffset = builder.createString(c.name);
inner = CommandScienceRemove.createCommandScienceRemove(
builder,
nameOffset,
);
payloadType = CommandPayload.CommandScienceRemove;
break;
}
} }
CommandItem.startCommandItem(builder); CommandItem.startCommandItem(builder);
CommandItem.addCmdId(builder, cmdIdOffset); CommandItem.addCmdId(builder, cmdIdOffset);
+30 -2
View File
@@ -11,8 +11,9 @@
// against realistic values. Phase 15 adds a minimal `LocalShipClass` // against realistic values. Phase 15 adds a minimal `LocalShipClass`
// projection so the planet inspector's Build-Ship sub-picker has data // projection so the planet inspector's Build-Ship sub-picker has data
// in e2e specs (`name` only — Phase 17 widens this when ship-class // in e2e specs (`name` only — Phase 17 widens this when ship-class
// CRUD lands). Later phases extend the helper as fleets, sciences, // CRUD lands). Phase 21 adds a `LocalScience` projection so the
// etc. land. // sciences table and the planet production picker's Research sub-row
// have data in e2e specs.
import { Builder } from "flatbuffers"; import { Builder } from "flatbuffers";
@@ -23,6 +24,7 @@ import {
Report, Report,
Route, Route,
RouteEntry, RouteEntry,
Science,
ShipClass, ShipClass,
UnidentifiedPlanet, UnidentifiedPlanet,
UninhabitedPlanet, UninhabitedPlanet,
@@ -60,6 +62,14 @@ export interface ShipClassFixture {
cargo?: number; cargo?: number;
} }
export interface ScienceFixture {
name: string;
drive?: number;
weapons?: number;
shields?: number;
cargo?: number;
}
export interface PlayerFixture { export interface PlayerFixture {
name: string; name: string;
drive?: number; drive?: number;
@@ -84,6 +94,7 @@ export interface ReportFixture {
uninhabitedPlanets?: PlanetFixture[]; uninhabitedPlanets?: PlanetFixture[];
unidentifiedPlanets?: { number: number; x: number; y: number }[]; unidentifiedPlanets?: { number: number; x: number; y: number }[];
localShipClass?: ShipClassFixture[]; localShipClass?: ShipClassFixture[];
localScience?: ScienceFixture[];
race?: string; race?: string;
players?: PlayerFixture[]; players?: PlayerFixture[];
routes?: RouteFixture[]; routes?: RouteFixture[];
@@ -178,6 +189,17 @@ export function buildReportPayload(fixture: ReportFixture): Uint8Array {
return ShipClass.endShipClass(builder); return ShipClass.endShipClass(builder);
}); });
const localScienceOffsets = (fixture.localScience ?? []).map((sci) => {
const name = builder.createString(sci.name);
Science.startScience(builder);
Science.addName(builder, name);
Science.addDrive(builder, sci.drive ?? 0);
Science.addWeapons(builder, sci.weapons ?? 0);
Science.addShields(builder, sci.shields ?? 0);
Science.addCargo(builder, sci.cargo ?? 0);
return Science.endScience(builder);
});
const playerOffsets = (fixture.players ?? []).map((p) => { const playerOffsets = (fixture.players ?? []).map((p) => {
const name = builder.createString(p.name); const name = builder.createString(p.name);
Player.startPlayer(builder); Player.startPlayer(builder);
@@ -221,6 +243,10 @@ export function buildReportPayload(fixture: ReportFixture): Uint8Array {
localShipClassOffsets.length === 0 localShipClassOffsets.length === 0
? null ? null
: Report.createLocalShipClassVector(builder, localShipClassOffsets); : Report.createLocalShipClassVector(builder, localShipClassOffsets);
const localScienceVec =
localScienceOffsets.length === 0
? null
: Report.createLocalScienceVector(builder, localScienceOffsets);
const playerVec = const playerVec =
playerOffsets.length === 0 playerOffsets.length === 0
? null ? null
@@ -251,6 +277,8 @@ export function buildReportPayload(fixture: ReportFixture): Uint8Array {
if (unidentifiedVec !== null) Report.addUnidentifiedPlanet(builder, unidentifiedVec); if (unidentifiedVec !== null) Report.addUnidentifiedPlanet(builder, unidentifiedVec);
if (localShipClassVec !== null) if (localShipClassVec !== null)
Report.addLocalShipClass(builder, localShipClassVec); Report.addLocalShipClass(builder, localShipClassVec);
if (localScienceVec !== null)
Report.addLocalScience(builder, localScienceVec);
if (routeVec !== null) Report.addRoute(builder, routeVec); if (routeVec !== null) Report.addRoute(builder, routeVec);
const reportOff = Report.endReport(builder); const reportOff = Report.endReport(builder);
builder.finish(reportOff); builder.finish(reportOff);
+423
View File
@@ -0,0 +1,423 @@
// Phase 21 end-to-end coverage for the science CRUD flow + the
// production-picker integration. Boots an authenticated session,
// mocks the gateway with a single local planet plus an empty
// `localScience` projection, navigates to the sciences table, opens
// the designer, fills the form (four percentages summing to 100),
// and asserts that:
//
// 1. Save adds a `createScience` row to the local order draft,
// auto-syncs through `user.games.order`, and the new science
// 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 (sum-not-100 + duplicate name);
// 3. setting a planet's production to the new science via the
// Research sub-row of the planet inspector dispatches
// `setProductionType("SCIENCE", <name>)` and the optimistic
// overlay flips the planet's production string immediately;
// 4. Delete on a row adds a `removeScience` and the science
// disappears from the table; the order tab reflects both rows.
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,
CommandPlanetProduce,
CommandScienceCreate,
CommandScienceRemove,
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 ScienceFixture,
} from "./fixtures/report-fbs";
import {
buildOrderGetResponsePayload,
buildOrderResponsePayload,
type CommandResultFixture,
} from "./fixtures/order-fbs";
const SESSION_ID = "phase-21-sciences-session";
const GAME_ID = "21212121-2121-2121-2121-212121212121";
interface MockOpts {
createOutcome: "applied" | "rejected";
initialSciences?: ScienceFixture[];
}
interface MockHandle {
get lastCreate(): {
name: string;
drive: number;
weapons: number;
shields: number;
cargo: number;
} | null;
get lastRemove(): { name: string } | null;
get lastProduce(): {
planetNumber: number;
productionType: string;
subject: string;
} | null;
}
async function mockGateway(page: Page, opts: MockOpts): Promise<MockHandle> {
const game: GameFixture = {
gameId: GAME_ID,
gameName: "Phase 21 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 lastProduce: MockHandle["lastProduce"] = null;
const reportSciences: ScienceFixture[] = [...(opts.initialSciences ?? [])];
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: 2000,
y: 2000,
size: 1000,
resources: 5,
population: 800,
industry: 600,
},
],
localScience: reportSciences,
});
break;
}
case "user.games.order": {
const decoded = UserGamesOrder.getRootAsUserGamesOrder(
new ByteBuffer(req.payloadBytes),
);
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.CommandScienceCreate) {
const inner = new CommandScienceCreate();
item.payload(inner);
lastCreate = {
name: inner.name() ?? "",
drive: inner.drive(),
weapons: inner.weapons(),
shields: inner.shields(),
cargo: inner.cargo(),
};
const applied = opts.createOutcome === "applied";
fixtures.push({
kind: "createScience",
cmdId,
name: lastCreate.name,
drive: lastCreate.drive,
weapons: lastCreate.weapons,
shields: lastCreate.shields,
cargo: lastCreate.cargo,
applied,
errorCode: applied ? null : 1,
});
continue;
}
if (payloadType === CommandPayload.CommandScienceRemove) {
const inner = new CommandScienceRemove();
item.payload(inner);
lastRemove = { name: inner.name() ?? "" };
fixtures.push({
kind: "removeScience",
cmdId,
name: lastRemove.name,
applied: true,
errorCode: null,
});
continue;
}
if (payloadType === CommandPayload.CommandPlanetProduce) {
const inner = new CommandPlanetProduce();
item.payload(inner);
lastProduce = {
planetNumber: Number(inner.number()),
productionType: String(inner.production()),
subject: inner.subject() ?? "",
};
fixtures.push({
kind: "setProductionType",
cmdId,
planetNumber: Number(inner.number()),
productionType: "SCIENCE",
subject: inner.subject() ?? "",
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 lastProduce() {
return lastProduce;
},
};
}
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 science via the table + designer", async ({
page,
}, testInfo) => {
test.skip(
testInfo.project.name.startsWith("chromium-mobile"),
"phase 21 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/sciences`);
const tableHost = page.getByTestId("active-view-table");
await expect(tableHost).toBeVisible();
await expect(page.getByTestId("sciences-empty")).toBeVisible();
await page.getByTestId("sciences-new").click();
await expect(page.getByTestId("active-view-designer-science")).toHaveAttribute(
"data-mode",
"new",
);
await page.getByTestId("designer-science-input-name").fill("FirstStep");
await page.getByTestId("designer-science-input-drive").fill("25");
await page.getByTestId("designer-science-input-weapons").fill("25");
await page.getByTestId("designer-science-input-shields").fill("25");
await page.getByTestId("designer-science-input-cargo").fill("25");
const save = page.getByTestId("designer-science-save");
await expect(save).toBeEnabled();
await save.click();
// Returns to the table; the optimistic overlay shows the new science.
await expect(page.getByTestId("sciences-table")).toBeVisible();
const row = page.getByTestId("sciences-row");
await expect(row).toHaveAttribute("data-name", "FirstStep");
await expect(page.getByTestId("sciences-cell-drive")).toHaveText("25");
// 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(
"FirstStep",
);
await expect(orderTool.getByTestId("order-command-status-0")).toHaveText(
"applied",
);
expect(handle.lastCreate?.name).toBe("FirstStep");
expect(handle.lastCreate?.drive).toBeCloseTo(0.25, 12);
// Delete the science 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("sciences-delete").click();
await expect(page.getByTestId("sciences-empty")).toBeVisible();
await page.getByTestId("sidebar-tab-order").click();
await expect(orderTool.getByTestId("order-command-label-1")).toContainText(
"FirstStep",
);
expect(handle.lastRemove?.name).toBe("FirstStep");
});
test("designer keeps Save disabled while the form is invalid", async ({
page,
}, testInfo) => {
test.skip(
testInfo.project.name.startsWith("chromium-mobile"),
"phase 21 spec covers desktop layout; mobile inherits the same store",
);
await mockGateway(page, { createOutcome: "applied" });
await bootSession(page);
await page.goto(`/games/${GAME_ID}/designer/science`);
const save = page.getByTestId("designer-science-save");
await expect(save).toBeDisabled();
// Empty name surfaces the entity-name error.
await expect(page.getByTestId("designer-science-error")).toHaveText(
"name cannot be empty",
);
// Sum off — error stays visible and Save remains disabled.
await page.getByTestId("designer-science-input-name").fill("Bad");
await page.getByTestId("designer-science-input-drive").fill("50");
await expect(page.getByTestId("designer-science-error")).toHaveText(
"the four percentages must sum to exactly 100",
);
await expect(save).toBeDisabled();
// Filling the rest to total 100 enables Save.
await page.getByTestId("designer-science-input-weapons").fill("50");
await expect(save).toBeEnabled();
});
test("planet production picker exposes user sciences in the Research sub-row", async ({
page,
}, testInfo) => {
test.skip(
testInfo.project.name.startsWith("chromium-mobile"),
"phase 21 spec covers desktop layout; mobile inherits the same store",
);
const handle = await mockGateway(page, {
createOutcome: "applied",
initialSciences: [
{ name: "FirstStep", drive: 0.25, weapons: 0.25, shields: 0.25, cargo: 0.25 },
],
});
await bootSession(page);
await page.goto(`/games/${GAME_ID}/map`);
await expect(page.getByTestId("active-view-map")).toHaveAttribute(
"data-status",
"ready",
);
// Click the planet on the map canvas to seed the inspector
// selection — the Phase 11 map auto-centres on the single planet.
const canvas = page.locator("canvas");
const box = await canvas.boundingBox();
if (box === null) throw new Error("canvas has no bounding box");
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
const sidebar = page.getByTestId("sidebar-tool-inspector");
await expect(sidebar.getByTestId("inspector-planet-name")).toHaveText("Earth");
// Expand the Research segment.
await sidebar
.getByTestId("inspector-planet-production-segment-research")
.click();
// Tech buttons + the user's science button are both rendered.
await expect(
sidebar.getByTestId("inspector-planet-production-research-drive"),
).toBeVisible();
const scienceButton = sidebar.getByTestId(
"inspector-planet-production-science-FirstStep",
);
await expect(scienceButton).toBeVisible();
// Click the science → setProductionType("SCIENCE", "FirstStep")
// lands in the draft and auto-syncs.
await scienceButton.click();
await expect.poll(() => handle.lastProduce?.subject).toBe("FirstStep");
expect(handle.lastProduce?.planetNumber).toBe(1);
});
+8 -13
View File
@@ -2,12 +2,13 @@
// stub renders the localised view title plus the `coming soon` body // stub renders the localised view title plus the `coming soon` body
// copy and exposes a stable `data-testid` so later phases can replace // copy and exposes a stable `data-testid` so later phases can replace
// the content without renaming the test hook. Phase 17 lit up the // the content without renaming the test hook. Phase 17 lit up the
// ship-classes table and the ship-class designer, so the assertions // ship-classes table and the ship-class designer; Phase 21 lit up
// for those slugs / components moved to the dedicated suites // the sciences table and the science designer. Their assertions
// (`table-ship-classes.test.ts`, `designer-ship-class.test.ts`); the // moved to dedicated suites (`table-ship-classes.test.ts`,
// `table.svelte` router still falls back to the stub for the // `designer-ship-class.test.ts`, `table-sciences.test.ts`,
// not-yet-implemented entities (planets, ship-groups, fleets, // `designer-science.test.ts`); the `table.svelte` router still falls
// sciences, races) and that fallback is exercised here. // back to the stub for the remaining entities (planets, ship-groups,
// fleets, races) and that fallback is exercised here.
import "@testing-library/jest-dom/vitest"; import "@testing-library/jest-dom/vitest";
import { render } from "@testing-library/svelte"; import { render } from "@testing-library/svelte";
@@ -20,7 +21,6 @@ import TableView from "../src/lib/active-view/table.svelte";
import ReportView from "../src/lib/active-view/report.svelte"; import ReportView from "../src/lib/active-view/report.svelte";
import BattleView from "../src/lib/active-view/battle.svelte"; import BattleView from "../src/lib/active-view/battle.svelte";
import MailView from "../src/lib/active-view/mail.svelte"; import MailView from "../src/lib/active-view/mail.svelte";
import DesignerScience from "../src/lib/active-view/designer-science.svelte";
beforeEach(() => { beforeEach(() => {
i18n.resetForTests("en"); i18n.resetForTests("en");
@@ -56,7 +56,7 @@ describe("active-view stubs", () => {
expect(node).toHaveTextContent("ship groups"); expect(node).toHaveTextContent("ship groups");
}); });
test("report / mail / designer-science stubs render their localised titles", () => { test("report / mail stubs render their localised titles", () => {
const r = render(ReportView); const r = render(ReportView);
expect(r.getByTestId("active-view-report")).toHaveTextContent( expect(r.getByTestId("active-view-report")).toHaveTextContent(
"turn report", "turn report",
@@ -66,11 +66,6 @@ describe("active-view stubs", () => {
expect(m.getByTestId("active-view-mail")).toHaveTextContent( expect(m.getByTestId("active-view-mail")).toHaveTextContent(
"diplomatic mail", "diplomatic mail",
); );
const sci = render(DesignerScience);
expect(
sci.getByTestId("active-view-designer-science"),
).toHaveTextContent("science designer");
}); });
test("battle stub stamps the battleId on the host element", () => { test("battle stub stamps the battleId on the host element", () => {
@@ -1,8 +1,8 @@
// EMPTY_SHIP_GROUPS supplies empty arrays for the five ship-group / // EMPTY_SHIP_GROUPS supplies empty arrays for the ancillary report
// fleet fields added to GameReport in Phase 19. Test fixtures spread // fields added in Phase 19 (ship-groups + fleets) and Phase 21
// it into their report objects so the fixture body still focuses on // (sciences). Test fixtures spread it into their report objects so
// the fields under test, without forcing every spec to enumerate // the fixture body still focuses on the fields under test, without
// the full GameReport surface. // forcing every spec to enumerate the full GameReport surface.
import type { import type {
ReportIncomingShipGroup, ReportIncomingShipGroup,
@@ -10,6 +10,7 @@ import type {
ReportLocalShipGroup, ReportLocalShipGroup,
ReportOtherShipGroup, ReportOtherShipGroup,
ReportUnidentifiedShipGroup, ReportUnidentifiedShipGroup,
ScienceSummary,
} from "../../src/api/game-state"; } from "../../src/api/game-state";
export const EMPTY_SHIP_GROUPS: { export const EMPTY_SHIP_GROUPS: {
@@ -19,6 +20,7 @@ export const EMPTY_SHIP_GROUPS: {
unidentifiedShipGroups: ReportUnidentifiedShipGroup[]; unidentifiedShipGroups: ReportUnidentifiedShipGroup[];
localFleets: ReportLocalFleet[]; localFleets: ReportLocalFleet[];
otherRaces: string[]; otherRaces: string[];
localScience: ScienceSummary[];
} = { } = {
localShipGroups: [], localShipGroups: [],
otherShipGroups: [], otherShipGroups: [],
@@ -26,4 +28,5 @@ export const EMPTY_SHIP_GROUPS: {
unidentifiedShipGroups: [], unidentifiedShipGroups: [],
localFleets: [], localFleets: [],
otherRaces: [], otherRaces: [],
localScience: [],
}; };
@@ -17,6 +17,7 @@ import { afterEach, beforeEach, describe, expect, test } from "vitest";
import { i18n } from "../src/lib/i18n/index.svelte"; import { i18n } from "../src/lib/i18n/index.svelte";
import type { import type {
ReportPlanet, ReportPlanet,
ScienceSummary,
ShipClassSummary, ShipClassSummary,
} from "../src/api/game-state"; } from "../src/api/game-state";
import Production from "../src/lib/inspectors/planet/production.svelte"; import Production from "../src/lib/inspectors/planet/production.svelte";
@@ -94,12 +95,13 @@ function shipClass(
function mountProduction( function mountProduction(
planet: ReportPlanet, planet: ReportPlanet,
localShipClass: ShipClassSummary[] = [], localShipClass: ShipClassSummary[] = [],
localScience: ScienceSummary[] = [],
) { ) {
const context = new Map<unknown, unknown>([ const context = new Map<unknown, unknown>([
[ORDER_DRAFT_CONTEXT_KEY, draft], [ORDER_DRAFT_CONTEXT_KEY, draft],
]); ]);
return render(Production, { return render(Production, {
props: { planet, localShipClass }, props: { planet, localShipClass, localScience },
context, context,
}); });
} }
@@ -65,6 +65,7 @@ describe("planet inspector", () => {
freeIndustry: 187.5, freeIndustry: 187.5,
}), }),
localShipClass: [], localShipClass: [],
localScience: [],
routes: [], routes: [],
planets: [], planets: [],
mapWidth: 1, mapWidth: 1,
@@ -138,6 +139,7 @@ describe("planet inspector", () => {
freeIndustry: 75, freeIndustry: 75,
}), }),
localShipClass: [], localShipClass: [],
localScience: [],
routes: [], routes: [],
planets: [], planets: [],
mapWidth: 1, mapWidth: 1,
@@ -177,6 +179,7 @@ describe("planet inspector", () => {
materialsStockpile: 0, materialsStockpile: 0,
}), }),
localShipClass: [], localShipClass: [],
localScience: [],
routes: [], routes: [],
planets: [], planets: [],
mapWidth: 1, mapWidth: 1,
@@ -217,6 +220,7 @@ describe("planet inspector", () => {
y: -5, y: -5,
}), }),
localShipClass: [], localShipClass: [],
localScience: [],
routes: [], routes: [],
planets: [], planets: [],
mapWidth: 1, mapWidth: 1,
@@ -253,6 +257,7 @@ describe("planet inspector", () => {
resources: 5, resources: 5,
}), }),
localShipClass: [], localShipClass: [],
localScience: [],
routes: [], routes: [],
planets: [], planets: [],
mapWidth: 1, mapWidth: 1,
@@ -293,6 +298,7 @@ describe("planet inspector", () => {
freeIndustry: 0, freeIndustry: 0,
}), }),
localShipClass: [], localShipClass: [],
localScience: [],
routes: [], routes: [],
planets: [], planets: [],
mapWidth: 1, mapWidth: 1,
@@ -364,6 +370,7 @@ describe("planet inspector", () => {
freeIndustry: 0, freeIndustry: 0,
}), }),
localShipClass: [], localShipClass: [],
localScience: [],
routes: [], routes: [],
planets: [], planets: [],
mapWidth: 1, mapWidth: 1,
@@ -402,6 +409,7 @@ describe("planet inspector", () => {
freeIndustry: 0, freeIndustry: 0,
}), }),
localShipClass: [], localShipClass: [],
localScience: [],
routes: [], routes: [],
planets: [], planets: [],
mapWidth: 1, mapWidth: 1,
@@ -58,6 +58,7 @@ function makeReport(
planetCount: overrides.planets.length, planetCount: overrides.planets.length,
race: "Earthlings", race: "Earthlings",
localShipClass: [], localShipClass: [],
localScience: [],
routes: [], routes: [],
localPlayerDrive: 0, localPlayerDrive: 0,
localPlayerWeapons: 0, localPlayerWeapons: 0,
@@ -0,0 +1,190 @@
// Vitest coverage for `lib/util/science-validation.ts`. The
// validator is the TS-side mirror of
// `pkg/calc/validator.go.ValidateScienceValues` plus the
// `validateEntityName` rules and a UX-only duplicate-name check.
// The designer composes percentages (`[0, 100]` summing to `100`)
// and the validator returns canonical fractions (`[0, 1]` summing
// to `1.0`) on success — so the exhaustive coverage below also
// pins the percent → fraction conversion contract.
import { describe, expect, test } from "vitest";
import {
SUM_EPSILON_PERCENT,
fractionsToPercent,
validateScience,
type ScienceDraft,
} from "../src/lib/util/science-validation";
function draft(overrides: Partial<ScienceDraft>): ScienceDraft {
return {
name: "FirstStep",
drive: 25,
weapons: 25,
shields: 25,
cargo: 25,
...overrides,
};
}
describe("validateScience", () => {
test("accepts an even-split science and converts to fractions", () => {
const result = validateScience(draft({ name: "Even" }));
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.name).toBe("Even");
expect(result.value.drive).toBeCloseTo(0.25, 12);
expect(result.value.weapons).toBeCloseTo(0.25, 12);
expect(result.value.shields).toBeCloseTo(0.25, 12);
expect(result.value.cargo).toBeCloseTo(0.25, 12);
});
test("trims surrounding whitespace from the name", () => {
const result = validateScience(draft({ name: " Beta " }));
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.name).toBe("Beta");
});
test("rejects empty name", () => {
const result = validateScience(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 = validateScience(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 = validateScience(draft({ name: "Big Name" }));
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.reason).toBe("whitespace");
});
test.each([
{ value: -0.1, reason: "drive_value" as const, field: "drive" as const },
{ value: 100.1, reason: "drive_value" as const, field: "drive" as const },
{
value: Number.POSITIVE_INFINITY,
reason: "drive_value" as const,
field: "drive" as const,
},
{
value: Number.NaN,
reason: "weapons_value" as const,
field: "weapons" as const,
},
{
value: -1,
reason: "shields_value" as const,
field: "shields" as const,
},
{ value: 101, reason: "cargo_value" as const, field: "cargo" as const },
])(
"rejects $field = $value with reason $reason",
({ value, reason, field }) => {
const overrides: Partial<ScienceDraft> = {
drive: 25,
weapons: 25,
shields: 25,
cargo: 25,
};
(overrides as Record<typeof field, number>)[field] = value;
const result = validateScience(draft(overrides));
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.reason).toBe(reason);
},
);
test("rejects sum off by more than the epsilon", () => {
const result = validateScience(
draft({ drive: 30, weapons: 30, shields: 30, cargo: 5 }),
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.reason).toBe("sum_not_hundred");
});
test("accepts the canonical First Step fixture from rules.txt", () => {
// 10 Drive + 5 Weapons + 30 Shields + 0 Cargo, normalised:
// 10/45 ≈ 22.222… %, 5/45 ≈ 11.111… %, 30/45 ≈ 66.666… %,
// 0/45 = 0 %. Snapped to one decimal at input time:
// 22.2 / 11.1 / 66.7 / 0 → sum = 100. The float arithmetic is
// well within `SUM_EPSILON_PERCENT`.
const result = validateScience(
draft({ name: "FirstStep", drive: 22.2, weapons: 11.1, shields: 66.7, cargo: 0 }),
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.drive).toBeCloseTo(0.222, 6);
expect(result.value.weapons).toBeCloseTo(0.111, 6);
expect(result.value.shields).toBeCloseTo(0.667, 6);
expect(result.value.cargo).toBe(0);
});
test("accepts a 100/0/0/0 single-axis science", () => {
const result = validateScience(
draft({ name: "PureDrive", drive: 100, weapons: 0, shields: 0, cargo: 0 }),
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.drive).toBe(1);
});
test("accepts sums within the float tolerance", () => {
// Build a sum that drifts a hair off due to FP arithmetic but
// stays inside `SUM_EPSILON_PERCENT`.
const sumOk = 100 - SUM_EPSILON_PERCENT / 2;
const result = validateScience(
draft({ drive: sumOk, weapons: 0, shields: 0, cargo: 0 }),
);
expect(result.ok).toBe(true);
});
test("flags duplicate names against existingNames", () => {
const result = validateScience(draft({ name: "Beta" }), {
existingNames: ["Alpha", "Beta"],
});
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.reason).toBe("duplicate_name");
});
test("compares duplicate names after trimming", () => {
const result = validateScience(draft({ name: " Beta " }), {
existingNames: ["Beta"],
});
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 = validateScience(draft({ name: "Beta" }), {
existingNames: [],
});
expect(result.ok).toBe(true);
});
});
describe("fractionsToPercent", () => {
test("inverts the percent → fraction conversion", () => {
const back = fractionsToPercent({
drive: 0.25,
weapons: 0.111,
shields: 0.5,
cargo: 0.139,
});
expect(back.drive).toBeCloseTo(25, 6);
expect(back.weapons).toBeCloseTo(11.1, 6);
expect(back.shields).toBeCloseTo(50, 6);
expect(back.cargo).toBeCloseTo(13.9, 6);
});
});
+215
View File
@@ -0,0 +1,215 @@
// Vitest coverage for the Phase 21 sciences 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 `removeScience` 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, ScienceSummary } 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";
import { EMPTY_SHIP_GROUPS } from "./helpers/empty-ship-groups";
const GAME_ID = "11111111-2222-3333-4444-555555555555";
const pageMock = vi.hoisted(() => ({
url: new URL("http://localhost/games/g1/table/sciences"),
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 TableSciences from "../src/lib/active-view/table-sciences.svelte";
let db: IDBPDatabase<GalaxyDB>;
let dbName: string;
let cache: Cache;
let draft: OrderDraftStore;
beforeEach(async () => {
dbName = `galaxy-table-sciences-${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 science(
overrides: Partial<ScienceSummary> & Pick<ScienceSummary, "name">,
): ScienceSummary {
return {
drive: 0,
weapons: 0,
shields: 0,
cargo: 0,
...overrides,
};
}
function makeReport(localScience: ScienceSummary[]): GameReport {
const baseEmpty = { ...EMPTY_SHIP_GROUPS, localScience };
return {
turn: 1,
mapWidth: 1000,
mapHeight: 1000,
planetCount: 0,
planets: [],
race: "",
localShipClass: [],
routes: [],
localPlayerDrive: 0,
localPlayerWeapons: 0,
localPlayerShields: 0,
localPlayerCargo: 0,
...baseEmpty,
};
}
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(TableSciences, { context });
}
describe("sciences table", () => {
test("renders a loading placeholder before the report lands", () => {
const ui = mountTable(null);
expect(ui.getByTestId("sciences-loading")).toBeInTheDocument();
});
test("renders an empty placeholder when no sciences are defined", () => {
const ui = mountTable(makeReport([]));
expect(ui.getByTestId("sciences-empty")).toBeInTheDocument();
});
test("renders one row per science with percent-formatted attributes", () => {
const ui = mountTable(
makeReport([
science({
name: "FirstStep",
drive: 0.222,
weapons: 0.111,
shields: 0.667,
cargo: 0,
}),
]),
);
const rows = ui.getAllByTestId("sciences-row");
expect(rows).toHaveLength(1);
expect(rows[0]).toHaveAttribute("data-name", "FirstStep");
expect(ui.getByTestId("sciences-cell-drive")).toHaveTextContent("22.2");
expect(ui.getByTestId("sciences-cell-weapons")).toHaveTextContent("11.1");
expect(ui.getByTestId("sciences-cell-shields")).toHaveTextContent("66.7");
expect(ui.getByTestId("sciences-cell-cargo")).toHaveTextContent("0");
});
test("filters rows by case-insensitive name match", async () => {
const ui = mountTable(
makeReport([
science({ name: "Alpha", drive: 1 }),
science({ name: "Beta", drive: 1 }),
science({ name: "Gamma", drive: 1 }),
]),
);
await fireEvent.input(ui.getByTestId("sciences-filter"), {
target: { value: "ph" },
});
const rows = ui.getAllByTestId("sciences-row");
expect(rows).toHaveLength(1);
expect(rows[0]).toHaveAttribute("data-name", "Alpha");
});
test("toggles sort direction when the same column is clicked twice", async () => {
const ui = mountTable(
makeReport([
science({ name: "Alpha", drive: 0.1 }),
science({ name: "Beta", drive: 0.5 }),
science({ name: "Gamma", drive: 0.3 }),
]),
);
const driveHeader = ui.getByTestId("sciences-column-drive");
await fireEvent.click(driveHeader);
let names = ui
.getAllByTestId("sciences-row")
.map((row) => row.getAttribute("data-name"));
expect(names).toEqual(["Alpha", "Gamma", "Beta"]);
await fireEvent.click(driveHeader);
names = ui
.getAllByTestId("sciences-row")
.map((row) => row.getAttribute("data-name"));
expect(names).toEqual(["Beta", "Gamma", "Alpha"]);
});
test("dblclick on a row navigates to the designer for that science", async () => {
const ui = mountTable(
makeReport([science({ name: "FirstStep", drive: 1 })]),
);
await fireEvent.dblClick(ui.getByTestId("sciences-row"));
expect(gotoMock).toHaveBeenCalledWith(
"/games/g1/designer/science/FirstStep",
);
});
test("delete button adds a removeScience to the draft", async () => {
const ui = mountTable(makeReport([science({ name: "FirstStep", drive: 1 })]));
await fireEvent.click(ui.getByTestId("sciences-delete"));
await waitFor(() => expect(draft.commands).toHaveLength(1));
const cmd = draft.commands[0]!;
if (cmd.kind !== "removeScience") throw new Error("wrong kind");
expect(cmd.name).toBe("FirstStep");
});
test("new button navigates to the empty designer", async () => {
const ui = mountTable(makeReport([]));
await fireEvent.click(ui.getByTestId("sciences-new"));
expect(gotoMock).toHaveBeenCalledWith("/games/g1/designer/science");
});
});