fix(viewer): restore all-player Over Time statistics

This commit is contained in:
coyotte508 2026-11-15 21:57:19 +00:00
commit 622e54ea73
7 changed files with 257 additions and 8 deletions

View file

@ -1,6 +1,6 @@
{
"name": "@gaia-project/old-ui",
"version": "1.2.37",
"version": "1.2.38",
"scripts": {
"serve": "vite --port 5193",
"build": "vite build",

View file

@ -1,6 +1,6 @@
{
"name": "@gaia-project/viewer",
"version": "5.22.37",
"version": "5.22.38",
"description": "Functions to visualize the map and boards for gaia project inside html canvas",
"contributors": [
"coyotte508",

View file

@ -0,0 +1,136 @@
// Run after building engine, viewer and old-ui:
// node viewer/scripts/statistics-overtime-smoke.mjs
// Optional BASE_STATE / LF_STATE paths exercise captured public game states instead
// of the no-activity fixtures. All interactions are local and no moves are sent.
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { createServer } from "node:http";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import { chromium } from "playwright";
const require = createRequire(import.meta.url);
const repo = new URL("../../", import.meta.url);
const engine = require(fileURLToPath(new URL("engine/dist/index.js", repo)));
const modes = ["normal", "old"];
const html =
'<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="stylesheet" href="/bundle.css"><div id="app"></div><script src="/vue.js"></script>' +
'<script src="/bootstrap.js"></script>' +
'<script src="/bundle.js"></script>';
let mode = "normal";
const server = createServer(async (req, res) => {
try {
const bundle = mode === "old" ? "old-ui/dist/package/old-ui.umd.js" : "viewer/dist/package/viewer.umd.js";
const css = mode === "old" ? "old-ui/dist/package/old-ui.css" : "viewer/dist/package/viewer.css";
const files = {
"/bundle.js": fileURLToPath(new URL(bundle, repo)),
"/bundle.css": fileURLToPath(new URL(css, repo)),
"/vue.js": require.resolve("vue/dist/vue.min.js"),
"/bootstrap.js": require.resolve("bootstrap-vue/dist/bootstrap-vue.min.js"),
};
if (req.url === "/") {
res.setHeader("Content-Type", "text/html");
res.end(html);
} else if (/^\/[a-zA-Z0-9-]+\.(json|jpg)$/.test(req.url)) {
res.setHeader("Content-Type", req.url.endsWith(".json") ? "application/json" : "image/jpeg");
res.end(
await readFile(
fileURLToPath(new URL((mode === "old" ? "old-ui/dist/package" : "viewer/dist/package") + req.url, repo))
)
);
} else if (files[req.url]) {
res.setHeader("Content-Type", req.url.endsWith(".css") ? "text/css" : "text/javascript; charset=utf-8");
res.end(await readFile(files[req.url]));
} else {
res.statusCode = 404;
res.end();
}
} catch (error) {
res.statusCode = 500;
res.end(String(error));
}
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_EXECUTABLE });
try {
for (const ui of modes) {
for (const [lostFleet, stateFile] of [
[false, process.env.BASE_STATE],
[true, process.env.LF_STATE],
]) {
mode = ui;
const page = await browser.newPage({ viewport: { width: 1400, height: 1000 } });
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
page.on("console", (message) => {
if (message.type() === "error" && !message.text().startsWith("Failed to load resource:"))
errors.push(message.text());
});
const state = stateFile
? JSON.parse(await readFile(stateFile, "utf8"))
: JSON.parse(
JSON.stringify(
new engine.default(
["init 3 overtime", "p1 faction terrans", "p2 faction itars", "p3 faction hadsch-hallas"],
{ lostFleet }
)
)
);
await page.goto(`http://127.0.0.1:${server.address().port}/`);
await page.evaluate((state) => {
window.host = window.gaiaViewer.launch("#app");
host.emit("preferences", { sound: false });
host.emit("state", state);
}, state);
// Both UIs expose the same statistics modal; the old UI uses an SVG chart icon.
await page.waitForFunction(() =>
[...document.querySelectorAll("*")].some((el) => el.__vue__?.$store?.state?.data?.players?.length)
);
await page.evaluate(() => {
const vm = [...document.querySelectorAll("*")].find((el) => el.__vue__?.$bvModal)?.__vue__;
vm.$bvModal.show("chart-button");
});
const stats = page.locator(".stats-window");
await stats.waitFor();
const field = (label) =>
stats
.locator(".stats-window__field")
.filter({ has: page.locator("label", { hasText: new RegExp(`^${label}$`) }) });
const choices = async (label) => field(label).locator(".dropdown-item").allTextContents();
const pick = async (label, index) => {
const container = field(label);
await container.locator(".dropdown-toggle").click();
await container.locator(".dropdown-item").nth(index).click();
await page.waitForTimeout(10);
assert.deepEqual(errors, [], `${ui}/${lostFleet}/${label}: no errors`);
};
let count = 0;
const views = await choices("View");
for (let v = 0; v < views.length; v++) {
await pick("View", v);
const types = (await field("Breakdown").count()) ? await choices("Breakdown") : [null];
for (let t = 0; t < types.length; t++) {
if (types[t] !== null) await pick("Breakdown", t);
const kinds = await choices("Details");
// The first two are Overview and Over Time; exercise every player/source too.
for (let k = 1; k < kinds.length; k++) {
await pick("Details", k);
assert.equal((await field("Details").locator(".dropdown-toggle").innerText()).trim(), kinds[k].trim());
const rows = stats.locator("tbody tr");
assert.match(await rows.first().innerText(), /Start/);
assert(!(await stats.innerText()).includes("NaN"));
if (k > state.players.length + 1) {
assert.equal((await stats.locator("caption").innerText()).trim(), `${kinds[k].trim()} of all players`);
}
count++;
}
}
}
console.log(`${ui}/${lostFleet ? "Lost Fleet" : "base"}: ${count} Over Time/player/source selections passed`);
await page.close();
}
}
} finally {
await browser.close();
await new Promise((resolve) => server.close(resolve));
}

View file

@ -102,6 +102,39 @@ describe("Charts", () => {
wrapper.destroy();
});
it("clicking Over Time selects an all-player time series rather than a missing source", async () => {
const engine = new Engine((endedGame as any).moveHistory, (endedGame as any).options, null, true);
const store = makeStore();
store.commit("receiveData", engine);
const wrapper = mount(Charts, { store });
const vm: any = wrapper.vm;
await Vue.nextTick();
const overview = vm.table.title;
// Use the rendered dropdown's click handler, not just the factory API.
await wrapper
.findAll(".dropdown-item")
.wrappers.find((item) => item.text() === "Over Time")
.trigger("click");
expect(vm.chartKindLabel).to.equal("Over Time");
expect(vm.table.title).to.equal(overview);
expect(vm.table.items.length).to.be.greaterThan(0);
expect(vm.table.items[0].Name).to.equal("<span>Start</span>");
expect(vm.table.items[vm.table.items.length - 1].Name).to.equal("<span>Final</span>");
expect(vm.table.header).to.have.length(engine.players.length + 1);
// A grouped Breakdown change keeps the common Over Time selection.
await wrapper
.findAll(".stats-window__field")
.at(1)
.findAll(".dropdown-item")
.wrappers.find((item) => item.text() === "Boosters")
.trigger("click");
expect(vm.chartKindLabel).to.equal("Over Time");
expect(vm.table.title).to.equal("Victory Points from Boosters of all players");
expect(vm.table.items[0].Name).to.equal("<span>Start</span>");
wrapper.destroy();
});
it("no longer renders a Compact toggle (statistics is always compact)", async () => {
const engine = new Engine(["init 2 djfjjv4k", "p1 faction terrans", "p2 faction itars"]);
const store = makeStore();

View file

@ -91,7 +91,7 @@
</template>
<script lang="ts">
import Engine, { PlayerEnum } from "@gaia-project/engine";
import Engine from "@gaia-project/engine";
import type { ChartConfiguration } from "chart.js";
import { Component, Vue } from "vue-property-decorator";
import type { ChartKind, ChartKindDisplay, TableMeta } from "../logic/charts/chart-factory";
@ -207,8 +207,6 @@ export default class Charts extends Vue {
if (this.chartKind === barChartKind) {
const config = this.setup.newBarChart(this.chartStyle, factory, data, colorLookup);
this.buildTable(config.chart, config.table);
} else if (this.chartKind === lineChartKind) {
this.buildTable(this.setup.newLineChart(this.chartStyle, factory, data, PlayerEnum.All, colorLookup));
} else {
this.buildTable(this.setup.newLineChart(this.chartStyle, factory, data, this.chartKind, colorLookup));
}

View file

@ -124,7 +124,7 @@ const vpChartFactory = (
return `${victoryPointSource(source, allSources).label} of all players`;
},
stacked(kind: ChartKind) {
return Object.values(PlayerEnum).includes(kind) && kind != PlayerEnum.All;
return typeof kind === "number";
},
summary: ChartSummary.total,
roundLabels(source: ChartSource<any>): string[] | null {
@ -301,8 +301,10 @@ export class ChartSetup {
const allSources = factory.sources;
const includeRounds = factory.includeRounds;
if (typeof kind == "number") {
const numbers = kind === PlayerEnum.All ? chartPlayerOrder(data) : [kind as PlayerEnum];
// Over Time is a viewer selection, not a player enum member. Keeping its
// sentinel here also prevents it from falling through to the source lookup.
if (kind === lineChartKind || typeof kind === "number") {
const numbers = kind === lineChartKind ? chartPlayerOrder(data) : [kind as PlayerEnum];
if (numbers.length == 1) {
const p = numbers[0];

View file

@ -0,0 +1,80 @@
import Engine from "@gaia-project/engine";
import { expect } from "chai";
import { ChartSetup, lineChartKind } from "./chart-factory";
import { ChartGroup, playerLabel } from "./charts";
import endedGame from "./testdata/ended-game/test-case.json";
const style = { type: "table" as const, compact: true, label: "" };
const color = (c: string) => c;
describe("Over Time selections", () => {
for (const lostFleet of [false, true]) {
it(`builds every summary, player and source selection (${lostFleet ? "Lost Fleet" : "base"}) without activity`, () => {
const engine = new Engine(
["init 3 overtime", "p1 faction terrans", "p2 faction itars", "p3 faction hadsch-hallas"],
{ lostFleet }
);
const setup = new ChartSetup(engine);
for (const fleetView of ["Exploration", "Artifacts", "Lost Fleet activities"]) {
expect(setup.selects.includes(fleetView)).to.equal(lostFleet);
}
for (const select of setup.selects) {
const types = setup.types(select);
for (const type of types.length ? types : [null]) {
const factory = setup.factory(select, type);
const summary = setup.newLineChart(style, factory, engine, lineChartKind, color);
expect(summary.options.plugins.title.text).to.equal(factory.playerSummaryTitle);
expect(summary.data.datasets).to.have.length(engine.players.length);
expect(summary.options.scales.y.stacked).to.equal(false);
expect(summary.data.datasets.map((dataset) => dataset.label)).to.deep.equal(engine.players.map(playerLabel));
if (select === "Buildings") {
// Before initial placement there is genuinely no activity, not a missing source.
expect(
summary.data.datasets.every((dataset) => dataset.data.every((point: any) => point.y === 0))
).to.equal(true);
}
for (const group of setup.kinds(engine, factory).slice(1)) {
for (const { kind } of group) {
const config = setup.newLineChart(style, factory, engine, kind, color);
expect(config.data.datasets.length).to.be.greaterThan(0);
const title =
typeof kind === "number"
? factory.singlePlayerSummaryTitle(engine.player(kind))
: `${factory.sources.find((source) => source.type === kind).label} of all players`;
expect(config.options.plugins.title.text).to.equal(title);
for (const dataset of config.data.datasets) {
expect(dataset.data.length).to.be.greaterThan(0);
expect(dataset.data.every((point: any) => Number.isFinite(point.y))).to.equal(true);
}
}
}
}
}
});
}
it("aggregates each player's VP sources to the same totals as Overview on a completed game", () => {
const engine = new Engine(endedGame.moveHistory, endedGame.options as any, null, true);
const setup = new ChartSetup(engine);
const factory = setup.factory(ChartGroup.vp, "Overview");
const config = setup.newLineChart(style, factory, engine, lineChartKind, color);
const overview = setup.newBarChart(style, factory, engine, color);
expect(config.data.labels).to.deep.equal([
"Start",
"Round 1",
"Round 2",
"Round 3",
"Round 4",
"Round 5",
"Round 6",
"Final",
]);
expect(config.data.datasets.map((dataset) => dataset.label)).to.deep.equal(engine.players.map(playerLabel));
for (const dataset of config.data.datasets) {
const summary = Object.values(overview.table.datasetMeta).find((meta) => meta.label === dataset.label);
expect((dataset.data[7] as any).y).to.equal(summary.total);
}
const playerConfig = setup.newLineChart(style, factory, engine, engine.players[0].player, color);
expect(playerConfig.options.scales.y.stacked).to.equal("single");
});
});