import { test, expect, type Page } from "@playwright/test";
import { execFileSync } from "node:child_process";
import { copyFileSync, existsSync, readFileSync, rmSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import * as urls from "./urls";
// ---------------------------------------------------------------------------
// MEDIA SCENES and the BAND CENSOR (report-to-video/post-media-scene.mjs,
// post-censor.mjs; knobs.md, "Media scenes" and "A post item"; operator, 4
// Nov: "make it obvious he's posted multiple different messages about this
// same picture" -- "censor everything neck down"). Fixture:
// e2e/fixtures/media-scenes-fixture.mjs -- p-j (words, joins), p-a (the
// picture, censored below the middle: the anchor), p-b and p-c (the same
// bytes again), p-x (another picture). No narration: each item is its read.
//
// MEDIA_SCENES_SHOTS=
screenshots there
// ---------------------------------------------------------------------------
const HERE = path.dirname(fileURLToPath(import.meta.url));
const FIXTURE = path.join(HERE, "..", ".e2e-song");
const DIR = path.join(FIXTURE, "reports", "media-scenes-fixture");
const MANIFEST = path.join(DIR, "video.manifest.json");
const PROJECT = "reports/media-scenes-fixture";
const SHOTS = process.env.MEDIA_SCENES_SHOTS ?? null;
const PIC = "posts-media/scenechan-x/a/a_1.png";
type Entry = { id: string; type: string; scene?: unknown; media?: Array<{ blur?: { band?: { below?: number }; style?: string } }> };
const timeline = () => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Entry[] }).timeline;
const umtool = (args: string[]) =>
execFileSync("node", ["bin/umtool.mjs", ...args], {
cwd: path.join(HERE, ".."),
encoding: "utf8",
env: { ...process.env, REPORTS_DIR: FIXTURE, CHANNELS_DIR: path.join(FIXTURE, "channels"), UMTOOL_CACHE_DIR: path.join(FIXTURE, "cache"), UMTOOL_PRINTS_CACHE: path.join(FIXTURE, "cache", "media-prints"), UMTOOL_MEDIA_DIR: "" },
});
test.beforeAll(() => {
if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`);
});
test.beforeEach(() => {
test.setTimeout(120_000);
copyFileSync(`${MANIFEST}.pristine`, MANIFEST);
rmSync(path.join(DIR, "revisions"), { recursive: true, force: true });
});
/** Play opened paused `at` seconds into `id`. */
async function playAt(page: Page, id: string, at: number) {
await page.goto(urls.playHref(PROJECT, { bare: true, clip: id, at }));
const player = page.locator(`[data-post-play="${id}"]`);
await expect(player).toBeVisible({ timeout: 15_000 });
await expect.poll(async () => Math.abs(Number(await player.getAttribute("data-post-s")) - at)).toBeLessThan(0.3);
return { player, frame: page.frameLocator('[data-post-card-frame="read"]') };
}
const tilesOf = async (player: ReturnType) =>
Object.fromEntries(((await player.getAttribute("data-post-thread-tiles")) ?? "").split(" ").filter(Boolean).map((x) => {
const [sc, v] = x.split("=");
return [sc, v.split("/").map(Number)];
})) as Record;
test("Play: one picture, several messages -- the picture held as the anchor's, the earlier messages stacked above, the one before giving way", async ({ page }) => {
await page.setViewportSize({ width: 1366, height: 1000 });
// The join item (words only): in the scene, the picture beside its words -- the anchor's, censored as it is.
{
const { player } = await playAt(page, "p-j", 1);
await expect(player).toHaveAttribute("data-post-scene", "s1");
await expect(player).toHaveAttribute("data-post-scene-n", "1/4");
const m = player.locator("[data-post-media]");
await expect(m).toHaveCount(1);
await expect(m.locator("img")).toHaveAttribute("src", new RegExp(encodeURIComponent(PIC)));
await expect(m).toHaveAttribute("data-post-blurred", "band");
}
// p-b, its first frame: p-a (the message just before) in full, his own hidden under it.
{
const { player, frame } = await playAt(page, "p-b", 0);
await expect(player).toHaveAttribute("data-post-scene-n", "3/4");
await expect(frame.locator('[data-thread-slot="scene:0"] [data-scene-post="p-j"]')).toHaveCount(1);
await expect(frame.locator('[data-thread-slot="scene:1"] [data-scene-post="p-a"]')).toHaveCount(1);
const t = await tilesOf(player);
expect(t["scene:1"][0]).toBeGreaterThan(0.95);
expect(t.post[1]).toBeLessThan(0.2);
expect(t["scene:0"]).toEqual([0.62, 0.5]);
// The picture: the ANCHOR's file and censor, not its own copy's.
await expect(player.locator("[data-post-media] img")).toHaveAttribute("src", new RegExp(encodeURIComponent(PIC)));
await expect(player.locator("[data-post-media]")).toHaveAttribute("data-post-censor-band", "0,0.5,1,0.5");
if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "media-scene-p-b-start.png") });
}
// Two seconds in: both earlier messages small and dim above, his own up, lit.
{
const { player, frame } = await playAt(page, "p-b", 2);
await expect(player).toHaveAttribute("data-post-thread-tiles", "scene:0=0.62/0.5 scene:1=0.62/0.5 post=1/1");
await expect.poll(async () => frame.locator('[data-thread-slot="scene:1"]').getAttribute("data-thread-state")).toBe("context");
await expect.poll(async () => frame.locator('[data-thread-slot="post"]').getAttribute("data-thread-state")).toBe("focus");
// Oldest up top: the earlier messages above his post.
const tops = await frame.locator("[data-thread-slot]").evaluateAll((els) => els.map((el) => [el.getAttribute("data-thread-slot"), Math.round(el.getBoundingClientRect().top)]));
expect(tops.map((x) => x[0])).toEqual(["scene:0", "scene:1", "post"]);
expect(Number(tops[0][1])).toBeLessThan(Number(tops[2][1]));
if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "media-scene-p-b-later.png") });
}
// Another picture: no scene, its own card alone.
{
const { player, frame } = await playAt(page, "p-x", 1);
await expect(player).not.toHaveAttribute("data-post-scene", /./);
await expect(frame.locator("[data-thread-slot]")).toHaveCount(0);
}
// umtool posts scenes says the same.
const v = JSON.parse(umtool(["posts", "scenes", PROJECT, "--json"])) as { scenes: { ids: string[]; anchor: string }[] };
expect(v.scenes.map((s) => `${s.ids.join(",")}@${s.anchor}`)).toEqual(["p-j,p-a,p-b,p-c@p-a"]);
});
test("Play: the band censor -- blurred below the middle, then black above a line, then pixelated (set-item's censor knob)", async ({ page }) => {
await page.setViewportSize({ width: 1366, height: 1000 });
{
const { player } = await playAt(page, "p-a", 1);
const m = player.locator("[data-post-media]");
await expect(m).toHaveAttribute("data-post-blurred", "band");
await expect(m).toHaveAttribute("data-post-censor-style", "blur");
await expect(m).toHaveAttribute("data-post-censor-band", "0,0.5,1,0.5");
const box = m.locator("[data-post-blur-box]");
await expect(box).toHaveCount(1);
expect(await box.evaluate((el) => (el as HTMLElement).style.top)).toBe("50%");
expect(await box.evaluate((el) => getComputedStyle(el).backdropFilter)).toMatch(/blur/);
// The label at the band's corner, not the picture's.
expect(await m.locator("[data-post-blur-label]").evaluate((el) => (el as HTMLElement).style.top)).toContain("50%");
if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "media-scene-band-blur.png") });
}
umtool(["posts", "set-item", PROJECT, "p-a", "media.0.censor=above:0.4:black"]);
expect(timeline().find((e) => e.id === "p-a")?.media?.[0].blur).toEqual({ on: true, band: { above: 0.4 }, style: "black" });
{
const { player } = await playAt(page, "p-a", 1);
const m = player.locator("[data-post-media]");
await expect(m).toHaveAttribute("data-post-censor-style", "black");
await expect(m).toHaveAttribute("data-post-censor-band", "0,0,1,0.4");
expect(await m.locator("[data-post-blur-box]").evaluate((el) => getComputedStyle(el).backgroundColor)).toBe("rgb(0, 0, 0)");
// The scene's later message draws the anchor's censor.
const b = (await playAt(page, "p-c", 1)).player.locator("[data-post-media]");
await expect(b).toHaveAttribute("data-post-censor-style", "black");
}
umtool(["posts", "set-item", PROJECT, "p-a", "media.0.censor=below:0.5:pixelate:9"]);
{
const { player } = await playAt(page, "p-a", 1);
const m = player.locator("[data-post-media]");
await expect(m).toHaveAttribute("data-post-censor-style", "pixelate");
// The pixels drawn coarse on a canvas over the band, the head left alone.
const canvas = m.locator("[data-post-pixelated]");
await expect(canvas).toHaveCount(1);
await expect.poll(async () => canvas.evaluate((c) => {
const cv = c as HTMLCanvasElement;
const ctx = cv.getContext("2d");
if (!ctx || !cv.width) return "none";
const at = (y: number) => ctx.getImageData(Math.floor(cv.width / 2), Math.floor(cv.height * y), 1, 1).data[3];
return `${at(0.25) > 0 ? "head" : "-"}/${at(0.75) > 0 ? "band" : "-"}`;
}), { timeout: 10_000 }).toBe("-/band");
if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "media-scene-band-pixelate.png") });
}
umtool(["posts", "set-item", PROJECT, "p-a", "media.0.censor=off"]);
expect(timeline().find((e) => e.id === "p-a")?.media?.[0].blur).toEqual({ on: false, strength: 9 });
});
test("the bench: the band's line dragged writes the censor; the scene block names the anchor and keeps an item out of the scene", async ({ page }) => {
await page.setViewportSize({ width: 1500, height: 1100 });
await page.goto(urls.postBenchHref(PROJECT, "p-a"));
const block = page.locator('[data-post-bench-scene="s1"]');
await expect(block).toBeVisible();
await expect(block.locator("[data-post-bench-scene-members]")).toContainText("message 2 of 4");
await expect(page.locator('[data-post-bench-censor-band="0"]')).toHaveValue("below");
const line = page.locator('[data-post-bench-band-line="below"]');
await expect(line).toHaveAttribute("data-band-at", "0.5");
// Drag the line up to 30% of the picture's height.
const pad = page.locator('[data-post-bench-blur-pad="0"]');
const pb = (await pad.boundingBox())!;
const lb = (await line.boundingBox())!;
await page.mouse.move(lb.x + lb.width / 3, lb.y + lb.height / 2);
await page.mouse.down();
await page.mouse.move(lb.x + lb.width / 3, pb.y + pb.height * 0.3, { steps: 6 });
await page.mouse.up();
await expect.poll(async () => Number(await line.getAttribute("data-band-at"))).toBeCloseTo(0.3, 1);
// The player shows it at once (the anchor's own bench previews its edit).
await expect.poll(async () => (await page.locator("[data-post-play] [data-post-media]").getAttribute("data-post-censor-band")) ?? "").toMatch(/^0,0\.(2|3)\d*,1,/);
await page.locator('[data-post-bench-censor-style="0"]').selectOption("pixelate");
await expect(page.locator("[data-post-play] [data-post-media]")).toHaveAttribute("data-post-censor-style", "pixelate");
if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "media-scene-bench-band.png") });
await page.locator("[data-post-bench-save]").click();
await expect.poll(() => timeline().find((e) => e.id === "p-a")?.media?.[0].blur?.style).toBe("pixelate");
expect(timeline().find((e) => e.id === "p-a")?.media?.[0].blur?.band?.below).toBeCloseTo(0.3, 1);
// A later message's bench: the anchor named (its censor is set there); kept out, the scene shrinks.
await page.goto(urls.postBenchHref(PROJECT, "p-b"));
await expect(page.locator('[data-post-bench-scene-anchor="p-a"]')).toBeVisible();
await page.locator("[data-post-bench-scene-knob]").selectOption("off");
await page.locator("[data-post-bench-save]").click();
await expect.poll(() => timeline().find((e) => e.id === "p-b")?.scene).toBe(false);
const v = JSON.parse(umtool(["posts", "scenes", PROJECT, "--json"])) as { scenes: { ids: string[] }[] };
expect(v.scenes.map((s) => s.ids.join(","))).toEqual(["p-j,p-a"]);
});