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.

Preset covers: clips play by themselves while their cards are in view

Adarsh8bb26ee174fe
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index e0b43abb..83102697 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -525,7 +525,7 @@ Liner-inspired shell (pale frame, rounded inset sheet, 13px sidebar rows, serif
- **Hubs** (Audio, Video tools, Upscale) have one prerendered path per mode (`src/lib/hubs.ts`, `ModeSwitchStudio` in `mode-switch-studio.tsx`, `[mode]/page.tsx`); old `?mode=` links redirect in `next.config.ts`, and an unknown mode is a real 404. Round 4 adds `/upscale/fps`, `/upscale/hdr`, `/upscale/export`, `/audio/transcribe`, `/audio/loop`, `/audio/join` and `/video-tools/remove-object`; round 5 part 1 adds `/video-tools/evolution`, and round 5 part 2 `/audio/split` (`SplitSoundtrackTool` in `TOOLS`).
- **Composer** pieces: pure logic in `src/lib/composer.ts` (summary, blockers, `onImageChange`, `fitAttachments`, `firstMissingSlot`; since round 4 `blockerLine` for the phone's blocked-Generate line, `framesRequest` and the Frames strip helpers, the start token), `attachments.ts` (`useAttach`, `useUploadReaper`), `settings-panel.tsx`, `model-picker.tsx` (cmdk), `attach-menu.tsx`, `preset-chips.tsx` (lazy), `radio-keys.ts`, `frames-strip.tsx`, and since round 4 part 3 `look-chip.tsx` (lazy: Fuobe Soul's looks, a popover on desktop and a sheet on phones). Since round 4 part 3 the composer sends `engine` for a Fuobe Original, drops a look when the model changes to one without looks, moves to a motion's or effect's Original when one is picked, and follows a move across an engine switch (the pure helpers are in `src/lib/composer.ts`: see Fuobe Originals). Video finishing reads the attached clip's facts from `POST /api/media/probe` for its "24 → 60 fps · 5 s → 10 s" line and its prices. Since round 5 part 1 Edit video does too (`clipFacts`, fixes-5): a clip edit that keeps the clip's length is priced on its seconds, and `clipBlocker` blocks Generate with the reason when the clip is outside the model's window (`clip-windows.ts`; the server refuses the same for an API call that sends no length, after the clip is uploaded to the provider's storage, nothing billed). Lipsync reads the voice's length (`StudioConfig.voiceFacts`) to price talking avatars, and the Image studio prices a look's step after the picture (`postStepCost`, with the face mosaic's models in `extraModels`). The Look chip has a "No look" state (`none`, Storyboard). Since round 5 part 2 a price is read on the browser's day (`useToday` in `src/hooks/use-today.ts`: null on the server and while the page hydrates, so a launch-priced model shows no price until then, and it changes at UTC midnight): the composer's estimate, the model picker (`pickerPrice`) and the Models page (`rowPrice` with `ModelRow.launch`; `GET /api/models` answers the day's `price` and keeps `launch`). The slim studio catalog carries `Pricing.promo` as it is. A run with LoRAs on an endpoint with no published price shows "Price unknown", never free, in the composer and on Canvas nodes. The Image studio's controls chip reads "Options" (`StudioConfig.controlsTitle`), where MOSS-Image's Quality sits.
- **Feed and results**: running tiles show elapsed time and, once progress has moved, time left (`use-now.ts`; `notePace` / `timeLeft` in `src/lib/format.ts`); the newest single result offers next steps (`nextSteps` in `output-actions.ts`); video tiles get a poster (`videoPoster`); ProRes, FFV1 and clips the browser can't decode show as a file card (`VideoFileCard` in `result-media.tsx`). Since round 4 part 2, `useCreateGeneration` (`src/lib/api.ts`) shows a run's `notes` (LoRAs left out, a length the API rounds) as a warning toast. Since round 4 part 3 every studio feed finishes Fuobe Soul pictures (`useSoulFinish`), the viewer's Details show a Look row and a Finish row, and a clip with `meta.grade` offers "Apply the … grade" first.
-- **Galleries** get slim cards (`src/lib/preset-cards.ts`) with procedural previews (`preset-preview.tsx`, `move-glyphs.ts`); `previewFor` (`src/lib/preset-card-data.ts`) shows a real cover instead when `src/lib/preset-previews.generated.ts` lists one: a still cover is the card's picture as rendered (no tint, bleed, mirroring or move glyph), a clip cover is a muted `<video preload="none">` over its first-frame poster. Every entry records the run, engine, model and variant that made it. `preset-card-data.ts` is the only module that reads the manifest, and only the server gallery pages and the preset header (loaded on its own with `next/dynamic`) import it, so the manifest never ships in the shared client chunks (`tests/preset-covers.test.ts` checks the importers, and checks the real manifest against `public/previews`). Covers are served with a day's cache and a week of background revalidation, outside the sign-in proxy like `samples/`. The file is written by the evaluation harness's `eval:covers`, from a measured run's promoted renders or, with `--from-masters <dir>`, from rendered masters kept outside the repo (`coversFromMasters()` in `scripts/eval/lib/covers.mjs`; it replaces only the ids it writes, and skips an id whose cover another run made elsewhere unless `--replace`). Stills are 4:2:0 JPEGs of at most 768 px; a clip cover is at most 4 s and 512 px, and its last 6 frames are crossfaded into its first ones so the card's loop has no jump (a clip that already ends where it starts is only cut). The first covers came that way: 480 of the 487 app, motion and effect cards (474 stills from Ideogram 4 and 6 clips from MiniMax H3, all rendered in ComfyUI; run `comfyui-previews-2026-10`, in `public/previews/presets/`), while the other 7 keep their procedural preview. Main's later cover work gave 43 apps a before/after reveal clip (Ideogram 4, then Qwen-Image 2.1 Edit), so 48 of the 480 now have a clip (the other 5 from MiniMax H3) and 432 are stills. `preview-playback.ts` plays one card at a time: on hover after a short rest or on keyboard focus, on phones the centred card once scrolling stops, and not with Save-Data or on 2G (the preset header's autoplay too).
+- **Galleries** get slim cards (`src/lib/preset-cards.ts`) with procedural previews (`preset-preview.tsx`, `move-glyphs.ts`); `previewFor` (`src/lib/preset-card-data.ts`) shows a real cover instead when `src/lib/preset-previews.generated.ts` lists one: a still cover is the card's picture as rendered (no tint, bleed, mirroring or move glyph), a clip cover is its first-frame poster with a muted `<video>` over it only while it plays (invisible until its first frame is ready, released when it stops). Every entry records the run, engine, model and variant that made it. `preset-card-data.ts` is the only module that reads the manifest, and only the server gallery pages and the preset header (loaded on its own with `next/dynamic`) import it, so the manifest never ships in the shared client chunks (`tests/preset-covers.test.ts` checks the importers, and checks the real manifest against `public/previews`). Covers are served with a day's cache and a week of background revalidation, outside the sign-in proxy like `samples/`. The file is written by the evaluation harness's `eval:covers`, from a measured run's promoted renders or, with `--from-masters <dir>`, from rendered masters kept outside the repo (`coversFromMasters()` in `scripts/eval/lib/covers.mjs`; it replaces only the ids it writes, and skips an id whose cover another run made elsewhere unless `--replace`). Stills are 4:2:0 JPEGs of at most 768 px; a clip cover is at most 4 s and 512 px, and its last 6 frames are crossfaded into its first ones so the card's loop has no jump (a clip that already ends where it starts is only cut). The first covers came that way: 480 of the 487 app, motion and effect cards (474 stills from Ideogram 4 and 6 clips from MiniMax H3, all rendered in ComfyUI; run `comfyui-previews-2026-10`, in `public/previews/presets/`), while the other 7 keep their procedural preview. Main's later cover work gave 43 apps a before/after reveal clip (Ideogram 4, then Qwen-Image 2.1 Edit), so 48 of the 480 now have a clip (the other 5 from MiniMax H3) and 432 are stills. `preview-playback.ts` decides which play: a clip card plays by itself while it's mostly in view, once scrolling stops, at most 6 at once (3 on a phone), the cards in full view and nearest the middle of the screen first; a procedural preview does so only where nothing can hover (phones), and the preset header plays whatever moves. Nothing plays by itself with reduced motion, Save-Data, on 2G or in a hidden tab; a hover (after a short rest), keyboard focus, or a tap on the preset header still plays one (with reduced motion, only a clip).
- **Sidebar** (round 4 part 2): Studios gains AI Influencer (`/influencer`) and Content Factory (`/content-factory`) in `nav-items.ts`. Round 4 part 5 adds Character Swap Studio (`/character-swap`, short label "Character swap") after Genjutsu.
- **Models page** (round 4 part 3): `ModelRow.engines` (`src/lib/model-rows.ts`) puts an Original under both the Cloud and Open source filters, with both engine icons, "Open source + cloud" (`enginesLabel`) and a "Free · $… / megapixel" price. Since round 4 part 4 models switched off leave the list (`models-table.tsx`), which says how many and links to Settings → Models & licences.
- **Sharing** (round 4 part 4): the studio layout (`src/app/(studio)/layout.tsx`) wraps every page in `ShareProvider`, so any result menu can open the Share dialog; the Library gains the Shared tab and Publish in its selection bar, whose phone version folds Like, Pin and Review into a ⋯ menu (see Share links). The public share page lives outside the `(studio)` group, without the studio's frame.
diff --git a/src/components/preset-gallery.tsx b/src/components/preset-gallery.tsx
index 6d97c288..2417373d 100644
--- a/src/components/preset-gallery.tsx
+++ b/src/components/preset-gallery.tsx
@@ -50,7 +50,7 @@ export const PresetCard = memo(function PresetCard({
}) {
const badge = engine !== "cloud" ? parseBadgeKey(gpu) : null;
const Icon = PRESET_ICONS[preset.icon] ?? Sparkles;
- const { ref, playing, handlers } = usePreviewPlayback<HTMLAnchorElement>(preset.id);
+ const { ref, playing, handlers } = usePreviewPlayback<HTMLAnchorElement>(preset.id, preset.preview);
return (
// Prefetched on hover or touch, not on sight: a gallery shows hundreds of these.
<IntentLink
diff --git a/src/components/preset-preview.tsx b/src/components/preset-preview.tsx
index 0da86171..aba7783e 100644
--- a/src/components/preset-preview.tsx
+++ b/src/components/preset-preview.tsx
@@ -17,31 +17,32 @@ import {
} from "@/lib/preset-cards";
import { releaseVideo } from "@/lib/media-release";
import { glyphFor } from "@/lib/move-glyphs";
-import { browserPlaybackEnv, createPlaybackStore } from "@/lib/preview-playback";
+import { autoplays, browserPlaybackEnv, createPlaybackStore, playsWhenAsked, previewKind } from "@/lib/preview-playback";
import { cn } from "@/lib/utils";
-/** One preview plays at a time (rules in lib/preview-playback.ts). */
+/** Which previews play, shared by every card (rules in lib/preview-playback.ts). */
const store = createPlaybackStore(browserPlaybackEnv);
/**
* Wire a card element to the playback store. Returns whether its preview should play and the
- * handlers to spread on the card (hover and keyboard focus on desktop, after a short rest; touch
- * devices use visibility).
+ * handlers to spread on the card (hover and keyboard focus, after a short rest). A clip plays by
+ * itself while the card is in view (see autoplays).
*/
-export function usePreviewPlayback<T extends HTMLElement>(id: string) {
+export function usePreviewPlayback<T extends HTMLElement>(id: string, preview: Pick<Preview, "video" | "move" | "fx">) {
const ref = useRef<T | null>(null);
const playing = useSyncExternalStore(
store.subscribe,
- () => store.isActive(id),
+ () => store.isPlaying(id),
() => false,
);
+ const kind = previewKind(preview);
useEffect(() => {
const el = ref.current;
- if (!el || store.canHover() || store.reducedMotion()) return;
+ if (!el || !autoplays(kind, store.canHover())) return;
return store.watch(el, id);
- }, [id]);
+ }, [id, kind]);
useEffect(() => () => store.stop(id), [id]);
- const on = () => store.play(id);
+ const on = () => playsWhenAsked(kind, store.reducedMotion()) && store.play(id);
const off = () => store.stop(id);
return {
ref,
diff --git a/src/components/shorts/preset-card.tsx b/src/components/shorts/preset-card.tsx
index 56d1fb24..3dbe3d9b 100644
--- a/src/components/shorts/preset-card.tsx
+++ b/src/components/shorts/preset-card.tsx
@@ -9,7 +9,7 @@ import { LookMotif } from "./look-motif";
/**
* A selectable look card (Shorts Studio and Mixed Media): the procedural preview from the
- * galleries (plays on hover or focus, the centred card on phones), name and one line.
+ * galleries (plays on hover or focus; on phones, by itself while in view), name and one line.
*/
export const LookCard = memo(function LookCard({
id,
@@ -30,7 +30,7 @@ export const LookCard = memo(function LookCard({
onSelect: (id: string) => void;
badge?: string;
}) {
- const { ref, playing, handlers } = usePreviewPlayback<HTMLButtonElement>(id);
+ const { ref, playing, handlers } = usePreviewPlayback<HTMLButtonElement>(id, preview);
return (
<button
ref={ref}
diff --git a/src/lib/preview-playback.ts b/src/lib/preview-playback.ts
index d3b21141..dbe96537 100644
--- a/src/lib/preview-playback.ts
+++ b/src/lib/preview-playback.ts
@@ -1,9 +1,14 @@
/**
- * Which gallery preview plays (preset-preview.tsx). One at a time everywhere: on devices that can
- * hover, the hovered or focused card once the pointer has rested on it for a moment (a pointer
- * crossing the grid doesn't start every card it passes); otherwise the card nearest the middle of
- * the screen while it's mostly in view, once scrolling has stopped (phones; not with Save-Data or
- * on a 2G connection). Nothing plays when the user prefers reduced motion.
+ * 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
+ * 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
+ * for less data (Save-Data, a 2G connection) or the tab is hidden.
+ *
+ * The hovered or focused card plays too, on top of those, once the pointer has rested on it for a
+ * moment (a pointer crossing the grid doesn't start every card it passes); asked for, it plays even
+ * with Save-Data, and a clip even with reduced motion (playsWhenAsked).
*
* Pure apart from the environment it's given, so the rules are testable without a browser.
*/
@@ -15,23 +20,76 @@ export interface PlaybackEnv {
IntersectionObserver?: new (cb: IntersectionObserverCallback, opts?: IntersectionObserverInit) => Pick<IntersectionObserver, "observe" | "unobserve">;
/** Run `cb` after `ms` milliseconds; returns what cancels it. */
delay(cb: () => void, ms: number): () => void;
+ viewportWidth(): number;
viewportHeight(): number;
- onScroll(cb: () => void): void;
- offScroll(cb: () => void): void;
+ /** Scrolling anywhere on the page, or the tab being hidden or shown. */
+ on(type: "scroll" | "visibilitychange", cb: () => void): void;
+ off(type: "scroll" | "visibilitychange", cb: () => void): void;
+ /** The tab is in the background. */
+ hidden(): boolean;
/** The user asked for less data (Save-Data), or the connection is 2G. */
saveData(): boolean;
}
-/** A card must be at least this much in view to play on a phone. */
+/** A card must be at least this much in view to play by itself. */
export const MIN_VISIBLE = 0.6;
+/** 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. */
export const HOVER_INTENT = 120;
-/** On phones, how long scrolling must have stopped before the centred card plays, in ms. */
+/** How long scrolling must have stopped before the cards in view play, in ms. */
export const SCROLL_SETTLE = 400;
+/** At most this many previews play by themselves at once: on a narrow screen (a phone), and wider. */
+export const MAX_PLAYING = { narrow: 3, wide: 6 };
+/** Narrower than this (px) is a phone: the galleries show two columns. */
+export const NARROW = 640;
+
+export const maxPlaying = (viewportWidth: number) => (viewportWidth < NARROW ? MAX_PLAYING.narrow : MAX_PLAYING.wide);
+
+/** What a preview shows: a real cover's clip, a procedural animation, or a still. */
+export type PreviewKind = "clip" | "procedural" | "still";
+
+export const previewKind = (p: { video?: string; move?: string; fx?: string }): PreviewKind => (p.video ? "clip" : p.move || p.fx ? "procedural" : "still");
+
+/** Whether a preview of this kind plays by itself while it's in view: a clip anywhere, a procedural one only where nothing can hover. */
+export const autoplays = (kind: PreviewKind, canHover: boolean) => kind === "clip" || (kind === "procedural" && !canHover);
+
+/**
+ * Whether a hover, keyboard focus or tap plays a preview of this kind. With reduced motion only a clip
+ * does: a procedural preview's animations are off then (globals.css), so it keeps its poster.
+ */
+export const playsWhenAsked = (kind: PreviewKind, reducedMotion: boolean) => kind === "clip" || (kind === "procedural" && !reducedMotion);
+
+/** A watched card when the store picks which play. */
+export interface Candidate {
+ id: string;
+ /** How much of it is in view, 0..1. */
+ ratio: number;
+ /** From its centre to the screen's, in px. */
+ dist: number;
+ playing: boolean;
+}
+
+/**
+ * Which cards play by themselves, at most `max`: only those mostly 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.
+ */
+export function pickPlaying(cards: Candidate[], max: number): string[] {
+ const tier = (ratio: number) => (ratio >= FULL_VIEW ? 1 : 0);
+ const ranked = cards
+ .filter((c) => c.ratio >= MIN_VISIBLE)
+ .sort((a, b) => tier(b.ratio) - tier(a.ratio) || Number(b.playing) - Number(a.playing) || a.dist - b.dist);
+ const ids = new Set<string>();
+ for (const c of ranked) if (ids.size < max) ids.add(c.id);
+ return [...ids];
+}
export function createPlaybackStore(env: PlaybackEnv) {
const listeners = new Set<() => void>();
- let active: string | null = null;
+ /** The cards playing by themselves, and the one the pointer (or focus) is on. */
+ let auto = new Set<string>();
+ let hovered: string | null = null;
const watched = new Map<Element, string>();
const ratios = new Map<Element, number>();
let observer: Pick<IntersectionObserver, "observe" | "unobserve"> | null = null;
@@ -39,97 +97,122 @@ export function createPlaybackStore(env: PlaybackEnv) {
let pending: { id: string; cancel: () => void } | null = null;
let settle: (() => void) | null = null;
- const setActive = (id: string | null) => {
- if (active === id) return;
- active = id;
- listeners.forEach((l) => l());
+ const notify = () => listeners.forEach((l) => l());
+ const setHovered = (id: string | null) => {
+ if (hovered === id) return;
+ hovered = id;
+ notify();
+ };
+ const setAuto = (ids: string[]) => {
+ if (ids.length === auto.size && ids.every((id) => auto.has(id))) return;
+ auto = new Set(ids);
+ notify();
};
const reducedMotion = () => env.matches("(prefers-reduced-motion: reduce)");
const cancelPending = () => {
pending?.cancel();
pending = null;
};
+ const cancelSettle = () => {
+ settle?.();
+ settle = null;
+ };
- /** Phones: the most visible card closest to the viewport's middle plays. */
- const pickCentered = () => {
+ const pick = () => {
settle = null;
- const mid = env.viewportHeight() / 2;
- let best: string | null = null;
- let bestDist = Infinity;
+ const cx = env.viewportWidth() / 2;
+ const cy = env.viewportHeight() / 2;
+ const cards: Candidate[] = [];
for (const [el, ratio] of ratios) {
if (ratio < MIN_VISIBLE) continue;
const r = el.getBoundingClientRect();
- const dist = Math.abs(r.top + r.height / 2 - mid);
- if (dist < bestDist) {
- bestDist = dist;
- best = watched.get(el) ?? null;
- }
+ const id = watched.get(el)!;
+ cards.push({ id, ratio, dist: Math.hypot(r.left + r.width / 2 - cx, r.top + r.height / 2 - cy), playing: auto.has(id) });
}
- setActive(best);
+ setAuto(pickPlaying(cards, maxPlaying(env.viewportWidth())));
};
/** Pick once the page is still: every scroll (or visibility change) starts the wait over. */
const schedule = () => {
- settle?.();
- settle = env.delay(pickCentered, SCROLL_SETTLE);
+ cancelSettle();
+ if (!env.hidden()) settle = env.delay(pick, SCROLL_SETTLE);
+ };
+ // A hidden tab plays nothing (isPlaying says so); back in view, the cards on screen may have changed.
+ const onVisibility = () => {
+ if (env.hidden()) cancelSettle();
+ else if (watched.size) schedule();
+ notify();
+ };
+
+ const isPlaying = (id: string) => !env.hidden() && (hovered === id || auto.has(id));
+ /** Hover / focus: play this one once it has had the pointer for HOVER_INTENT. */
+ const play = (id: string) => {
+ cancelPending();
+ const cancel = env.delay(() => {
+ pending = null;
+ setHovered(id);
+ }, HOVER_INTENT);
+ pending = { id, cancel };
+ };
+ /** Stop this one, if it's the one hovered (or about to be); a card playing by itself goes on. */
+ const stop = (id: string) => {
+ if (pending?.id === id) cancelPending();
+ if (hovered === id) setHovered(null);
};
return {
subscribe(l: () => void) {
+ if (!listeners.size) env.on("visibilitychange", onVisibility);
listeners.add(l);
return () => {
listeners.delete(l);
+ if (!listeners.size) env.off("visibilitychange", onVisibility);
};
},
- getActive: () => active,
- isActive: (id: string) => active === id,
+ isPlaying,
+ /** Every card playing now, by id (for tests). */
+ playing: () => [...new Set([...auto, ...(hovered ? [hovered] : [])])].filter(isPlaying).sort(),
canHover: () => env.matches("(hover: hover) and (pointer: fine)"),
reducedMotion,
saveData: () => env.saveData(),
- /** Hover / focus: play this one once it has had the pointer for HOVER_INTENT (unless motion is reduced). */
- play(id: string) {
- cancelPending();
- if (reducedMotion()) return;
- const cancel = env.delay(() => {
- pending = null;
- setActive(id);
- }, HOVER_INTENT);
- pending = { id, cancel };
- },
- /** Stop this one, if it's the one playing (or about to). */
- stop(id: string) {
- if (pending?.id === id) cancelPending();
- if (active === id) setActive(null);
- },
- /** Touch devices: let visibility decide whether `el` plays. Returns the cleanup. */
+ play,
+ stop,
+ /** A tap: play this one, or stop it if a tap already did. */
+ toggle: (id: string) => (hovered === id || pending?.id === id ? stop(id) : play(id)),
+ /** Let visibility decide whether `el` plays by itself (see autoplays). Returns the cleanup. */
watch(el: Element, id: string): () => void {
const IO = env.IntersectionObserver;
- // Each card passing the middle of the screen would start a download: none with Save-Data or on 2G.
- if (!IO || env.saveData()) return () => {};
+ // Each card that comes into view would start a download, and motion the user didn't ask for: none
+ // with Save-Data, on 2G or with reduced motion.
+ if (!IO || env.saveData() || reducedMotion()) return () => {};
observer ??= new IO(
(entries) => {
for (const e of entries) {
+ const card = watched.get(e.target);
+ if (card === undefined) continue;
const ratio = e.isIntersecting ? e.intersectionRatio : 0;
ratios.set(e.target, ratio);
- // The playing card stops as soon as it's mostly out of view; the next one waits for the scroll to settle.
- if (ratio < MIN_VISIBLE && active !== null && watched.get(e.target) === active) setActive(null);
+ // A playing card stops as soon as it's mostly out of view; the next ones wait for the scroll to settle.
+ if (ratio < MIN_VISIBLE && auto.has(card)) setAuto([...auto].filter((a) => a !== card));
}
schedule();
},
- { threshold: [0, MIN_VISIBLE, 0.85, 1] },
+ { threshold: [0, MIN_VISIBLE, FULL_VIEW, 1] },
);
- if (!watched.size) env.onScroll(schedule);
+ if (!watched.size) env.on("scroll", schedule);
watched.set(el, id);
observer.observe(el);
return () => {
observer?.unobserve(el);
watched.delete(el);
ratios.delete(el);
- if (!watched.size) {
- env.offScroll(schedule);
- settle?.();
- settle = null;
+ if (auto.has(id)) setAuto([...auto].filter((a) => a !== id));
+ if (watched.size) {
+ // Its place goes to the next card in view.
+ schedule();
+ } else {
+ env.off("scroll", schedule);
+ cancelSettle();
}
- if (active === id) setActive(null);
};
},
/** For tests: how many cards are watched. */
@@ -151,9 +234,12 @@ export const browserPlaybackEnv: PlaybackEnv = {
const t = setTimeout(cb, ms);
return () => clearTimeout(t);
},
+ viewportWidth: () => window.innerWidth,
viewportHeight: () => window.innerHeight,
- onScroll: (cb) => window.addEventListener("scroll", cb, { passive: true, capture: true }),
- offScroll: (cb) => window.removeEventListener("scroll", cb, { capture: true }),
+ // Scrolls are caught from every scroller (capture), a horizontal row's included.
+ on: (type, cb) => (type === "scroll" ? window.addEventListener("scroll", cb, { passive: true, capture: true }) : document.addEventListener(type, cb)),
+ off: (type, cb) => (type === "scroll" ? window.removeEventListener("scroll", cb, { capture: true }) : document.removeEventListener(type, cb)),
+ hidden: () => typeof document !== "undefined" && document.hidden,
saveData: () => {
const c = typeof navigator === "undefined" ? undefined : (navigator as Navigator & { connection?: Connection }).connection;
// effectiveType is "slow-2g", "2g", "3g" or "4g" (Chromium only; elsewhere this is false).
diff --git a/tests/shell-logic.test.ts b/tests/shell-logic.test.ts
index 85eeec73..3b61ce8a 100644
--- a/tests/shell-logic.test.ts
+++ b/tests/shell-logic.test.ts
@@ -16,7 +16,22 @@ import {
type CameraMove,
} from "@/lib/preset-cards";
import { previewFor, toPresetCard } from "@/lib/preset-card-data";
-import { browserPlaybackEnv, createPlaybackStore, HOVER_INTENT, MIN_VISIBLE, SCROLL_SETTLE, type PlaybackEnv } from "@/lib/preview-playback";
+import {
+ autoplays,
+ browserPlaybackEnv,
+ createPlaybackStore,
+ FULL_VIEW,
+ HOVER_INTENT,
+ MAX_PLAYING,
+ maxPlaying,
+ MIN_VISIBLE,
+ pickPlaying,
+ playsWhenAsked,
+ previewKind,
+ SCROLL_SETTLE,
+ type PlaybackEnv,
+ type PlaybackStore,
+} from "@/lib/preview-playback";
import { pageAfter, progressiveStart, syncProgressive } from "@/lib/progressive";
import { storyboardName } from "@/lib/storyboard-board";
@@ -81,10 +96,11 @@ describe("progressive list paging", () => {
});
/** A fake browser for the playback store, with a clock that only moves when `advance` says so. */
-function fakeEnv({ hover = false, reduced = false, height = 800, saveData = false } = {}) {
+function fakeEnv({ hover = false, reduced = false, width = 1280, height = 800, saveData = false } = {}) {
let ioCallback: IntersectionObserverCallback | null = null;
const observed = new Set<Element>();
- const scroll = new Set<() => void>();
+ const listeners = { scroll: new Set<() => void>(), visibilitychange: new Set<() => void>() };
+ let hidden = false;
let now = 0;
const timers = new Set<{ at: number; cb: () => void }>();
const next = () => [...timers].sort((a, b) => a.at - b.at)[0];
@@ -116,117 +132,187 @@ function fakeEnv({ hover = false, reduced = false, height = 800, saveData = fals
timers.add(t);
return () => void timers.delete(t);
},
+ viewportWidth: () => width,
viewportHeight: () => height,
- onScroll: (cb) => scroll.add(cb),
- offScroll: (cb) => scroll.delete(cb),
+ on: (type, cb) => void listeners[type].add(cb),
+ off: (type, cb) => void listeners[type].delete(cb),
+ hidden: () => hidden,
saveData: () => saveData,
};
- const card = (top: number, h = 200) => ({ getBoundingClientRect: () => ({ top, height: h }) }) as unknown as Element;
+ /** A card whose box starts `top` px down and `left` px across the screen. */
+ const card = (top: number, left = 0, width = 240, height = 180) => ({ getBoundingClientRect: () => ({ top, left, width, height }) }) 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);
- const scrolled = () => scroll.forEach((f) => f());
- return { env, card, intersect, scrolled, advance, observed, scroll, timers };
+ const scrolled = () => listeners.scroll.forEach((f) => f());
+ /** The tab goes to the background (or comes back). */
+ const setHidden = (h: boolean) => {
+ hidden = h;
+ listeners.visibilitychange.forEach((f) => f());
+ };
+ return { env, card, intersect, scrolled, setHidden, advance, observed, listeners, timers };
+}
+
+/** Cards in a grid, `rows` × `cols` of `w` × `h` with 20 px between them, watched by `store` and all in full view: "r1c2" is row 1, column 2. */
+function watchGrid(store: PlaybackStore, { card, intersect }: ReturnType<typeof fakeEnv>, rows: number, cols: number, w = 240, h = 180) {
+ const cards = new Map<string, Element>();
+ for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) cards.set(`r${r}c${c}`, card(r * (h + 20), c * (w + 20), w, h));
+ for (const [id, el] of cards) store.watch(el, id);
+ intersect([...cards.values()].map((el) => [el, 1]));
+ return cards;
}
describe("preview playback store", () => {
- it("plays one preview at a time and stops only the one playing", () => {
+ it("plays the card the pointer rests on, one at a time", () => {
const { env, advance } = fakeEnv({ hover: true });
const store = createPlaybackStore(env);
- const seen: (string | null)[] = [];
- store.subscribe(() => seen.push(store.getActive()));
+ const seen: string[][] = [];
+ store.subscribe(() => seen.push(store.playing()));
store.play("a");
advance(HOVER_INTENT);
store.play("b");
advance(HOVER_INTENT);
- expect(store.isActive("a")).toBe(false);
- expect(store.isActive("b")).toBe(true);
+ expect(store.isPlaying("a")).toBe(false);
+ expect(store.isPlaying("b")).toBe(true);
store.stop("a");
- expect(store.getActive()).toBe("b");
+ expect(store.playing()).toEqual(["b"]);
store.stop("b");
- expect(seen).toEqual(["a", "b", null]);
+ expect(seen).toEqual([["a"], ["b"], []]);
});
it("waits for the pointer to rest on a card before playing it", () => {
const { env, advance, timers } = fakeEnv({ hover: true });
const store = createPlaybackStore(env);
- const seen: (string | null)[] = [];
- store.subscribe(() => seen.push(store.getActive()));
+ const seen: string[][] = [];
+ store.subscribe(() => seen.push(store.playing()));
// Crossing one card on the way to another starts neither until the pointer stops.
store.play("a");
advance(HOVER_INTENT - 20);
store.stop("a");
store.play("b");
advance(HOVER_INTENT - 1);
- expect(store.getActive()).toBeNull();
+ expect(store.playing()).toEqual([]);
advance(1);
- expect(store.getActive()).toBe("b");
+ expect(store.playing()).toEqual(["b"]);
// Leaving before the intent is up calls it off.
store.play("c");
store.stop("c");
expect(timers.size).toBe(0);
advance(1000);
- expect(seen).toEqual(["b"]);
+ expect(seen).toEqual([["b"]]);
});
- it("plays nothing when the user prefers reduced motion", () => {
- const { env, advance } = fakeEnv({ reduced: true });
- const store = createPlaybackStore(env);
- store.play("a");
- advance(HOVER_INTENT);
- expect(store.getActive()).toBeNull();
- expect(store.reducedMotion()).toBe(true);
- });
-
- it("on phones plays the mostly visible card nearest the middle of the screen, once scrolling stops", () => {
- const { env, card, intersect, scrolled, advance } = fakeEnv({ height: 800 });
+ it("plays the cards in view by themselves once scrolling stops, the six nearest the middle of a wide screen", () => {
+ const fake = fakeEnv({ hover: true, width: 1280, height: 800 });
+ const store = createPlaybackStore(fake.env);
+ // Four rows of four: card centres at x 120, 380, 640, 900 and y 90, 290, 490, 690; the screen's middle is (640, 400).
+ watchGrid(store, fake, 4, 4);
+ // Still scrolling: nothing starts (or downloads) yet.
+ fake.advance(SCROLL_SETTLE - 100);
+ fake.scrolled();
+ fake.advance(SCROLL_SETTLE - 1);
+ expect(store.playing()).toEqual([]);
+ fake.advance(1);
+ expect(store.playing()).toEqual(["r1c1", "r1c2", "r1c3", "r2c1", "r2c2", "r2c3"]);
+ });
+
+ it("plays at most three at once on a phone", () => {
+ const fake = fakeEnv({ width: 390, height: 844 });
+ const store = createPlaybackStore(fake.env);
+ // Two columns, four rows: card centres at y 70, 230, 390, 550 (the middle is 422).
+ watchGrid(store, fake, 4, 2, 175, 140);
+ fake.advance(SCROLL_SETTLE);
+ expect(store.playing()).toHaveLength(MAX_PLAYING.narrow);
+ expect(store.playing()).toEqual(expect.arrayContaining(["r2c0", "r2c1"]));
+ expect(maxPlaying(390)).toBe(MAX_PLAYING.narrow);
+ expect(maxPlaying(1280)).toBe(MAX_PLAYING.wide);
+ });
+
+ 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)];
+ expect(pickPlaying(cards, 2)).toEqual(["playing", "near"]);
+ expect(pickPlaying(cards, 4)).toEqual(["playing", "near", "far", "partly"]);
+ // Never a card that isn't mostly in view, whatever the room.
+ expect(pickPlaying(cards, 10)).not.toContain("hidden");
+ // The same preset twice on a page takes one place.
+ expect(pickPlaying([c("a", 1, 0), c("a", 1, 5), c("b", 1, 9)], 2)).toEqual(["a", "b"]);
+ });
+
+ it("stops a playing card as soon as it scrolls mostly out of view; the next one waits for the scroll to settle", () => {
+ const { env, card, intersect, advance } = fakeEnv({ width: 390 });
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");
+ const cards = [card(0), card(200), card(400), card(600)];
+ cards.forEach((el, i) => store.watch(el, `c${i}`));
+ intersect(cards.slice(0, 3).map((el) => [el, 1]));
+ advance(SCROLL_SETTLE);
+ expect(store.playing()).toEqual(["c0", "c1", "c2"]);
intersect([
- [top, 1],
- [mid, MIN_VISIBLE - 0.1],
- [low, 1],
+ [cards[0], MIN_VISIBLE - 0.1],
+ [cards[3], 1],
]);
- // Still scrolling: nothing starts (or downloads) yet.
- advance(SCROLL_SETTLE - 100);
- scrolled();
- advance(SCROLL_SETTLE - 1);
- expect(store.getActive()).toBeNull();
- advance(1);
- // The middle card isn't visible enough yet.
- expect(store.getActive()).toBe("low");
- intersect([[mid, 0.9]]);
- expect(store.getActive()).toBe("low");
+ expect(store.playing()).toEqual(["c1", "c2"]);
advance(SCROLL_SETTLE);
- expect(store.getActive()).toBe("mid");
- });
-
- it("stops the playing card as soon as it scrolls mostly out of view", () => {
- const { env, card, intersect, advance } = fakeEnv();
+ expect(store.playing()).toEqual(["c1", "c2", "c3"]);
+ });
+
+ it("keeps a hovered card playing while it plays by itself, and plays a hovered one beyond the cap", () => {
+ const fake = fakeEnv({ hover: true, width: 390 });
+ const store = createPlaybackStore(fake.env);
+ watchGrid(store, fake, 4, 2, 175, 140);
+ fake.advance(SCROLL_SETTLE);
+ const [auto] = store.playing();
+ store.play(auto);
+ fake.advance(HOVER_INTENT);
+ store.stop(auto);
+ expect(store.isPlaying(auto)).toBe(true);
+ store.play("r0c0");
+ fake.advance(HOVER_INTENT);
+ expect(store.playing()).toHaveLength(MAX_PLAYING.narrow + 1);
+ });
+
+ it("pauses everything while the tab is hidden, and goes on when it's back", () => {
+ const fake = fakeEnv({ hover: true, width: 390 });
+ const store = createPlaybackStore(fake.env);
+ const seen: string[][] = [];
+ store.subscribe(() => seen.push(store.playing()));
+ watchGrid(store, fake, 1, 2);
+ fake.advance(SCROLL_SETTLE);
+ store.play("hovered");
+ fake.advance(HOVER_INTENT);
+ fake.scrolled();
+ fake.setHidden(true);
+ expect(store.isPlaying("hovered")).toBe(false);
+ // A pick waiting for the scroll to settle is called off too.
+ expect(fake.timers.size).toBe(0);
+ fake.setHidden(false);
+ expect(seen).toEqual([["r0c0", "r0c1"], ["hovered", "r0c0", "r0c1"], [], ["hovered", "r0c0", "r0c1"]]);
+ // Back in view, it looks again once the page is still.
+ expect(fake.timers.size).toBe(1);
+ });
+
+ it("with reduced motion nothing plays by itself, but hover and keyboard focus still do", () => {
+ const { env, card, advance, observed, listeners } = fakeEnv({ reduced: true });
const store = createPlaybackStore(env);
- const a = card(300);
- store.watch(a, "a");
- intersect([[a, 1]]);
- advance(SCROLL_SETTLE);
- expect(store.getActive()).toBe("a");
- intersect([[a, MIN_VISIBLE - 0.1]]);
- expect(store.getActive()).toBeNull();
+ store.watch(card(300), "a")();
+ expect(store.watchedCount()).toBe(0);
+ expect(observed.size).toBe(0);
+ expect(listeners.scroll.size).toBe(0);
+ store.play("a");
+ advance(HOVER_INTENT);
+ expect(store.playing()).toEqual(["a"]);
+ expect(store.reducedMotion()).toBe(true);
});
- it("doesn't autoplay on phones with Save-Data or on a 2G connection (hover still plays)", () => {
- const { env, card, advance, observed, scroll } = fakeEnv({ saveData: true });
+ it("with Save-Data or on a 2G connection nothing plays by itself (hover still does)", () => {
+ const { env, card, advance, observed, listeners } = fakeEnv({ saveData: true });
const store = createPlaybackStore(env);
store.watch(card(300), "a")();
expect(store.watchedCount()).toBe(0);
expect(observed.size).toBe(0);
- expect(scroll.size).toBe(0);
+ expect(listeners.scroll.size).toBe(0);
store.play("a");
advance(HOVER_INTENT);
- expect(store.getActive()).toBe("a");
+ expect(store.playing()).toEqual(["a"]);
});
it("reads Save-Data and the connection type from the browser", () => {
@@ -245,27 +331,41 @@ describe("preview playback store", () => {
}
});
- it("cleans up: unwatching stops the card and the last one removes the scroll listener", () => {
- const { env, card, intersect, advance, observed, scroll, timers } = fakeEnv();
+ it("a tap plays a preview and the next tap stops it (the preset header when nothing plays by itself)", () => {
+ const { env, advance } = fakeEnv({ reduced: true });
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]]);
+ store.toggle("a");
+ advance(HOVER_INTENT);
+ expect(store.playing()).toEqual(["a"]);
+ store.toggle("a");
+ expect(store.playing()).toEqual([]);
+ });
+
+ it("cleans up: unwatching stops the card and frees its place, the last one removes the listeners", () => {
+ const { env, card, intersect, advance, observed, listeners, timers } = fakeEnv({ width: 390 });
+ const store = createPlaybackStore(env);
+ const off = store.subscribe(() => {});
+ expect(listeners.visibilitychange.size).toBe(1);
+ const els = [card(0), card(200), card(400), card(600)];
+ const unwatch = els.map((el, i) => store.watch(el, `c${i}`));
+ expect(listeners.scroll.size).toBe(1);
+ intersect(els.map((el) => [el, 1]));
+ advance(SCROLL_SETTLE);
+ expect(store.playing()).toEqual(["c1", "c2", "c3"]);
+ unwatch[2]();
+ expect(store.playing()).toEqual(["c1", "c3"]);
+ expect(observed.has(els[2])).toBe(false);
advance(SCROLL_SETTLE);
- expect(store.getActive()).toBe("a");
- offA();
- expect(store.getActive()).toBeNull();
- expect(observed.has(a)).toBe(false);
- expect(scroll.size).toBe(1);
- intersect([[b, 1]]);
- offB();
+ expect(store.playing()).toEqual(["c0", "c1", "c3"]);
+ intersect([[els[0], 0.9]]);
+ unwatch.forEach((u) => u());
expect(store.watchedCount()).toBe(0);
- expect(scroll.size).toBe(0);
+ expect(store.playing()).toEqual([]);
+ expect(listeners.scroll.size).toBe(0);
// A pick still waiting for the scroll to settle goes with the last card.
expect(timers.size).toBe(0);
+ off();
+ expect(listeners.visibilitychange.size).toBe(0);
});
it("does nothing without IntersectionObserver", () => {
@@ -274,6 +374,22 @@ describe("preview playback store", () => {
store.watch(card(0), "a")();
expect(store.watchedCount()).toBe(0);
});
+
+ it("plays a clip by itself everywhere, a procedural preview only where nothing can hover, a still never", () => {
+ expect(previewKind({ video: "/previews/presets/a.mp4" })).toBe("clip");
+ expect(previewKind({ move: "dolly-in" })).toBe("procedural");
+ expect(previewKind({ fx: "fire" })).toBe("procedural");
+ expect(previewKind({})).toBe("still");
+ expect([true, false].map((hover) => autoplays("clip", hover))).toEqual([true, true]);
+ expect([true, false].map((hover) => autoplays("procedural", hover))).toEqual([false, true]);
+ expect([true, false].map((hover) => autoplays("still", hover))).toEqual([false, false]);
+ });
+
+ it("with reduced motion a hover or tap plays a clip, but a procedural preview keeps its poster", () => {
+ expect([false, true].map((reduced) => playsWhenAsked("clip", reduced))).toEqual([true, true]);
+ expect([false, true].map((reduced) => playsWhenAsked("procedural", reduced))).toEqual([true, false]);
+ expect([false, true].map((reduced) => playsWhenAsked("still", reduced))).toEqual([false, false]);
+ });
});
describe("camera move diagrams", () => {