ui/phase-21: sciences CRUD list, designer, and production-picker integration

Lights up the player-defined sciences feature: a table view with sort
and filter, a designer with four percent inputs and a strict
sum-equals-100 gate, and a Research-sub-row integration so the
planet production picker lists the user's sciences alongside the
four tech buttons. Phase 21 decisions are baked back into ui/PLAN.md
(no UpdateScience on the wire — write-once via createScience +
removeScience; percentages instead of fractions; sciences live under
the existing Research segment).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Ilia Denisov
2026-05-10 21:32:37 +02:00
parent 0509f2cde2
commit 7bea22b0b5
31 changed files with 2751 additions and 71 deletions
@@ -1,28 +1,448 @@
<!--
Phase 10 stub for the science designer active view. Phase 21 wires
the CRUD list and designer. The optional `scienceId` URL segment is
accepted but ignored at this point.
Phase 21 science designer. Two modes driven by the optional
`scienceId` URL segment:
- **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">
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>
<section class="active-view" data-testid="active-view-designer-science">
<h2>{i18n.t("game.view.designer.science")}</h2>
<p>{i18n.t("game.shell.coming_soon")}</p>
<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>
<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>
<style>
.active-view {
padding: 1.5rem;
font-family: system-ui, sans-serif;
display: flex;
flex-direction: column;
gap: 0.85rem;
}
.active-view h2 {
margin: 0 0 0.5rem;
margin: 0;
font-size: 1.1rem;
}
.active-view p {
.notice,
.hint,
.not-found {
margin: 0;
color: #555;
color: #888;
font-size: 0.85rem;
}
.form {
display: flex;
flex-direction: column;
gap: 0.55rem;
max-width: 30rem;
}
.row {
display: grid;
grid-template-columns: 8rem 1fr;
align-items: center;
gap: 0.6rem;
}
.row span {
color: #aab;
font-size: 0.85rem;
}
.row input {
font: inherit;
padding: 0.3rem 0.5rem;
background: #0a0e1a;
color: #e8eaf6;
border: 1px solid #2a3150;
border-radius: 3px;
}
.row input[aria-invalid="true"] {
border-color: #d97a7a;
}
.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>
@@ -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
the ship-classes table; the other slugs (planets, ship-groups,
fleets, sciences, races) keep the Phase 10 stub copy until their
respective phases land. The wrapper preserves
`data-testid="active-view-table"` and `data-entity={entity}` for
both branches so the navigation e2e specs (`game-shell.spec.ts`,
the ship-classes table; Phase 21 lights up the sciences table; the
remaining slugs (planets, ship-groups, fleets, races) keep the
Phase 10 stub copy until their respective phases land. The wrapper
preserves `data-testid="active-view-table"` and
`data-entity={entity}` for every branch (each leaf component
mirrors them) so the navigation e2e specs (`game-shell.spec.ts`,
`view-menu`) keep matching.
-->
<script lang="ts">
import { i18n, type TranslationKey } from "$lib/i18n/index.svelte";
import TableShipClasses from "./table-ship-classes.svelte";
import TableSciences from "./table-sciences.svelte";
type Props = { entity: string };
let { entity }: Props = $props();
@@ -22,6 +24,8 @@ both branches so the navigation e2e specs (`game-shell.spec.ts`,
{#if entity === "ship-classes"}
<TableShipClasses />
{:else if entity === "sciences"}
<TableSciences />
{:else}
<section
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.ship_class_create": "design 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_send": "send group {group} → planet {destination}",
"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.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.other": "other race 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.ship_class_create": "сконструировать класс корабля {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_send": "отправить группу {group} → планета {destination}",
"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.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.other": "группа другой расы",
"game.inspector.ship_group.kind.incoming": "входящая группа",
@@ -16,6 +16,7 @@ dismiss from the IA section §6 land in Phase 35 polish.
ReportOtherShipGroup,
ReportPlanet,
ReportRoute,
ScienceSummary,
ShipClassSummary,
} from "../../api/game-state";
import { i18n } from "$lib/i18n/index.svelte";
@@ -24,6 +25,7 @@ dismiss from the IA section §6 land in Phase 35 polish.
type Props = {
planet: ReportPlanet | null;
localShipClass: ShipClassSummary[];
localScience: ScienceSummary[];
routes: ReportRoute[];
planets: ReportPlanet[];
mapWidth: number;
@@ -38,6 +40,7 @@ dismiss from the IA section §6 land in Phase 35 polish.
let {
planet,
localShipClass,
localScience,
routes,
planets,
mapWidth,
@@ -69,6 +72,7 @@ dismiss from the IA section §6 land in Phase 35 polish.
<Planet
{planet}
{localShipClass}
{localScience}
{routes}
{planets}
{mapWidth}
+4 -1
View File
@@ -19,6 +19,7 @@ field with five buttons.
ReportOtherShipGroup,
ReportPlanet,
ReportRoute,
ScienceSummary,
ShipClassSummary,
} from "../../api/game-state";
import { i18n, type TranslationKey } from "$lib/i18n/index.svelte";
@@ -37,6 +38,7 @@ field with five buttons.
type Props = {
planet: ReportPlanet;
localShipClass: ShipClassSummary[];
localScience: ScienceSummary[];
routes: ReportRoute[];
planets: ReportPlanet[];
mapWidth: number;
@@ -49,6 +51,7 @@ field with five buttons.
let {
planet,
localShipClass,
localScience,
routes,
planets,
mapWidth,
@@ -221,7 +224,7 @@ field with five buttons.
{/if}
{#if planet.kind === "local"}
<Production {planet} {localShipClass} />
<Production {planet} {localShipClass} {localScience} />
<CargoRoutes
{planet}
{routes}
@@ -2,10 +2,11 @@
Phase 15 production-controls subsection of the planet inspector.
Renders four main segments — industry / materials / research / build
ship — and reveals a sub-row when the player picks a category that
needs a target (research → tech field, build ship → designed class).
Every leaf click appends a `setProductionType` command to the local
order draft via `OrderDraftStore`; the collapse-by-`planetNumber`
rule inside `add` keeps at most one production choice per planet.
needs a target (research → tech field or science, build ship →
designed class). Every leaf click appends a `setProductionType`
command to the local order draft via `OrderDraftStore`; the
collapse-by-`planetNumber` rule inside `add` keeps at most one
production choice per planet.
The currently-active segment is derived from `planet.production`
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
not render forecast text; the existing `freeIndustry` ("free
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">
import { getContext } from "svelte";
import type {
ReportPlanet,
ScienceSummary,
ShipClassSummary,
} from "../../../api/game-state";
import { i18n, type TranslationKey } from "$lib/i18n/index.svelte";
@@ -37,8 +48,9 @@ production") row in the parent inspector is unchanged.
type Props = {
planet: ReportPlanet;
localShipClass: ShipClassSummary[];
localScience: ScienceSummary[];
};
let { planet, localShipClass }: Props = $props();
let { planet, localShipClass, localScience }: Props = $props();
type MainSegment = "industry" | "materials" | "research" | "ship";
@@ -49,9 +61,12 @@ production") row in the parent inspector is unchanged.
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 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));
$effect(() => {
@@ -92,8 +107,13 @@ production") row in the parent inspector is unchanged.
function parseMain(
value: string | null,
classes: ShipClassSummary[],
sciences: ScienceSummary[],
): MainSegment | 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) {
case "Capital":
return "industry";
@@ -108,7 +128,14 @@ production") row in the parent inspector is unchanged.
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) {
case "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(
value: string | null,
classes: ShipClassSummary[],
@@ -150,6 +185,11 @@ production") row in the parent inspector is unchanged.
expandedMain = null;
}
function clickScience(name: string): void {
void emit("SCIENCE", name);
expandedMain = null;
}
function clickShip(name: string): void {
void emit("SHIP", name);
expandedMain = null;
@@ -231,6 +271,18 @@ production") row in the parent inspector is unchanged.
{i18n.t(option.labelKey)}
</button>
{/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>
{/if}
@@ -82,6 +82,7 @@ from the Phase 10 stub.
const localShipClass = $derived(
renderedReport?.report?.localShipClass ?? [],
);
const localScience = $derived(renderedReport?.report?.localScience ?? []);
const allPlanets = $derived(renderedReport?.report?.planets ?? []);
const routes = $derived(renderedReport?.report?.routes ?? []);
const mapWidth = $derived(renderedReport?.report?.mapWidth ?? 1);
@@ -114,6 +115,7 @@ from the Phase 10 stub.
<Planet
planet={selectedPlanet}
{localShipClass}
{localScience}
{routes}
planets={allPlanets}
{mapWidth}
@@ -77,6 +77,14 @@ Tests exercise the tab through `__galaxyDebug.seedOrderDraft`
return i18n.t("game.sidebar.order.label.ship_class_remove", {
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":
return i18n.t("game.sidebar.order.label.ship_group_break", {
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;
}