Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Tests: phone layout sweep that can gate, shell e2e, unit tests for the shell logic

Claude71187cf0cb36
diff --git a/package.json b/package.json
index 925f53ff..85a263ef 100644
--- a/package.json
+++ b/package.json
@@ -10,6 +10,8 @@
"lint": "eslint",
"test": "vitest run",
"test:e2e:comfyui": "node tests/e2e/comfyui-selftest.mjs",
+ "test:e2e:mobile": "node tests/e2e/no-horizontal-scroll.mjs",
+ "test:e2e:shell": "node tests/e2e/shell.mjs",
"gen:catalog": "python3 scripts/gen-cloud-models.py && python3 scripts/gen-higgsfield-models.py && python3 scripts/gen-oss-loras.py && node scripts/gen-icon-map.mjs",
"typecheck": "tsc --noEmit"
},
diff --git a/tests/e2e/_browser.mjs b/tests/e2e/_browser.mjs
new file mode 100644
index 00000000..951ec0c3
--- /dev/null
+++ b/tests/e2e/_browser.mjs
@@ -0,0 +1,68 @@
+// Shared by the Playwright scripts in tests/e2e (not a test itself).
+//
+// Playwright: the `playwright` (or `playwright-core`) package if it resolves from the repo, else the
+// global install at /opt/node22/lib/node_modules. Chromium: $CHROMIUM_PATH, else the newest
+// /opt/pw-browsers/chromium-*/chrome-linux/chrome, else Playwright's own.
+import fs from "node:fs";
+import path from "node:path";
+import { createRequire } from "node:module";
+import { fileURLToPath } from "node:url";
+
+export const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
+
+export function loadPlaywright() {
+ for (const from of [path.join(root, "package.json"), "/opt/node22/lib/node_modules/"]) {
+ const req = createRequire(from);
+ for (const name of ["playwright", "playwright-core"]) {
+ try {
+ return req(name);
+ } catch {}
+ }
+ }
+ throw new Error("Playwright not found: install playwright-core or run where the global install exists");
+}
+
+export function chromiumPath() {
+ if (process.env.CHROMIUM_PATH) return process.env.CHROMIUM_PATH;
+ const dir = "/opt/pw-browsers";
+ if (!fs.existsSync(dir)) return undefined;
+ const newest = fs
+ .readdirSync(dir)
+ .filter((d) => /^chromium-\d+$/.test(d))
+ .sort((a, b) => Number(b.split("-")[1]) - Number(a.split("-")[1]))[0];
+ const exe = newest && path.join(dir, newest, "chrome-linux/chrome");
+ return exe && fs.existsSync(exe) ? exe : undefined;
+}
+
+export async function launch() {
+ const { chromium } = loadPlaywright();
+ return chromium.launch({ executablePath: chromiumPath() });
+}
+
+export const PHONE = { viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true };
+export const DESKTOP = { viewport: { width: 1440, height: 900 } };
+
+/**
+ * Open a route and wait until it has rendered: the `load` event, then the page's first heading (or
+ * a short timeout for pages without one), then a moment for late layout. Never waits for network
+ * idle: pages that stream live updates (the generations feed) keep a connection open for good.
+ */
+export async function openRoute(page, url, { settleMs = 700, timeout = 60_000 } = {}) {
+ await page.goto(url, { waitUntil: "load", timeout });
+ await page
+ .locator("h1")
+ .first()
+ .waitFor({ timeout: 15_000 })
+ .catch(() => {});
+ await page.waitForTimeout(settleMs);
+}
+
+/** POST JSON to the app; resolves to the parsed body or null. */
+export async function post(app, route, body) {
+ try {
+ const res = await fetch(app + route, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+ return res.ok ? await res.json() : null;
+ } catch {
+ return null;
+ }
+}
diff --git a/tests/e2e/no-horizontal-scroll.mjs b/tests/e2e/no-horizontal-scroll.mjs
index 64932663..06901f06 100644
--- a/tests/e2e/no-horizontal-scroll.mjs
+++ b/tests/e2e/no-horizontal-scroll.mjs
@@ -1,28 +1,23 @@
-// Phone-width layout check: no route may scroll sideways at 390 px.
-// Usage: node tests/e2e/no-horizontal-scroll.mjs [appUrl] [--dark] [--routes=/a,/b]
-// (app must be running; demo mode is fine). Exits 1 if any page is wider than the screen.
+// Phone-width layout check: no route may scroll sideways at 390 px, in light and dark mode.
+// Usage: node tests/e2e/no-horizontal-scroll.mjs [appUrl] [--light | --dark] [--routes=/a,/b]
+// (pnpm test:e2e:mobile; the app must be running, demo mode is fine). Exits 1 if any page is wider
+// than the screen or doesn't load.
//
-// Every page under src/app/(studio) is visited (dynamic segments with a sample id), plus /login and
-// an unknown URL (the 404 page). For each route it asserts document.documentElement.scrollWidth ===
-// clientWidth after the page settles, and names the widest elements when it isn't.
-//
-// Playwright: uses the `playwright` (or `playwright-core`) package if it resolves, else the global
-// install at /opt/node22/lib/node_modules. Chromium: $CHROMIUM_PATH, else the newest
-// /opt/pw-browsers/chromium-*/chrome-linux/chrome, else Playwright's own.
+// Every page under src/app/(studio) is visited, dynamic segments with a sample id (a cinema project and
+// a canvas are created for the purpose), plus /login and an unknown URL (the 404 page). For each route it
+// asserts document.documentElement.scrollWidth === clientWidth once the page has rendered, and names
+// the widest elements when it isn't. Pages that don't load are reported apart from layout failures.
import fs from "node:fs";
import path from "node:path";
-import { createRequire } from "node:module";
-import { fileURLToPath } from "node:url";
+import { launch, openRoute, PHONE, post, root } from "./_browser.mjs";
const args = process.argv.slice(2);
const app = (args.find((a) => !a.startsWith("--")) ?? "http://localhost:3000").replace(/\/$/, "");
-const dark = args.includes("--dark");
+const schemes = args.includes("--dark") ? ["dark"] : args.includes("--light") ? ["light"] : ["light", "dark"];
const only = args.find((a) => a.startsWith("--routes="))?.slice(9).split(",").filter(Boolean);
-const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
-
/** Static routes from the file system, plus samples for the dynamic ones. */
-function discoverRoutes() {
+async function discoverRoutes() {
const base = path.join(root, "src/app/(studio)");
const out = [];
const walk = (dir, url) => {
@@ -36,78 +31,82 @@ function discoverRoutes() {
if (fs.existsSync(path.join(dir, "page.tsx"))) out.push(url || "/");
};
walk(base, "");
- return [...new Set([...out.sort(), "/apps/app-face-swap", "/apps/app-packshot", "/elements/does-not-exist", "/library?tab=favorites", "/login", "/this-page-does-not-exist"])];
+ const project = await post(app, "/api/cinema/projects", { name: "Layout check" });
+ const canvas = await post(app, "/api/canvases", { name: "Layout check" });
+ const samples = [
+ "/apps/app-face-swap",
+ "/apps/app-packshot",
+ "/elements/does-not-exist",
+ "/library?tab=favorites",
+ project?.id ? `/cinema/${project.id}` : null,
+ canvas?.id ? `/canvas/${canvas.id}` : null,
+ "/login",
+ "/this-page-does-not-exist",
+ ].filter(Boolean);
+ if (!project?.id) console.log("note: couldn't create a sample cinema project, /cinema/[id] is not checked");
+ if (!canvas?.id) console.log("note: couldn't create a sample canvas, /canvas/[id] is not checked");
+ return [...new Set([...out.sort(), ...samples])];
}
-function loadPlaywright() {
- for (const from of [path.join(root, "package.json"), "/opt/node22/lib/node_modules/"]) {
- const req = createRequire(from);
- for (const name of ["playwright", "playwright-core"]) {
- try {
- return req(name);
- } catch {}
+const routes = only ?? (await discoverRoutes());
+const browser = await launch();
+const wide = [];
+const broken = [];
+for (const scheme of schemes) {
+ console.log(`\n${scheme} mode, 390 × 844`);
+ const ctx = await browser.newContext({ ...PHONE, colorScheme: scheme });
+ for (const route of routes) {
+ const page = await ctx.newPage();
+ try {
+ await openRoute(page, app + route);
+ } catch (e) {
+ console.log(`LOAD ${route.padEnd(36)} ${e.message.split("\n")[0]}`);
+ broken.push(`${route} (${scheme})`);
+ await page.close();
+ continue;
}
- }
- throw new Error("Playwright not found: install playwright-core or run where the global install exists");
-}
-
-function chromiumPath() {
- if (process.env.CHROMIUM_PATH) return process.env.CHROMIUM_PATH;
- const dir = "/opt/pw-browsers";
- if (!fs.existsSync(dir)) return undefined;
- const newest = fs
- .readdirSync(dir)
- .filter((d) => /^chromium-\d+$/.test(d))
- .sort((a, b) => Number(b.split("-")[1]) - Number(a.split("-")[1]))[0];
- const exe = newest && path.join(dir, newest, "chrome-linux/chrome");
- return exe && fs.existsSync(exe) ? exe : undefined;
-}
-
-const { chromium } = loadPlaywright();
-const browser = await chromium.launch({ executablePath: chromiumPath() });
-const ctx = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true, colorScheme: dark ? "dark" : "light" });
-const routes = only ?? discoverRoutes();
-const failures = [];
-for (const route of routes) {
- const page = await ctx.newPage();
- try {
- await page.goto(app + route, { waitUntil: "networkidle", timeout: 60_000 });
- await page.waitForTimeout(800);
- const r = await page.evaluate(() => {
- const W = document.documentElement.clientWidth;
- const wide = [];
- const describe = (el, b) => `${el.tagName.toLowerCase()}${el.id ? `#${el.id}` : ""}.${String(el.className).split(" ").slice(0, 4).join(".")} (right ${Math.round(b.right)}px)`;
- if (document.documentElement.scrollWidth > W) {
- const sticking = [...document.querySelectorAll("body *")].map((el) => [el, el.getBoundingClientRect()]).filter(([, b]) => b.right > W + 1 && b.width);
- // Prefer elements not inside a scroller that itself fits (those are the real culprits).
- for (const [el, b] of sticking) {
- let contained = false;
- for (let p = el.parentElement; p && p !== document.body; p = p.parentElement) {
- if (["auto", "scroll", "hidden", "clip"].includes(getComputedStyle(p).overflowX) && p.getBoundingClientRect().right <= W + 1) {
- contained = true;
- break;
+ try {
+ const r = await page.evaluate(() => {
+ const W = document.documentElement.clientWidth;
+ const culprits = [];
+ const describe = (el, b) => `${el.tagName.toLowerCase()}${el.id ? `#${el.id}` : ""}.${String(el.className).split(" ").slice(0, 4).join(".")} (right ${Math.round(b.right)}px)`;
+ if (document.documentElement.scrollWidth > W) {
+ const sticking = [...document.querySelectorAll("body *")].map((el) => [el, el.getBoundingClientRect()]).filter(([, b]) => b.right > W + 1 && b.width);
+ // Prefer elements not inside a scroller that itself fits (those are the real culprits).
+ for (const [el, b] of sticking) {
+ let contained = false;
+ for (let p = el.parentElement; p && p !== document.body; p = p.parentElement) {
+ if (["auto", "scroll", "hidden", "clip"].includes(getComputedStyle(p).overflowX) && p.getBoundingClientRect().right <= W + 1) {
+ contained = true;
+ break;
+ }
}
+ if (!contained) culprits.push(describe(el, b));
+ if (culprits.length >= 5) break;
}
- if (!contained) wide.push(describe(el, b));
- if (wide.length >= 5) break;
+ if (!culprits.length) for (const [el, b] of sticking.slice(0, 5)) culprits.push(describe(el, b));
}
- if (!wide.length) for (const [el, b] of sticking.slice(0, 5)) wide.push(describe(el, b));
+ return { scrollWidth: document.documentElement.scrollWidth, clientWidth: W, culprits };
+ });
+ const ok = r.scrollWidth === r.clientWidth;
+ console.log(`${ok ? "ok " : "WIDE"} ${route.padEnd(36)} ${r.scrollWidth}/${r.clientWidth}`);
+ if (!ok) {
+ for (const c of r.culprits) console.log(` ${c}`);
+ wide.push(`${route} (${scheme})`);
}
- return { scrollWidth: document.documentElement.scrollWidth, clientWidth: W, wide };
- });
- const ok = r.scrollWidth === r.clientWidth;
- console.log(`${ok ? "ok " : "FAIL"} ${route.padEnd(32)} ${r.scrollWidth}/${r.clientWidth}`);
- if (!ok) {
- for (const w of r.wide) console.log(` ${w}`);
- failures.push(route);
+ } catch (e) {
+ console.log(`LOAD ${route.padEnd(36)} ${e.message.split("\n")[0]}`);
+ broken.push(`${route} (${scheme})`);
+ } finally {
+ await page.close();
}
- } catch (e) {
- console.log(`FAIL ${route.padEnd(32)} ${e.message.split("\n")[0]}`);
- failures.push(route);
- } finally {
- await page.close();
}
+ await ctx.close();
}
await browser.close();
-console.log(failures.length ? `\n${failures.length} of ${routes.length} routes scroll sideways at 390 px: ${failures.join(", ")}` : `\nAll ${routes.length} routes fit 390 px.`);
-process.exit(failures.length ? 1 : 0);
+const checks = routes.length * schemes.length;
+console.log("");
+if (wide.length) console.log(`${wide.length} of ${checks} pages scroll sideways at 390 px: ${wide.join(", ")}`);
+if (broken.length) console.log(`${broken.length} of ${checks} pages didn't load: ${broken.join(", ")}`);
+if (!wide.length && !broken.length) console.log(`All ${routes.length} routes fit 390 px (${schemes.join(" and ")}).`);
+process.exit(wide.length || broken.length ? 1 : 0);
diff --git a/tests/e2e/shell.mjs b/tests/e2e/shell.mjs
new file mode 100644
index 00000000..39167897
--- /dev/null
+++ b/tests/e2e/shell.mjs
@@ -0,0 +1,76 @@
+// App-shell checks in a real browser (the app must be running; demo mode is fine).
+// Usage: node tests/e2e/shell.mjs [appUrl] (pnpm test:e2e:shell). Exits 1 on the first failure.
+//
+// 1. Phone: the sidebar drawer closes when a link in it is tapped (nav item, New creation, footer).
+// 2. A collapsed sidebar group still shows the page you're on.
+// 3. Deep links into Settings (/settings#comfyui) scroll to the section after a client navigation.
+// 4. Galleries: "Show more" pressed from the keyboard moves focus to the first new card.
+import assert from "node:assert/strict";
+import { DESKTOP, launch, openRoute, PHONE } from "./_browser.mjs";
+
+const app = (process.argv.slice(2).find((a) => !a.startsWith("--")) ?? "http://localhost:3000").replace(/\/$/, "");
+const browser = await launch();
+const step = (name) => console.log(`- ${name}`);
+
+try {
+ {
+ const ctx = await browser.newContext(PHONE);
+ const page = await ctx.newPage();
+ for (const [from, link, to] of [
+ ["/models", /^Effects$/, "/effects"],
+ ["/effects", /^New creation/, "/"],
+ ["/", /^Settings$/, "/settings"],
+ // The footer's engine status links to Settings too.
+ ["/models", /^Cloud models/, "/settings"],
+ ]) {
+ step(`phone: tapping “${link.source.replace(/[\^$]/g, "")}” in the drawer on ${from} closes it`);
+ await openRoute(page, app + from);
+ await page.getByRole("button", { name: "Toggle Sidebar" }).first().tap();
+ const drawer = page.locator('[data-mobile="true"]');
+ await drawer.waitFor({ state: "visible" });
+ await drawer.getByRole("link", { name: link }).first().tap();
+ await page.waitForURL((u) => new URL(u).pathname === to, { timeout: 20_000 });
+ await drawer.waitFor({ state: "detached", timeout: 5_000 });
+ }
+ await ctx.close();
+ }
+ {
+ const ctx = await browser.newContext(DESKTOP);
+ const page = await ctx.newPage();
+ step("a collapsed group still shows the active page");
+ await openRoute(page, `${app}/cinema`);
+ const studios = page.locator('[data-nav-group="studios"]');
+ if ((await studios.getAttribute("data-open")) !== "false") await studios.locator("[data-nav-toggle]").click();
+ assert.equal(await studios.getAttribute("data-open"), "false");
+ assert.ok(await studios.getByRole("link", { name: "Cinema Studio" }).isVisible(), "Cinema Studio stays visible");
+ assert.ok(!(await studios.getByRole("link", { name: "Upscale" }).isVisible()), "other Studios items are folded away");
+ await studios.locator("[data-nav-toggle]").click(); // leave it open for the next run
+
+ step("/workflows → Server settings scrolls to the ComfyUI section");
+ await openRoute(page, `${app}/workflows`);
+ await page.getByRole("link", { name: "Server settings" }).click();
+ await page.waitForURL(/\/settings#comfyui$/);
+ await page.locator("#comfyui").waitFor();
+ await page.waitForTimeout(400);
+ const top = await page.locator("#comfyui").evaluate((el) => el.getBoundingClientRect().top);
+ assert.ok(top >= -2 && top < 300, `ComfyUI section near the top of the screen (top ${Math.round(top)}px)`);
+
+ step("Show more from the keyboard focuses the first new card");
+ await openRoute(page, `${app}/effects`);
+ const cards = page.locator("main a[href^='/video?preset=']");
+ const before = await cards.count();
+ const more = page.getByRole("button", { name: /Show more/ });
+ await more.focus();
+ await page.keyboard.press("Enter");
+ await page.waitForTimeout(300);
+ const focused = await page.evaluate(() => document.activeElement?.getAttribute("href"));
+ assert.equal(focused, await cards.nth(before).getAttribute("href"));
+ await ctx.close();
+ }
+ console.log("\nShell checks passed.");
+} catch (e) {
+ console.error(`\nFAILED: ${e.message}`);
+ process.exitCode = 1;
+} finally {
+ await browser.close();
+}
diff --git a/tests/shell-logic.test.ts b/tests/shell-logic.test.ts
new file mode 100644
index 00000000..575ded10
--- /dev/null
+++ b/tests/shell-logic.test.ts
@@ -0,0 +1,327 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { EFFECTS, MOTIONS } from "@/lib/catalog";
+import { copyText } from "@/lib/clipboard";
+import { loseContext, releaseVideo } from "@/lib/media-release";
+import { GLYPHS, MOVE_GLYPH, glyphFor } from "@/lib/move-glyphs";
+import {
+ CAMERA_MOVES,
+ effectFx,
+ homeEffects,
+ interleaveByCategory,
+ motionMove,
+ previewFlip,
+ previewFor,
+ stableHash,
+ toPresetCard,
+ type CameraMove,
+} from "@/lib/preset-cards";
+import { createPlaybackStore, MIN_VISIBLE, type PlaybackEnv } from "@/lib/preview-playback";
+import { pageAfter, progressiveStart, syncProgressive } from "@/lib/progressive";
+import { storyboardName } from "@/lib/storyboard-board";
+import { capabilityGroup, usedByIndex } from "@/lib/workflow-usage";
+
+describe("workflow 'used by' index", () => {
+ const used = usedByIndex([
+ { endpoint: "flux-dev-t2i", name: "FLUX.1 dev" },
+ { endpoint: "flux-dev-t2i", name: "FLUX.1 dev" },
+ { endpoint: "flux-dev-t2i", name: "FLUX Krea" },
+ { endpoint: "video-concat-{n}", name: "Join clips" },
+ { endpoint: "wan.2-{n}x", name: "Dotted" },
+ ]);
+
+ it("matches exact endpoints and dedupes names in route order", () => {
+ expect(used("flux-dev-t2i")).toEqual(["FLUX.1 dev", "FLUX Krea"]);
+ expect(used("flux-dev")).toEqual([]);
+ });
+
+ it("matches {n} endpoints for any count, including two-digit ones", () => {
+ expect(used("video-concat-2")).toEqual(["Join clips"]);
+ expect(used("video-concat-12")).toEqual(["Join clips"]);
+ expect(used("video-concat-")).toEqual([]);
+ expect(used("video-concat-2b")).toEqual([]);
+ });
+
+ it("treats the rest of a pattern literally", () => {
+ expect(used("wan.2-4x")).toEqual(["Dotted"]);
+ expect(used("wanX2-4x")).toEqual([]);
+ });
+
+ it("groups capabilities by what they make, for the filter chips", () => {
+ expect(capabilityGroup("t2i")).toBe("Image");
+ expect(capabilityGroup("bg-remove-video")).toBe("Video");
+ expect(capabilityGroup("separate-audio")).toBe("Audio");
+ expect(capabilityGroup("transcribe")).toBe("Text & 3D");
+ expect(capabilityGroup("image-to-3d")).toBe("Text & 3D");
+ // Not operations, still sorted sensibly.
+ expect(capabilityGroup("draw-to-video")).toBe("Video");
+ expect(capabilityGroup("camera-motion")).toBe("Video");
+ expect(capabilityGroup("style-reference")).toBe("Image");
+ expect(capabilityGroup("character-sheet")).toBe("Image");
+ });
+});
+
+describe("progressive list paging", () => {
+ it("keeps its count while the filter is unchanged and starts over when it changes", () => {
+ let s = progressiveStart("all", 30);
+ s = { ...s, shown: pageAfter(s.shown, 40) };
+ expect(s.shown).toBe(70);
+ expect(syncProgressive(s, "all", 30)).toBe(s);
+ expect(syncProgressive(s, "fire", 30)).toEqual({ key: "fire", shown: 30 });
+ });
+
+ it("always grows by at least one", () => {
+ expect(pageAfter(5, 0)).toBe(6);
+ });
+});
+
+/** A fake browser for the playback store. */
+function fakeEnv({ hover = false, reduced = false, height = 800 } = {}) {
+ let ioCallback: IntersectionObserverCallback | null = null;
+ const observed = new Set<Element>();
+ const scroll = new Set<() => void>();
+ const frames: (() => void)[] = [];
+ const flush = () => frames.splice(0).forEach((f) => f());
+ const env: PlaybackEnv = {
+ matches: (q) => (q.includes("reduced-motion") ? reduced : q.includes("hover") ? hover : false),
+ IntersectionObserver: class {
+ constructor(cb: IntersectionObserverCallback) {
+ ioCallback = cb;
+ }
+ observe(el: Element) {
+ observed.add(el);
+ }
+ unobserve(el: Element) {
+ observed.delete(el);
+ }
+ },
+ requestFrame: (cb) => frames.push(cb),
+ viewportHeight: () => height,
+ onScroll: (cb) => scroll.add(cb),
+ offScroll: (cb) => scroll.delete(cb),
+ };
+ const card = (top: number, h = 200) => ({ getBoundingClientRect: () => ({ top, height: h }) }) as unknown as Element;
+ const intersect = (entries: [Element, number][]) => {
+ ioCallback!(entries.map(([target, ratio]) => ({ target, intersectionRatio: ratio, isIntersecting: ratio > 0 }) as IntersectionObserverEntry), null as never);
+ flush();
+ };
+ return { env, card, intersect, observed, scroll };
+}
+
+describe("preview playback store", () => {
+ it("plays one preview at a time and stops only the one playing", () => {
+ const { env } = fakeEnv({ hover: true });
+ const store = createPlaybackStore(env);
+ const seen: (string | null)[] = [];
+ store.subscribe(() => seen.push(store.getActive()));
+ store.play("a");
+ store.play("b");
+ expect(store.isActive("a")).toBe(false);
+ expect(store.isActive("b")).toBe(true);
+ store.stop("a");
+ expect(store.getActive()).toBe("b");
+ store.stop("b");
+ expect(seen).toEqual(["a", "b", null]);
+ });
+
+ it("plays nothing when the user prefers reduced motion", () => {
+ const store = createPlaybackStore(fakeEnv({ reduced: true }).env);
+ store.play("a");
+ expect(store.getActive()).toBeNull();
+ expect(store.reducedMotion()).toBe(true);
+ });
+
+ it("on phones plays the mostly visible card nearest the middle of the screen", () => {
+ const { env, card, intersect } = fakeEnv({ height: 800 });
+ const store = createPlaybackStore(env);
+ const top = card(0); // centre at 100
+ const mid = card(320); // centre at 420, nearest 400
+ const low = card(560); // centre at 660
+ store.watch(top, "top");
+ store.watch(mid, "mid");
+ store.watch(low, "low");
+ intersect([
+ [top, 1],
+ [mid, MIN_VISIBLE - 0.1],
+ [low, 1],
+ ]);
+ // The middle card isn't visible enough yet.
+ expect(store.getActive()).toBe("low");
+ intersect([[mid, 0.9]]);
+ expect(store.getActive()).toBe("mid");
+ });
+
+ it("cleans up: unwatching stops the card and the last one removes the scroll listener", () => {
+ const { env, card, intersect, observed, scroll } = fakeEnv();
+ const store = createPlaybackStore(env);
+ const a = card(300);
+ const b = card(900);
+ const offA = store.watch(a, "a");
+ const offB = store.watch(b, "b");
+ expect(scroll.size).toBe(1);
+ intersect([[a, 1]]);
+ expect(store.getActive()).toBe("a");
+ offA();
+ expect(store.getActive()).toBeNull();
+ expect(observed.has(a)).toBe(false);
+ expect(scroll.size).toBe(1);
+ offB();
+ expect(store.watchedCount()).toBe(0);
+ expect(scroll.size).toBe(0);
+ });
+
+ it("does nothing without IntersectionObserver", () => {
+ const { env, card } = fakeEnv();
+ const store = createPlaybackStore({ ...env, IntersectionObserver: undefined });
+ store.watch(card(0), "a")();
+ expect(store.watchedCount()).toBe(0);
+ });
+});
+
+describe("camera move diagrams", () => {
+ it("draws every camera move", () => {
+ for (const move of Object.keys(CAMERA_MOVES) as CameraMove[]) {
+ const parts = glyphFor(move);
+ expect(parts.length, move).toBeGreaterThan(0);
+ for (const p of parts) expect(p.d, move).toMatch(/^[MLHVQCSAZmlhvaz\d\s.,-]+$/);
+ }
+ });
+
+ it("keeps every glyph inside its 48 × 36 box", () => {
+ for (const [name, parts] of Object.entries(GLYPHS)) {
+ for (const p of parts) {
+ // Absolute M/L coordinates only (arcs and relative commands are checked by eye).
+ for (const m of p.d.matchAll(/[ML](-?[\d.]+) (-?[\d.]+)/g)) {
+ const [x, y] = [Number(m[1]), Number(m[2])];
+ expect(x, name).toBeGreaterThanOrEqual(0);
+ expect(x, name).toBeLessThanOrEqual(48);
+ expect(y, name).toBeGreaterThanOrEqual(0);
+ expect(y, name).toBeLessThanOrEqual(36);
+ }
+ }
+ }
+ });
+
+ it("tells the common moves apart", () => {
+ const glyph = (name: string) => MOVE_GLYPH[motionMove(MOTIONS.find((m) => m.name === name)!)];
+ const names = ["Zoom In", "Zoom Out", "Dolly In", "Dolly Out", "Crash Zoom In", "Dolly Zoom In", "360 Orbit", "Arc Left", "Arc Right", "Crane Up", "Crane Down", "Truck Right", "Dutch Angle"];
+ const glyphs = names.filter((n) => MOTIONS.some((m) => m.name === n)).map(glyph);
+ expect(new Set(glyphs).size).toBe(glyphs.length);
+ // Across the whole gallery the diagrams vary a lot.
+ expect(new Set(MOTIONS.map((m) => MOVE_GLYPH[motionMove(m)])).size).toBeGreaterThanOrEqual(25);
+ });
+});
+
+describe("gallery variety at rest", () => {
+ it("hashes ids stably", () => {
+ expect(stableHash("motion-zoom-in")).toBe(stableHash("motion-zoom-in"));
+ expect(stableHash("a")).not.toBe(stableHash("b"));
+ });
+
+ it("spreads the first page of motions over the stills", () => {
+ const scenes = new Set(MOTIONS.slice(0, 15).map((m) => previewFor(m).scene));
+ expect(scenes.size).toBeGreaterThanOrEqual(3);
+ });
+
+ it("doesn't put every destruction effect on the same still the same way round", () => {
+ const destruction = EFFECTS.filter((e) => e.category === "Destruction").map(toPresetCard);
+ expect(destruction.length).toBeGreaterThan(3);
+ const looks = new Set(destruction.map((c) => `${c.preview.scene}|${previewFlip(c) ? 1 : 0}`));
+ expect(looks.size).toBeGreaterThanOrEqual(3);
+ // Neighbouring cards get different hues.
+ expect(new Set(destruction.map((c) => c.hue)).size).toBe(destruction.length);
+ });
+
+ it("lets the categories take turns in a gallery's All view", () => {
+ const items = [
+ { id: "a1", category: "A" },
+ { id: "a2", category: "A" },
+ { id: "a3", category: "A" },
+ { id: "b1", category: "B" },
+ { id: "c1", category: "C" },
+ { id: "c2", category: "C" },
+ ];
+ expect(interleaveByCategory(items).map((i) => i.id)).toEqual(["a1", "b1", "c1", "a2", "c2", "a3"]);
+ // The first row of /effects no longer shows one category's near-identical cards.
+ const firstRow = interleaveByCategory(EFFECTS.map(toPresetCard)).slice(0, 5);
+ expect(new Set(firstRow.map((c) => c.category)).size).toBe(5);
+ expect(new Set(firstRow.map((c) => c.preview.fx)).size).toBeGreaterThanOrEqual(4);
+ });
+
+ it("gives cracks, dust and floating heads their own treatment instead of another explosion", () => {
+ const fx = (name: string) => effectFx(EFFECTS.find((e) => e.name === name)!);
+ expect(fx("Lens Crack")).toBe("crack");
+ expect(fx("Disintegration")).toBe("wind");
+ expect(fx("Head Off")).toBe("glow");
+ expect(fx("Building Explosion")).toBe("explode");
+ });
+
+ it("shows one effect per category on Home, the popular one when there is one", () => {
+ const row = homeEffects(EFFECTS, 6);
+ expect(row).toHaveLength(6);
+ expect(new Set(row.map((e) => e.category)).size).toBe(6);
+ for (const e of row) {
+ const top = EFFECTS.find((x) => x.category === e.category && x.badges?.includes("top"));
+ if (top) expect(e.id).toBe(top.id);
+ }
+ expect(new Set(row.map((e) => previewFor(e).fx)).size).toBeGreaterThanOrEqual(4);
+ });
+});
+
+describe("storyboard name", () => {
+ it("is the idea, or the first scene written by hand", () => {
+ expect(storyboardName(" a fox\n in the snow ", ["wide: a fox — beat 1 of 3"])).toBe("a fox in the snow");
+ expect(storyboardName(undefined, ["", "The keeper climbs"])).toBe("The keeper climbs");
+ expect(storyboardName("", [])).toBe("Storyboard");
+ expect(storyboardName("x".repeat(500), [])).toHaveLength(200);
+ });
+});
+
+describe("releasing color grading's media", () => {
+ it("pauses a detached video, drops its source and resets it (in that order)", () => {
+ const calls: string[] = [];
+ releaseVideo({ pause: () => calls.push("pause"), removeAttribute: (n) => calls.push(`remove ${n}`), load: () => calls.push("load") });
+ expect(calls).toEqual(["pause", "remove src", "load"]);
+ expect(() => releaseVideo(null)).not.toThrow();
+ });
+
+ it("loses a WebGL context explicitly, and tolerates none", () => {
+ const lose = vi.fn();
+ loseContext({ getExtension: ((name: string) => (name === "WEBGL_lose_context" ? { loseContext: lose } : null)) as WebGLRenderingContext["getExtension"] });
+ expect(lose).toHaveBeenCalledOnce();
+ expect(() => loseContext(null)).not.toThrow();
+ expect(() => loseContext({ getExtension: (() => null) as WebGLRenderingContext["getExtension"] })).not.toThrow();
+ });
+});
+
+describe("copyText", () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ it("uses the Clipboard API when there is one", async () => {
+ const writeText = vi.fn(async () => {});
+ vi.stubGlobal("navigator", { clipboard: { writeText } });
+ expect(await copyText("hi")).toBe(true);
+ expect(writeText).toHaveBeenCalledWith("hi");
+ });
+
+ it("falls back to a selected textarea on plain-http origins (no navigator.clipboard)", async () => {
+ vi.stubGlobal("navigator", {});
+ const ta = { value: "", style: { cssText: "" }, setAttribute() {}, select() {}, setSelectionRange() {}, remove: vi.fn() };
+ const execCommand = vi.fn(() => true);
+ vi.stubGlobal("document", { createElement: () => ta, body: { appendChild() {} }, activeElement: null, execCommand });
+ expect(await copyText("fuobe_secret")).toBe(true);
+ expect(ta.value).toBe("fuobe_secret");
+ expect(execCommand).toHaveBeenCalledWith("copy");
+ expect(ta.remove).toHaveBeenCalled();
+ });
+
+ it("says when nothing could be copied", async () => {
+ vi.stubGlobal("navigator", { clipboard: { writeText: async () => Promise.reject(new Error("denied")) } });
+ vi.stubGlobal("document", {
+ createElement: () => ({ style: {}, setAttribute() {}, select() {}, setSelectionRange() {}, remove() {} }),
+ body: { appendChild() {} },
+ activeElement: null,
+ execCommand: () => false,
+ });
+ expect(await copyText("x")).toBe(false);
+ });
+});