primordial-soup/test/analysis-chat-browser.mjs

351 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { serveAssets } from "./asset-server.mjs";
const assetBase = await serveAssets("dist");
import { checkHostPresentation } from "./host-presentation-smoke.mjs";
import { prepared } from "../viewer/tutorials.js";
import assert from "node:assert/strict";
import { chromium } from "playwright";
import { fileURLToPath } from "node:url";
const browser = await chromium.launch({
executablePath: process.env.CHROMIUM_EXECUTABLE,
});
const root = fileURLToPath(new URL("../", import.meta.url));
try {
for (const game of ["soup"]) {
const engine = await import(
game === "fuji"
? root + "/packages/engine/dist/wrapper.js"
: root + "/engine/index.js"
);
const state = engine.stripSecret(
await engine.init(3, [], {}, "analysis-chat-browser"),
0,
);
for (const width of [390, 1400]) {
const page = await browser.newPage({ viewport: { width, height: 950 } });
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.setContent(
'<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1"></head><body><div id="app"></div></body></html>',
);
const prefix =
game === "fuji"
? root + "/packages/viewer/dist/fuji-viewer"
: root + "/dist/viewer";
await page.addStyleTag({ url: assetBase + "/viewer.css" });
await page.addScriptTag({ url: assetBase + "/viewer.js" });
await page.evaluate(
({ state, game }) => {
window.e = (game === "fuji" ? fuji : primordialSoup).launch("#app");
window.requests = [];
e.on("chat:translate", (request) => {
requests.push(request);
e.emit("chat:translation", {
...request,
ok: true,
text: "Bonjour <img src=x>",
language: "en",
});
});
e.emit("preferences", { sound: false });
e.emit("player", { index: 0 });
e.emit("state", state);
e.emit("chat:state", { canSend: true, translationTarget: "fr" });
e.emit("chat:messages", [
{
_id: "000000000000000000000070",
type: "text",
text: "Hello",
language: "en",
author: "Ada",
playerIndex: 1,
},
]);
},
{ state, game },
);
await page.locator(".chat-translate").click();
await page
.getByRole("button", {
name: "Translated · Show original",
exact: true,
})
.waitFor();
assert.equal(
await page
.locator('[data-message-id="000000000000000000000070"] img')
.count(),
0,
);
assert.match(
await page
.locator('[data-message-id="000000000000000000000070"]')
.textContent(),
/Bonjour <img src=x>/,
);
await page.locator(".chat-translate").click();
assert.match(
await page
.locator('[data-message-id="000000000000000000000070"]')
.textContent(),
/Hello/,
);
assert.equal(await page.evaluate(() => requests.length), 1);
const desktop = width > 1000;
const chatPanel = page.locator(".activity-chat");
const journalPanel = page.locator(".activity-journal");
if (desktop) {
assert.ok(await chatPanel.isVisible());
assert.ok(await journalPanel.isVisible());
const chatBounds = await chatPanel.boundingBox(),
journalBounds = await journalPanel.boundingBox();
assert.ok(Math.abs(chatBounds.y - journalBounds.y) < 1);
assert.ok(Math.abs(chatBounds.width - journalBounds.width) < 1);
assert.ok(chatBounds.x + chatBounds.width <= journalBounds.x + 1);
assert.equal(
await page.locator('.soup-activity [role="region"]').count(),
2,
);
} else {
assert.ok(await journalPanel.isHidden());
}
await page.locator('[data-tab="journal"]').click();
if (desktop) await page.locator(".topbar").scrollIntoViewIfNeeded();
await page.evaluate(() => {
window.restoredReceipts = [];
e.on("chat:read", (payload) => restoredReceipts.push(payload));
e.emit("chat:state", {
canSend: true,
readState: { userId: "self", lastReadAt: 500000 },
});
e.emit("chat:messages", [
{
_id: "000001f40000000000000001",
type: "text",
authorId: "other",
text: "Already read",
},
{
_id: "000001f50000000000000001",
type: "text",
authorId: "other",
text: "Unread after reload",
},
{
_id: "000001f60000000000000001",
type: "text",
authorId: "self",
text: "My own message",
},
{
_id: "000001f70000000000000001",
type: "system",
text: "Game started",
},
]);
});
await page.waitForFunction(
() => document.querySelector(".chat-count")?.textContent === "1",
);
await page.waitForTimeout(650);
assert.equal(
await page.evaluate(
() =>
restoredReceipts.filter(
({ messageId }) => messageId >= "000001f50000000000000001",
).length,
),
0,
"hidden or offscreen chat does not mark restored messages read",
);
if (desktop)
await page.locator('.pond-tools [data-ui="journal"]').click();
else await page.locator(".soup-chat-shortcut").click();
await page.waitForFunction(() =>
restoredReceipts.some(
({ messageId }) => messageId === "000001f70000000000000001",
),
);
assert.equal(
await page.locator(".chat-count").isHidden(),
true,
"visible chat clears restored unread, including beside the journal",
);
await page.screenshot({
path: `/tmp/soup-activity-${width}.png`,
fullPage: true,
});
if (desktop) {
// Resizing keeps the selected mobile tab, then restores both desktop panes.
await page.setViewportSize({ width: 1000, height: 950 });
await page.getByRole("tab", { name: "Journal", exact: true }).waitFor();
assert.ok(await chatPanel.isHidden());
assert.ok(await journalPanel.isVisible());
await page.getByRole("tab", { name: /^Chat/ }).click();
assert.ok(await chatPanel.isVisible());
assert.ok(await journalPanel.isHidden());
await page.setViewportSize({ width: 1001, height: 950 });
await page
.getByRole("region", { name: "Journal", exact: true })
.waitFor();
assert.ok(await chatPanel.isVisible());
const history = {
...state,
log: Array.from({ length: 100 }, (_, i) => ({
round: 1,
phase: 0,
text: `Colony moves ${i}.`,
})),
};
await page.evaluate((state) => e.emit("state", state), history);
await page.waitForFunction(() => {
const list = document.querySelector(".journal-list");
return (
list.scrollHeight > list.clientHeight &&
list.scrollHeight - list.clientHeight - list.scrollTop <= 1
);
});
// New entries must not pull someone away while they read older journal lines.
await page
.locator(".journal-list")
.evaluate((list) => (list.scrollTop -= 50));
await page.waitForTimeout(50);
const position = await page
.locator(".journal-list")
.evaluate((list) => list.scrollTop);
history.log.push({ round: 1, phase: 0, text: "One more move." });
await page.evaluate((state) => e.emit("state", state), history);
await page.waitForTimeout(50);
assert.equal(
await page
.locator(".journal-list")
.evaluate((list) => list.scrollTop),
position,
);
await page.setViewportSize({ width, height: 950 });
}
const journalState = prepared();
const quotedName = `O'Brien & "Co" <img src=x>`;
journalState.players[0].name = quotedName;
journalState.players[3].name = "coyotte508";
journalState.log = [
{ round: 2, phase: 0, text: "Maya #1 chooses south with Movement II." },
{ round: 2, phase: 0, text: "Maya #1 moves to C5." },
{
round: 2,
phase: 0,
text: "Maya #1 feeds on 1 green nutrient, 1 blue nutrient, 1 yellow nutrient at C5.",
},
{ round: 2, phase: 0, text: "Maya #1 excretes 2 red nutrients at C5." },
{ round: 2, phase: 0, text: "Leo #1 moves to C5.", genes: ["holding"] },
{ round: 2, phase: 2, text: "coyotte508 didn't buy any genes." },
{ round: 2, phase: 2, text: `${quotedName} didn't buy any genes.` },
];
await page.evaluate(
(state) => e.emit("state", state),
engine.stripSecret(journalState),
);
const combined = page.locator(".journal-event--combined");
assert.equal(await combined.count(), 1);
assert.equal(await combined.locator(".journal-amoeba").count(), 1);
assert.equal(await combined.locator(".journal-action").count(), 4);
assert.equal(await combined.locator(".food-amount").count(), 4);
assert.equal(
await page
.locator(".journal-event .gene-label")
.filter({ hasText: "Holding" })
.count(),
1,
);
const passEntry = page
.locator(".journal-event")
.filter({ hasText: "coyotte508" });
assert.equal(
await passEntry
.locator("[data-localized-rich-text]")
.getAttribute("data-localized-rich-text"),
"coyotte508 didn't buy any genes.",
);
for (const locale of ["fr", "en"]) {
await page.evaluate(
(locale) => e.emit("preferences", { sound: false, locale }),
locale,
);
const holding = locale === "fr" ? "Adhérence" : "Holding";
// Gene names and full sentences localize without reintroducing the shared portrait.
await page.waitForFunction(
(holding) =>
[...document.querySelectorAll(".journal-event .gene-label")].some(
(label) => label.textContent.includes(holding),
),
holding,
);
assert.equal(await combined.locator(".journal-amoeba").count(), 1);
assert.equal(await combined.locator(".food-amount").count(), 4);
const passText =
locale === "fr" ? "n’a acheté aucun gène." : "didn't buy any genes.";
assert.equal(
(await passEntry.textContent()).trim(),
`coyotte508 ${passText}`,
);
assert.equal(
(await page.locator(".last-move").textContent()).trim(),
`${quotedName} ${passText}`,
);
assert.equal(
await page.locator(".last-move img, .journal-event img").count(),
0,
);
assert.ok(
await page.evaluate(
() => document.documentElement.scrollWidth <= innerWidth,
),
);
}
await page.locator('[data-tab="journal"]').click();
await combined.scrollIntoViewIfNeeded();
await page
.locator(".soup-activity")
.screenshot({ path: `/tmp/soup-grouped-journal-${width}.png` });
await page.evaluate(() =>
e.emit("preferences", { sound: false, analysis: true }),
);
await page.waitForFunction(
() =>
!document.querySelector(".chat-translate")?.getBoundingClientRect()
.height,
);
assert.equal(
await page.getByRole("button", { name: /^Chat/ }).count(),
0,
);
assert.equal(await page.getByRole("tab", { name: /^Chat/ }).count(), 0);
assert.ok(await journalPanel.isVisible());
assert.equal(await page.locator(".soup-activity.is-split").count(), 0);
await page.screenshot({
path: `/tmp/${game}-analysis-${width}.png`,
fullPage: true,
});
assert.deepEqual(errors, []);
console.log(
`${game} ${width}: chat/journal layout, unread visibility, responsive scrolling, translation and analysis passed`,
);
await page.evaluate(
(state) => {
e.emit("player", {});
e.emit("state", state);
},
engine.stripSecret(prepared({ genes: ["armor", "holding"] })),
);
await checkHostPresentation(
page,
"e",
`/tmp/soup-board-thumbnail-${width}.png`,
);
assert.deepEqual(errors, []);
await page.close();
}
}
} finally {
await browser.close();
}