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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Home: every card row shows its stills and plays its clips in view
Adarshfeb0a6430de6
diff --git a/package.json b/package.jsonindex 964b9c41..0e0a7804 100644--- a/package.json+++ b/package.json@@ -17,6 +17,7 @@"test:e2e:library": "node tests/e2e/library-flows.mjs","test:e2e:home": "node tests/e2e/home-bento.mjs","test:e2e:first-paint": "node tests/e2e/home-first-paint.mjs",+ "test:e2e:home-sections": "node tests/e2e/home-sections.mjs","test:e2e:mobile": "node tests/e2e/no-horizontal-scroll.mjs","test:e2e:shell": "node tests/e2e/shell.mjs","test:e2e:mega-menus": "node tests/e2e/mega-menus.mjs",diff --git a/src/components/home/home-islands.tsx b/src/components/home/home-islands.tsxindex 3fd2639f..3bd797a0 100644--- a/src/components/home/home-islands.tsx+++ b/src/components/home/home-islands.tsx@@ -4,25 +4,38 @@ import { ArrowRight, Check, Copy, Pause, Play } from "lucide-react";import { useEffect, useRef, useState } from "react";import { CardPending, IntentLink } from "@/components/intent-link";import { useFadeEdges } from "@/components/use-fade-edges";+import { useRailStills } from "@/components/use-rail-stills";import { PresetPreview, setPreviewsPaused, usePreviewPlayback, usePreviewsPaused } from "@/components/preset-preview";import { CONNECT_GPU_EVENT, signInHref, useHydrated, useIsOwner, useStatus } from "@/lib/api";import { copyWithToast } from "@/lib/clipboard";import type { PresetCardData } from "@/lib/preset-cards";+import type { AutoPlay } from "@/lib/preview-playback";import { cn } from "@/lib/utils";+const FADE_ROW = "fade-x scrollbar-none max-sm:-mx-4 max-sm:overflow-x-auto max-sm:px-4";+/** A row that scrolls sideways on a phone, its edges fading where there's more to see. */export function FadeRow({ className, children }: { className?: string; children: React.ReactNode }) {const ref = useFadeEdges<HTMLDivElement>();return (- <div ref={ref} className={cn("fade-x scrollbar-none max-sm:-mx-4 max-sm:overflow-x-auto max-sm:px-4", className)}>+ <div ref={ref} className={cn(FADE_ROW, className)}>{children}</div>);}-/** A row of cards: a grid from sm up, a rail that snaps on a phone, with the next card peeking at the edge. */+/**+ * A row of cards: a grid from sm up, a rail that snaps on a phone, with the next card peeking at the edge. Every card's+ * still loads as the row nears the screen, so a card sliding in from the side is never blank (useRailStills).+ */export function HomeRail({ className, children }: { className?: string; children: React.ReactNode }) {- return <FadeRow className={cn("flex snap-x snap-mandatory scroll-px-4 sm:grid sm:[mask-image:none]", className)}>{children}</FadeRow>;+ const ref = useFadeEdges<HTMLDivElement>();+ useRailStills(ref);+ return (+ <div ref={ref} className={cn(FADE_ROW, "flex snap-x snap-mandatory scroll-px-4 sm:grid sm:[mask-image:none]", className)}>+ {children}+ </div>+ );}/** Stops every preview playing by itself, on every page, for this visit; a hover still plays one. */@@ -73,9 +86,10 @@ export function CopyCommand({ text }: { text: string }) {}/**- * A studio's card. It plays where nothing can hover, like the cards above it; with a mouse it waits for one, so the- * clips higher on the page keep the screen's few players. A hover on a card resting on its peak starts where the- * change starts (PresetPreview's `asked`). `zoom`: a still that slowly closes in on hover instead.+ * A studio's card. `auto` "always" (Home's row): its clip plays by itself while it's in view, like the preset cards+ * above it, within the screen's few players. "touch" (an area page's grid): it plays by itself only where nothing can+ * hover; with a mouse it waits for one. A hover on a card resting on its peak starts where the change starts+ * (PresetPreview's `asked`). `zoom`: a still that slowly closes in on hover instead.*/export function StudioCard({href,@@ -85,6 +99,7 @@ export function StudioCard({zoom,place,sizes,+ auto = "touch",}: {href: string;label: string;@@ -93,8 +108,9 @@ export function StudioCard({zoom?: boolean;place?: number;sizes?: string;+ auto?: AutoPlay;}) {- const { ref, playing, asked, handlers } = usePreviewPlayback<HTMLAnchorElement>(card.id, card.preview, { auto: "touch" });+ const { ref, playing, asked, handlers } = usePreviewPlayback<HTMLAnchorElement>(card.id, card.preview, { auto });return (<IntentLink ref={ref} href={href} {...handlers} className="group/studio flex min-w-0 flex-col gap-2 rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring"><StudioPicture zoom={zoom}>diff --git a/src/components/home/home-sections.tsx b/src/components/home/home-sections.tsxindex bbe69cfd..9c34bd22 100644--- a/src/components/home/home-sections.tsx+++ b/src/components/home/home-sections.tsx@@ -29,7 +29,7 @@ import { FUOBE_REPO } from "@/lib/connections";import { HOME_LIVE, presetHref, type HomeShowcase } from "@/lib/home-showcase";import { area } from "@/lib/nav-areas";import { studioCount } from "@/lib/nav-model";-import { staggered } from "@/lib/preview-playback";+import { staggered, type AutoPlay } from "@/lib/preview-playback";import { cn } from "@/lib/utils";import { plainTagline } from "@/lib/plain-tagline";import type { PresetCardData } from "@/lib/preset-cards";@@ -366,6 +366,7 @@ export function DestinationsSection({allCount,allNoun,after,+ auto,}: {id: string;title: string;@@ -386,11 +387,22 @@ export function DestinationsSection({allNoun?: string;/** Pills only the viewer's island adds (the owner's), after the others. */after?: React.ReactNode;+ /** When the cards' clips play by themselves (StudioCard): Home's row, "always", like the preset rows above it. */+ auto?: AutoPlay;}) {const items = cards.map((s, i) => (<div key={s.href} className={grid ? "min-w-0" : RAIL_ITEM}>{s.card ? (- <StudioCard href={s.href} label={s.label} line={s.line} card={s.card} zoom={!s.card.preview.video} place={staggered(i)} sizes={grid ? GRID_SIZES : STUDIO_SIZES} />+ <StudioCard+ href={s.href}+ label={s.label}+ line={s.line}+ card={s.card}+ zoom={!s.card.preview.video}+ place={staggered(i)}+ sizes={grid ? GRID_SIZES : STUDIO_SIZES}+ auto={auto}+ />) : s.drawn === "live" ? (<DrawnCard href={s.href} label={s.label} line={s.line}>{/* A picture inside the link: its own controls stay out of reach (the card is one tap). */}@@ -454,6 +466,7 @@ export function StudiosSection({ facts, studios, audioTools, pills }: Pick<HomeSall={area("studios").href}allCount={studioCount()}allNoun="studios"+ auto="always"data-reveal className={cn(SECTION, "[--cv:529px] sm:[--cv:1597px] md:[--cv:1482px] lg:[--cv:770px] xl:[--cv:795px]")}/>);diff --git a/src/components/use-rail-stills.ts b/src/components/use-rail-stills.tsnew file mode 100644index 00000000..91a83b97--- /dev/null+++ b/src/components/use-rail-stills.ts@@ -0,0 +1,39 @@+"use client";++import { useEffect, type RefObject } from "react";++/** How near the screen a row is when its stills start loading: a screen's height above or below it. */+export const RAIL_STILLS_MARGIN = "100% 0px";++/**+ * A row of cards that scrolls sideways on a phone (HomeRail): every card's still loads once the row comes within a+ * screen of view, not one by one as each card slides in. A browser loads a lazy picture only when the picture nears the+ * screen, and a card waiting at the side of a row is cut off by the row, so its still was asked for only once the card+ * was already showing, blank. A card hidden at this width (display: none) loads nothing; one shown later (the screen+ * turned or grew) loads then, as the row's size changes.+ */+export function useRailStills(ref: RefObject<HTMLElement | null>) {+ useEffect(() => {+ const rail = ref.current;+ if (!rail || typeof IntersectionObserver === "undefined") return;+ let near = false;+ const load = () => {+ if (!near) return;+ for (const img of rail.querySelectorAll<HTMLImageElement>('img[loading="lazy"]')) if (img.getClientRects().length) img.loading = "eager";+ };+ const io = new IntersectionObserver(+ (entries) => {+ near = entries[entries.length - 1].isIntersecting;+ load();+ },+ { rootMargin: RAIL_STILLS_MARGIN },+ );+ io.observe(rail);+ const ro = typeof ResizeObserver === "undefined" ? undefined : new ResizeObserver(load);+ ro?.observe(rail);+ return () => {+ io.disconnect();+ ro?.disconnect();+ };+ }, [ref]);+}diff --git a/src/lib/preview-playback.ts b/src/lib/preview-playback.tsindex b02d9a4b..b138395d 100644--- a/src/lib/preview-playback.ts+++ b/src/lib/preview-playback.ts@@ -1,6 +1,6 @@/**- * Which gallery previews play (preset-preview.tsx). A card with a clip plays by itself while it's- * mostly in view, once scrolling has stopped: the cards most in view and nearest the middle of the+ * Which gallery previews play (preset-preview.tsx). A card with a clip plays by itself while at least+ * half of it is in view, once scrolling has stopped: the cards most in view and nearest the middle of the* screen, at most MAX_PLAYING at once, so a gallery with dozens of clips stays smooth and doesn't* download them all. Procedural previews (no clip) play by themselves only where nothing can hover* (phones); a still never moves. Nothing plays by itself when the user prefers reduced motion, asks@@ -37,8 +37,8 @@ export interface PlaybackEnv {saveData(): boolean;}-/** A card must be at least this much in view to play by itself. */-export const MIN_VISIBLE = 0.6;+/** A card must be at least this much in view to play by itself: half of it. */+export const MIN_VISIBLE = 0.5;/** In full view, near enough (IntersectionObserver reports ratios only as they cross its thresholds). */export const FULL_VIEW = 0.85;/** How long the pointer (or focus) rests on a card before it plays, in ms. */@@ -103,7 +103,7 @@ export interface Candidate {}/**- * Which cards play by themselves, at most `max`: only those mostly in view; the ones in full view+ * Which cards play by themselves, at most `max`: only those at least half in view; the ones in full view* first, then the ones already playing (a small scroll doesn't restart them), then the nearest the* middle of the screen.*/@@ -251,7 +251,7 @@ export function createPlaybackStore(env: PlaybackEnv) {if (card === undefined) continue;const ratio = e.isIntersecting ? e.intersectionRatio : 0;ratios.set(e.target, ratio);- // A playing card stops as soon as it's mostly out of view; the next ones wait for the scroll to settle.+ // A playing card stops as soon as less than half of it is in view; the next ones wait for the scroll to settle.if (ratio < MIN_VISIBLE && auto.has(card)) setAuto([...auto].filter((a) => a !== card));}schedule();diff --git a/tests/e2e/home-sections.mjs b/tests/e2e/home-sections.mjsnew file mode 100644index 00000000..701e3a3c--- /dev/null+++ b/tests/e2e/home-sections.mjs@@ -0,0 +1,302 @@+// Home's card rows under the first screen in a real browser: Effects, Camera motions, Apps, and Studios and tools+// (src/components/home/home-sections.tsx). Run it on a production server (`next build`, then `next start -p <port>`), or+// against the live site.+//+// Usage: node tests/e2e/home-sections.mjs [appUrl] [--shots <dir>] (pnpm test:e2e:home-sections)+//+// At 390@3x (a phone) and 1440@2x (a laptop), as a guest:+// 1. Every card shown at that width has its still, at least as wide as its box shows it (times the pixel ratio, up to+// the widest copy, 1024 px). On a phone that's every card of a sideways row too, loaded before it is swiped in+// (useRailStills), and a card swiped in shows its still at once. A card hidden at that width loads nothing.+// 2. With each row in view, its cards' clips play by themselves (muted, inline): every card at least half in view+// plays, up to the cap (MAX_PLAYING in src/lib/preview-playback.ts: 3 on a phone, 6 wider), its time moving on;+// never more than the cap on the whole page at once; a card less than half in view plays nothing. No play sign over+// a card.+// 3. A phone's row swiped along: the card swiped in plays, the one swiped out stops at once.+// 4. The tab hidden: nothing plays; shown again, the cards in view play again.+// 5. Nothing shifts: layout shift under 0.01 through all of it.+// 6. Reduced motion, and Save-Data: no clip plays by itself and every still is there; on the laptop a hover still plays+// the card's clip.+import fs from "node:fs";+import path from "node:path";+import { DESKTOP, launch, PHONE, root } from "./_browser.mjs";++const args = process.argv.slice(2);+const app = (args.find((a, i) => !a.startsWith("--") && args[i - 1] !== "--shots") ?? "http://localhost:3620").replace(/\/$/, "");+const shotsDir = args.includes("--shots") ? args[args.indexOf("--shots") + 1] : undefined;+if (shotsDir) fs.mkdirSync(shotsDir, { recursive: true });++const SECTIONS = ["home-effects", "home-motions", "home-apps", "home-studios"];+const cap = (() => {+ const src = fs.readFileSync(path.join(root, "src/lib/preview-playback.ts"), "utf8");+ const m = /MAX_PLAYING = \{ narrow: (\d+), wide: (\d+) \}/.exec(src);+ if (!m) throw new Error("MAX_PLAYING not found in src/lib/preview-playback.ts");+ return { narrow: Number(m[1]), wide: Number(m[2]) };+})();+/** The widest copy of a cover's still (preset-hd.generated.ts). */+const WIDEST = 1024;+/** How long a clip may take to load and reach its place in the shared cycle (STAGGER_CYCLE, 2.8 s) before it plays. */+const PLAY_WITHIN = app.includes("localhost") || app.includes("127.0.0.1") ? 9000 : 15000;++// E2E_CHANNEL=chrome: the installed Chrome, which plays H.264 (a Chromium build without the codec can't play the clips).+const browser = await launch({ args: ["--autoplay-policy=no-user-gesture-required"], ...(process.env.E2E_CHANNEL ? { channel: process.env.E2E_CHANNEL } : {}) });+const failures = [];+const check = (name, ok, detail = "") => {+ console.log(`${ok ? "ok " : "FAIL"} ${name}${detail ? ` (${detail})` : ""}`);+ if (!ok) failures.push(name);+};++/** Layout shifts (not caused by input), summed in `window.__cls`, from the first paint. */+const watchShifts = () => {+ window.__cls = 0;+ new PerformanceObserver((list) => {+ for (const e of list.getEntries()) if (!e.hadRecentInput) window.__cls += e.value;+ }).observe({ type: "layout-shift", buffered: true });+};++/**+ * Every card of the four rows shown at this width (a card hidden at this width is skipped): its section, its name,+ * how much of it is in view (cut by its row, which scrolls sideways on a phone), its still and its clip.+ */+const readCards = (sections) =>+ sections.flatMap((id) => {+ const section = document.getElementById(id).closest("section");+ const rail = section.querySelector(".snap-x");+ const clip = rail.getBoundingClientRect();+ return [...rail.children]+ .filter((item) => item.getClientRects().length > 0)+ .map((item) => {+ const a = item.querySelector("a");+ const r = a.getBoundingClientRect();+ const w = Math.max(0, Math.min(r.right, clip.right, innerWidth) - Math.max(r.left, clip.left, 0));+ const h = Math.max(0, Math.min(r.bottom, innerHeight) - Math.max(r.top, 0));+ const img = a.querySelector("img");+ const v = a.querySelector("video");+ return {+ section: id,+ name: (a.querySelector("p")?.textContent ?? a.getAttribute("href")).trim(),+ ratio: r.width && r.height ? (w * h) / (r.width * r.height) : 0,+ still: !!img && img.complete && img.naturalWidth > 0,+ src: img?.currentSrc ?? "",+ box: img ? [img.clientWidth, img.clientHeight] : [0, 0],+ video: v ? { t: v.currentTime, paused: v.paused, muted: v.muted, inline: v.hasAttribute("playsinline") } : null,+ sign: !!a.querySelector(".pv-play, svg.lucide-play, svg.lucide-circle-play"),+ };+ });+ });++/** Cards' clips playing anywhere on the page (the first screen's tiles too, which share the cap): not paused, not ended. */+const playingOnPage = () => [...document.querySelectorAll("a video")].filter((v) => !v.paused && !v.ended).length;++/** The true width of each still the browser chose, read from its file. */+async function stillWidths(page, srcs) {+ return page.evaluate(+ (list) =>+ Promise.all(+ list.map(+ (src) =>+ new Promise((resolve) => {+ const im = new Image();+ im.onload = () => resolve(im.naturalWidth);+ im.onerror = () => resolve(0);+ im.src = src;+ }),+ ),+ ),+ srcs,+ );+}++/** The device pixels a 4:3 picture covering this box needs (media-pick.ts coverWidth). */+const need = ([w, h], dpr) => Math.ceil(Math.max(w, h * (4 / 3)) * dpr);++async function scrollToSection(page, id) {+ await page.evaluate((i) => {+ const s = document.getElementById(i).closest("section");+ window.scrollTo(0, s.getBoundingClientRect().top + scrollY - 70);+ }, id);+}++/**+ * Waits until every card at least half in view plays (its time moving on), as many as the cap allows: the rows share+ * the cap, so all four are counted. Returns what it saw: the cards, the ones in view and playing, the most clips playing+ * on the page at once and loaded in the rows at once, and whether they all played in time.+ */+async function waitForPlaying(page, max) {+ const start = Date.now();+ let most = 0;+ let mounted = 0;+ let last;+ while (Date.now() - start < PLAY_WITHIN) {+ const a = await page.evaluate(readCards, SECTIONS);+ most = Math.max(most, await page.evaluate(playingOnPage));+ await page.waitForTimeout(500);+ const b = await page.evaluate(readCards, SECTIONS);+ most = Math.max(most, await page.evaluate(playingOnPage));+ mounted = Math.max(mounted, b.filter((c) => c.video).length);+ const inView = b.filter((c) => c.ratio >= 0.5);+ const moving = b.filter((c, i) => c.video && !c.video.paused && a[i]?.video && c.video.t !== a[i].video.t);+ last = { cards: b, inView, moving };+ if (moving.length >= Math.min(max, inView.length)) return { ...last, most, mounted, ok: true };+ }+ return { ...last, most, mounted, ok: false };+}++async function sharpAndFilled(page, label, dpr) {+ const cards = await page.evaluate(readCards, SECTIONS);+ const blank = cards.filter((c) => !c.still);+ check(`${label}: every card shown has its still`, blank.length === 0, `${cards.length} cards${blank.length ? `; blank: ${blank.map((c) => `${c.section}/${c.name}`).join(", ")}` : ""}`);+ const widths = await stillWidths(+ page,+ cards.map((c) => c.src),+ );+ const soft = cards.map((c, i) => ({ ...c, px: widths[i] })).filter((c) => c.px < Math.min(need(c.box, dpr), WIDEST));+ check(+ `${label}: every still is at least as wide as its box needs`,+ soft.length === 0,+ soft.length+ ? soft.map((c) => `${c.name} ${c.px}px < ${need(c.box, dpr)}`).join(", ")+ : `e.g. ${widths[0]} px (${cards[0].src.replace(app, "").split("?")[0]}) for a ${need(cards[0].box, dpr)} px box`,+ );+ return cards;+}++async function run(device, label, dpr, max) {+ const ctx = await browser.newContext({ ...device, deviceScaleFactor: dpr });+ const page = await ctx.newPage();+ await page.addInitScript(watchShifts);+ const errors = [];+ page.on("pageerror", (e) => errors.push(e.message.slice(0, 160)));+ await page.goto(`${app}/?e2e=${Date.now()}`, { waitUntil: "load" });+ await page.waitForTimeout(800);++ // The rows come into view one by one, as a reader scrolls down to them.+ for (const id of SECTIONS) {+ await scrollToSection(page, id);+ await page.waitForTimeout(400);+ const seen = await waitForPlaying(page, max);+ const here = seen.cards.filter((c) => c.section === id);+ const names = (list) => list.map((c) => `${c.section === id ? "" : `${c.section}/`}${c.name}`).join(", ");+ check(+ `${label} ${id}: the cards in view play by themselves`,+ seen.ok && seen.moving.some((c) => c.section === id),+ `${seen.moving.length} playing of ${seen.inView.length} at least half in view (cap ${max}): ${names(seen.moving)}`,+ );+ check(`${label} ${id}: never more than ${max} clips at once`, seen.most <= max && seen.mounted <= max, `at most ${seen.most} playing, ${seen.mounted} loaded`);+ const out = seen.cards.filter((c) => c.ratio < 0.5 && c.video && !c.video.paused);+ check(`${label} ${id}: a card less than half in view plays nothing`, out.length === 0, names(out));+ const loud = seen.cards.filter((c) => c.video && (!c.video.muted || !c.video.inline));+ check(`${label} ${id}: the clips are muted and inline`, loud.length === 0, names(loud));+ check(`${label} ${id}: no play sign over a card`, !here.some((c) => c.sign));+ if (shotsDir) await page.screenshot({ path: path.join(shotsDir, `${label}-${id}.png`) });+ }+ await sharpAndFilled(page, label, dpr);++ if (device === PHONE) {+ // Swiping the Effects row along, a card at a time: the card swiped in shows its still at once and then plays, and+ // the one swiped out stops.+ await scrollToSection(page, "home-effects");+ await page.waitForTimeout(1200);+ for (const step of [1, 2, 3]) {+ await page.evaluate((i) => {+ const rail = document.getElementById("home-effects").closest("section").querySelector(".snap-x");+ const pad = parseFloat(getComputedStyle(rail).scrollPaddingLeft) || 0;+ const left = rail.scrollLeft + rail.children[i].getBoundingClientRect().left - rail.getBoundingClientRect().left - pad;+ rail.scrollTo({ left, behavior: "instant" });+ }, step);+ const now = (await page.evaluate(readCards, ["home-effects"])).filter((c) => c.ratio > 0);+ check(`${label} swipe ${step}: the cards swiped in show their stills at once`, now.every((c) => c.still), now.filter((c) => !c.still).map((c) => c.name).join(", "));+ await page.waitForTimeout(150);+ const off = (await page.evaluate(readCards, ["home-effects"])).filter((c) => c.ratio < 0.5 && c.video && !c.video.paused);+ check(`${label} swipe ${step}: the card swiped out stops`, off.length === 0, off.map((c) => c.name).join(", "));+ const seen = await waitForPlaying(page, max);+ const full = seen.cards.filter((c) => c.section === "home-effects" && c.ratio >= 0.85).map((c) => c.name);+ check(+ `${label} swipe ${step}: the card swiped in plays`,+ seen.ok && seen.moving.some((c) => full.includes(c.name)),+ `in view: ${full.join(", ")}; playing: ${seen.moving.map((c) => c.name).join(", ")}`,+ );+ if (shotsDir && step === 3) await page.screenshot({ path: path.join(shotsDir, `${label}-swiped.png`) });+ }+ // To the end of the row: every card there already has its still.+ await page.evaluate(() => {+ const rail = document.getElementById("home-effects").closest("section").querySelector(".snap-x");+ rail.scrollTo({ left: rail.scrollWidth, behavior: "instant" });+ });+ const end = (await page.evaluate(readCards, ["home-effects"])).filter((c) => c.ratio > 0);+ check(`${label}: the end of the row shows its stills at once`, end.length > 0 && end.every((c) => c.still), end.map((c) => `${c.name}${c.still ? "" : " (blank)"}`).join(", "));+ }++ // The tab goes to the background: nothing plays. Back: the cards in view play again.+ await scrollToSection(page, "home-motions");+ await waitForPlaying(page, max);+ await page.evaluate(() => {+ Object.defineProperty(document, "hidden", { value: true, configurable: true });+ Object.defineProperty(document, "visibilityState", { value: "hidden", configurable: true });+ document.dispatchEvent(new Event("visibilitychange"));+ });+ await page.waitForTimeout(300);+ const hiddenPlaying = await page.evaluate(playingOnPage);+ check(`${label}: a hidden tab plays nothing`, hiddenPlaying === 0, `${hiddenPlaying} playing`);+ await page.evaluate(() => {+ delete document.hidden;+ delete document.visibilityState;+ document.dispatchEvent(new Event("visibilitychange"));+ });+ const back = await waitForPlaying(page, max);+ check(`${label}: shown again, the cards in view play again`, back.ok, `${back.moving.length} playing`);++ const cls = await page.evaluate(() => window.__cls);+ check(`${label}: nothing shifts`, cls < 0.01, `layout shift ${cls.toFixed(4)}`);+ check(`${label}: no page errors`, errors.length === 0, errors.slice(0, 3).join(" | "));+ await ctx.close();+}++/** Reduced motion, or Save-Data: stills only, every one there; a hover (where there's a pointer) still plays a clip. */+async function stillsOnly(device, label, dpr, opts) {+ const ctx = await browser.newContext({ ...device, deviceScaleFactor: dpr, ...(opts.reducedMotion ? { reducedMotion: "reduce" } : {}) });+ const page = await ctx.newPage();+ if (opts.saveData)+ await page.addInitScript(() => Object.defineProperty(navigator, "connection", { value: { saveData: true, effectiveType: "4g", addEventListener() {} }, configurable: true }));+ await page.goto(`${app}/?e2e=${Date.now()}`, { waitUntil: "load" });+ await page.waitForTimeout(800);+ let most = 0;+ for (const id of SECTIONS) {+ await scrollToSection(page, id);+ await page.waitForTimeout(2500);+ most = Math.max(most, await page.evaluate(playingOnPage), (await page.evaluate(readCards, SECTIONS)).filter((c) => c.video).length);+ }+ check(`${label}: no clip plays by itself`, most === 0, `${most} playing`);+ await sharpAndFilled(page, label, dpr);+ if (device === DESKTOP) {+ await scrollToSection(page, "home-effects");+ await page.waitForTimeout(400);+ const box = await page.evaluate(() => {+ const a = document.getElementById("home-effects").closest("section").querySelector(".snap-x a");+ const r = a.getBoundingClientRect();+ return { x: r.left + r.width / 2, y: r.top + r.height / 3 };+ });+ await page.mouse.move(box.x, box.y);+ const start = Date.now();+ let hovered = false;+ while (!hovered && Date.now() - start < PLAY_WITHIN) {+ await page.waitForTimeout(400);+ hovered = (await page.evaluate(readCards, ["home-effects"])).some((c) => c.video && !c.video.paused && c.video.t > 0);+ }+ check(`${label}: a hover still plays the card's clip`, hovered);+ await page.mouse.move(0, 0);+ }+ await ctx.close();+}++console.log(`Home's card rows at ${app} (caps: ${cap.narrow} on a phone, ${cap.wide} wider)`);+await run(PHONE, "390@3x", 3, cap.narrow);+await run(DESKTOP, "1440@2x", 2, cap.wide);+await stillsOnly(PHONE, "390@3x reduced motion", 3, { reducedMotion: true });+await stillsOnly(DESKTOP, "1440@2x reduced motion", 2, { reducedMotion: true });+await stillsOnly(PHONE, "390@3x Save-Data", 3, { saveData: true });+await stillsOnly(DESKTOP, "1440@2x Save-Data", 2, { saveData: true });+await browser.close();++console.log(failures.length ? `\n${failures.length} failed` : "\nall passed");+process.exit(failures.length ? 1 : 0);diff --git a/tests/shell-logic.test.ts b/tests/shell-logic.test.tsindex ea373c82..767dc4eb 100644--- a/tests/shell-logic.test.ts+++ b/tests/shell-logic.test.ts@@ -239,6 +239,69 @@ describe("preview playback store", () => {expect(maxPlaying(1280)).toBe(MAX_PLAYING.wide);});+ it("plays a card once half of it is in view, and stops it as soon as less than half is", () => {+ const { env, card, intersect, advance } = fakeEnv({ width: 1440, height: 900 });+ const store = createPlaybackStore(env);+ const [a, b] = [card(700), card(700, 300)];+ store.watch(a, "a");+ store.watch(b, "b");+ intersect([+ [a, 0.5],+ [b, 0.49],+ ]);+ advance(SCROLL_SETTLE);+ expect(MIN_VISIBLE).toBe(0.5);+ expect(store.playing()).toEqual(["a"]);+ intersect([[a, 0.49]]);+ expect(store.playing()).toEqual([]);+ });++ it("a phone's sideways row: the card in view plays, the one peeking in waits; swiped along, the next one takes over", () => {+ const { env, card, intersect, scrolled, advance } = fakeEnv({ width: 390, height: 844 });+ const store = createPlaybackStore(env);+ // Home's rail on a narrow phone: cards 237 px wide from x 10, the second showing less than half of itself at the edge.+ const row = Array.from({ length: 12 }, (_, i) => card(300, 10 + i * 237, 237, 190));+ row.forEach((el, i) => store.watch(el, `c${i}`));+ intersect([+ [row[0], 1],+ [row[1], 0.4],+ ]);+ advance(SCROLL_SETTLE);+ expect(store.playing()).toEqual(["c0"]);+ // A swipe: the first card slides out (it stops at once), the second comes in, and plays once the row is still.+ scrolled();+ intersect([+ [row[0], 0.2],+ [row[1], 1],+ [row[2], 0.3],+ ]);+ expect(store.playing()).toEqual([]);+ advance(SCROLL_SETTLE - 1);+ expect(store.playing()).toEqual([]);+ advance(1);+ expect(store.playing()).toEqual(["c1"]);+ });++ it("with more cards in view than may play, the ones most in view win, then the nearest the middle", () => {+ const { env, card, intersect, advance } = fakeEnv({ width: 390, height: 844 });+ const store = createPlaybackStore(env);+ // Three cards partly in view right at the middle of the screen, four in full view further out.+ const partly = [0, 1, 2].map((i) => card(330, i * 130, 120, 180));+ const full = [0, 1, 2, 3].map((i) => card(i < 2 ? 20 : 640, (i % 2) * 200, 180, 180));+ partly.forEach((el, i) => store.watch(el, `p${i}`));+ full.forEach((el, i) => store.watch(el, `f${i}`));+ intersect([...partly.map((el) => [el, 0.7] as [Element, number]), ...full.map((el) => [el, 1] as [Element, number])]);+ advance(SCROLL_SETTLE);+ expect(store.playing()).toHaveLength(MAX_PLAYING.narrow);+ expect(store.playing().every((id) => id.startsWith("f"))).toBe(true);+ });++ it("Home's studio cards (auto: \"always\") play by themselves where a pointer can hover too, as the preset cards do", () => {+ expect(autoplays("clip", true, "always")).toBe(true);+ expect(autoplays("clip", false, "always")).toBe(true);+ expect(autoplays("still", true, "always")).toBe(false);+ });+it("ranks cards in full view first, then the ones already playing (so a scroll doesn't restart them), then the nearest the middle", () => {const c = (id: string, ratio: number, dist: number, playing = false) => ({ id, ratio, dist, playing });const cards = [c("partly", FULL_VIEW - 0.1, 0, true), c("near", 1, 10), c("playing", 1, 500, true), c("hidden", MIN_VISIBLE - 0.1, 0), c("far", 1, 600)];@@ -437,7 +500,7 @@ describe("preview playback store", () => {expect([true, false].map((hover) => autoplays("still", hover))).toEqual([false, false]);});- it('with auto: "touch" (Home\'s studio cards) nothing plays by itself where a pointer can hover', () => {+ it('with auto: "touch" (an area page\'s studio cards) nothing plays by itself where a pointer can hover', () => {for (const kind of ["clip", "procedural", "still"] as const) expect(autoplays(kind, true, "touch"), kind).toBe(false);// Where nothing can hover (a phone) it plays as any card does.expect((["clip", "procedural", "still"] as const).map((kind) => autoplays(kind, false, "touch"))).toEqual([true, true, false]);