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: reduced motion turned on while a page is open stops the clips

Adarsh5993d499c880
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 83102697..72becc9d 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 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).
+- **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 (turned on while the page is open, it stops at once), 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/docs/STATUS.md b/docs/STATUS.md
index d957cb39..aca6abd7 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -205,7 +205,7 @@ Model names are the defaults first, then the alternatives. "Demo" outputs are la
| Live progress, cancel, retry, failure messages | ✅ | — | — | Results arrive over one server-sent-events stream per browser; polling slows to every 10 s while it's connected (1.5 s without it). Running tiles show the time spent and, once progress has moved, the time left; the newest single result offers next steps (Animate, Upscale, Edit for an image; Extend, Upscale, Add sound for a video; Lipsync, Voice change for audio) |
| Browser notifications | ✅ | — | — | Opt-in per browser (Settings → Notifications, with Send a test), plus a one-time offer once a job has run about 20 s. A job that finishes or fails while no Fuobe tab is on screen notifies once, from the live stream's leader tab; clicking it opens the result. The tab title counts running jobs. `tests/e2e/notifications.mjs` |
| Text, 3D and layer results | ✅ | — | — | Shown in the feed, viewer and Library: text with cue timings (copy, .txt / .srt / .vtt), .glb in `@google/model-viewer` (loaded on demand), layers as a composite with a named list, SVG as SVG, EXR frames as a .zip, and ProRes or FFV1 (which browsers don't play) as a file card. A rigged .glb plays its animation instead of turning; a splat shows its orbit video or picture and a .spz / .ply download, not a 3D view. A Fuobe Soul result's details show its Look and Finish |
-| Studio UI (composer, model picker, viewer, galleries, navigation) | ✅ | — | — | Compact composer ("+" for upload / paste / library, one settings chip, Cmd/Ctrl+Enter), cmdk model picker with Recent / Starred / Best for this studio, typing before hydration kept, blockers that name the missing slot (on phones a line under the composer says why Generate is blocked); viewer with a phone bottom bar, drawer and swipe; covers rendered in ComfyUI on 480 of the 487 app, motion and effect cards (432 stills and 48 clips that play on hover), procedural previews on the rest; one prerendered page per hub mode; a skip link, one `<main>` per page, a shorter sidebar (Engine starts folded; Studios starts open so first visits see the studios), full-screen studios that fold it, a phone header with Search, links that prefetch on hover; branded 404 and error pages (unknown ids and hub modes answer a real 404), loading skeletons. Reuse of a run on a retired model brings it back on its replacement, with a toast saying what changed, and `?model=` with a retired id opens the replacement (round 4, part 5). Checked by `composer-flows.mjs`, `shell.mjs` and the 390 px sweep |
+| Studio UI (composer, model picker, viewer, galleries, navigation) | ✅ | — | — | Compact composer ("+" for upload / paste / library, one settings chip, Cmd/Ctrl+Enter), cmdk model picker with Recent / Starred / Best for this studio, typing before hydration kept, blockers that name the missing slot (on phones a line under the composer says why Generate is blocked); viewer with a phone bottom bar, drawer and swipe; covers rendered in ComfyUI on 480 of the 487 app, motion and effect cards (432 stills and 48 clips that play by themselves while their card is in view, a few at a time; hover plays one too; none with reduced motion or Save-Data), procedural previews on the rest; one prerendered page per hub mode; a skip link, one `<main>` per page, a shorter sidebar (Engine starts folded; Studios starts open so first visits see the studios), full-screen studios that fold it, a phone header with Search, links that prefetch on hover; branded 404 and error pages (unknown ids and hub modes answer a real 404), loading skeletons. Reuse of a run on a retired model brings it back on its replacement, with a toast saying what changed, and `?model=` with a retired id opens the replacement (round 4, part 5). Checked by `composer-flows.mjs`, `shell.mjs` and the 390 px sweep |
| Search (⌘K / Ctrl+K palette) | ✅ | — | — | Searches pages, settings, apps, motions, effects, models (filtered to the engine mode) and recent creations, forgiving typos; a model opens where it runs, on its own engine (every Image to 3D model and Meshy Rigging now open `/image-to-3d`; an Original is listed once, as "Open source + cloud"). 33 models still open the filtered Models page (§3). Models switched off in Settings → Models & licences leave the palette; it finds Models & licences and Assist connectors. Checked by `shell.mjs` |
| Getting started and connections | ✅ app · ✅ ComfyUI when busy (tests, a live CPU run) · 🟢 Ollama when busy (tested against a stand-in), key tests and AI-Toolkit | Save & test for the fal.ai, Replicate and Anthropic keys, and the civitai key (Settings → LoRAs). Preferred provider: Automatic, fal.ai first or Replicate first (the Higgsfield key and "Higgsfield first" are gone since round 4, part 5) | Save & test for the ComfyUI address, its auth token, the isolated worker, and each local LLM server's URL, model and key (Settings → AI helper) | A Get started card on Home and Settings: Use paid models, Use your GPU, or Just try it (the demo). Every connection field tests what you typed before saving it and gives the reason on failure; a status strip shows each connection. Home's Start runs the job in Image, Video or Edit, and the line under the box says first what will run and what it costs. Settings → About & licences (`/settings/about`) lists every open model's licence and links to Settings → Models & licences. **A busy ComfyUI counts as up** (round 4, part 5): before, one 1.5–2 s check decided, so a busy ComfyUI could send new runs to demo. Now it counts as up if it answered in the last 2 minutes, or if its port accepts a connection and it answers a longer 10 s check; refused, an unknown host or an HTTP error still means down at once, and a port that never answers (a hung ComfyUI, a tunnel to a dead box) is down after the 10 s check. A chain step after real ComfyUI steps waits up to 60 s for ComfyUI ("Waits for ComfyUI to answer") before failing; cloud steps don't wait. **Ollama follows the same rules** since Fixes 5 (round 5, part 1): a late answer counts as busy if Ollama answered in the last 2 minutes, otherwise it gets one longer 10 s look if its port takes a connection, and a refused port or an HTTP error is down at once. A busy Ollama no longer sends Assist to the offline planner, and opening Assist waits at most 1.5 s for an Ollama that never answers. **Settings → Training · AI-Toolkit** (`/settings#training`, also in ⌘K; new in Fixes 5): the AI-Toolkit address (`http://127.0.0.1:8675` by default), an optional token and the photos folder, each with Save & test; the test says when the trainer wants a token or rejects one, when something else answers, and which trainings are still running, and the folder test checks it can be written without creating it. A saved token is never sent to a new, unsaved address, and the section is dimmed in Paid APIs only. Train dialogs' Open Settings now goes to the section that clears their blocker, and messages that named Settings sections that don't exist now name real ones (a test keeps it so). A live ComfyUI connected through the guide; no accepted key, no running Ollama and no real AI-Toolkit were tested. Round 5, part 2: main's GPU pre-flight board (`/connect`) gains rows for Split soundtrack, Fly path and Turnaround and lists MOSS-Image under Image; its index, `workflows/comfyui/requirements.json`, now covers 158 workflows, 161 files and 20 node packs (`public-signup-tools` checks the rows against it). Sizes asked of ComfyUI now snap to each graph's 16-pixel grid and largest side, and Workflows → Copy install commands creates the model subfolders |
| Engine choice (open only, paid only, both) | ✅ | — | — | Settings → Engine mode, or `FUOBE_ENGINE_MODE` |
diff --git a/src/lib/preview-playback.ts b/src/lib/preview-playback.ts
index dbe96537..225404ad 100644
--- a/src/lib/preview-playback.ts
+++ b/src/lib/preview-playback.ts
@@ -4,7 +4,8 @@
* 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.
+ * for less data (Save-Data, a 2G connection) or the tab is hidden; reduced motion turned on while the
+ * page is open stops what plays by itself at once.
*
* 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
@@ -13,6 +14,10 @@
* Pure apart from the environment it's given, so the rules are testable without a browser.
*/
+export type PlaybackEvent = "scroll" | "visibilitychange" | "motion";
+
+const REDUCED_MOTION = "(prefers-reduced-motion: reduce)";
+
/** What the store needs from the browser. */
export interface PlaybackEnv {
matches(query: string): boolean;
@@ -22,9 +27,9 @@ export interface PlaybackEnv {
delay(cb: () => void, ms: number): () => void;
viewportWidth(): number;
viewportHeight(): number;
- /** 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;
+ /** Scrolling anywhere on the page, the tab being hidden or shown, or the reduced-motion setting changing. */
+ on(type: PlaybackEvent, cb: () => void): void;
+ off(type: PlaybackEvent, cb: () => void): void;
/** The tab is in the background. */
hidden(): boolean;
/** The user asked for less data (Save-Data), or the connection is 2G. */
@@ -108,7 +113,7 @@ export function createPlaybackStore(env: PlaybackEnv) {
auto = new Set(ids);
notify();
};
- const reducedMotion = () => env.matches("(prefers-reduced-motion: reduce)");
+ const reducedMotion = () => env.matches(REDUCED_MOTION);
const cancelPending = () => {
pending?.cancel();
pending = null;
@@ -120,6 +125,7 @@ export function createPlaybackStore(env: PlaybackEnv) {
const pick = () => {
settle = null;
+ if (reducedMotion() || env.saveData()) return setAuto([]);
const cx = env.viewportWidth() / 2;
const cy = env.viewportHeight() / 2;
const cards: Candidate[] = [];
@@ -143,7 +149,14 @@ export function createPlaybackStore(env: PlaybackEnv) {
notify();
};
- const isPlaying = (id: string) => !env.hidden() && (hovered === id || auto.has(id));
+ // Reduced motion turned on stops what plays by itself at once (isPlaying) and the next pick chooses
+ // nothing; turned off, the cards in view are picked again.
+ const onMotion = () => {
+ if (watched.size) schedule();
+ notify();
+ };
+
+ const isPlaying = (id: string) => !env.hidden() && (hovered === id || (auto.has(id) && !reducedMotion()));
/** Hover / focus: play this one once it has had the pointer for HOVER_INTENT. */
const play = (id: string) => {
cancelPending();
@@ -161,11 +174,16 @@ export function createPlaybackStore(env: PlaybackEnv) {
return {
subscribe(l: () => void) {
- if (!listeners.size) env.on("visibilitychange", onVisibility);
+ if (!listeners.size) {
+ env.on("visibilitychange", onVisibility);
+ env.on("motion", onMotion);
+ }
listeners.add(l);
return () => {
listeners.delete(l);
- if (!listeners.size) env.off("visibilitychange", onVisibility);
+ if (listeners.size) return;
+ env.off("visibilitychange", onVisibility);
+ env.off("motion", onMotion);
};
},
isPlaying,
@@ -181,9 +199,9 @@ export function createPlaybackStore(env: PlaybackEnv) {
/** 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 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 () => {};
+ // Each card that comes into view would start a download: none with Save-Data or on 2G. With
+ // reduced motion it's watched but not picked (pick), so turning the setting off plays it.
+ if (!IO || env.saveData()) return () => {};
observer ??= new IO(
(entries) => {
for (const e of entries) {
@@ -224,6 +242,10 @@ export type PlaybackStore = ReturnType<typeof createPlaybackStore>;
type Connection = { saveData?: boolean; effectiveType?: string };
+/** The reduced-motion query, kept: a change listener comes off only the list it was added to. */
+let motionQuery: MediaQueryList | undefined;
+const reducedMotionQuery = () => (typeof window.matchMedia === "function" ? (motionQuery ??= window.matchMedia(REDUCED_MOTION)) : undefined);
+
/** The real browser; every member is safe to call during server rendering. */
export const browserPlaybackEnv: PlaybackEnv = {
matches: (q) => typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia(q).matches,
@@ -237,8 +259,16 @@ export const browserPlaybackEnv: PlaybackEnv = {
viewportWidth: () => window.innerWidth,
viewportHeight: () => window.innerHeight,
// 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)),
+ on: (type, cb) => {
+ if (type === "scroll") window.addEventListener("scroll", cb, { passive: true, capture: true });
+ else if (type === "motion") reducedMotionQuery()?.addEventListener("change", cb);
+ else document.addEventListener(type, cb);
+ },
+ off: (type, cb) => {
+ if (type === "scroll") window.removeEventListener("scroll", cb, { capture: true });
+ else if (type === "motion") reducedMotionQuery()?.removeEventListener("change", cb);
+ else document.removeEventListener(type, cb);
+ },
hidden: () => typeof document !== "undefined" && document.hidden,
saveData: () => {
const c = typeof navigator === "undefined" ? undefined : (navigator as Navigator & { connection?: Connection }).connection;
diff --git a/tests/shell-logic.test.ts b/tests/shell-logic.test.ts
index 3b61ce8a..8ecd9ef7 100644
--- a/tests/shell-logic.test.ts
+++ b/tests/shell-logic.test.ts
@@ -99,7 +99,7 @@ describe("progressive list paging", () => {
function fakeEnv({ hover = false, reduced = false, width = 1280, height = 800, saveData = false } = {}) {
let ioCallback: IntersectionObserverCallback | null = null;
const observed = new Set<Element>();
- const listeners = { scroll: new Set<() => void>(), visibilitychange: new Set<() => void>() };
+ const listeners = { scroll: new Set<() => void>(), visibilitychange: new Set<() => void>(), motion: new Set<() => void>() };
let hidden = false;
let now = 0;
const timers = new Set<{ at: number; cb: () => void }>();
@@ -139,6 +139,8 @@ function fakeEnv({ hover = false, reduced = false, width = 1280, height = 800, s
hidden: () => hidden,
saveData: () => saveData,
};
+ /** The connection turns to Save-Data or 2G (no event: the next pick reads it). */
+ const setSaveData = (on: boolean) => void (saveData = on);
/** 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][]) =>
@@ -149,7 +151,12 @@ function fakeEnv({ hover = false, reduced = false, width = 1280, height = 800, s
hidden = h;
listeners.visibilitychange.forEach((f) => f());
};
- return { env, card, intersect, scrolled, setHidden, advance, observed, listeners, timers };
+ /** The user turns reduced motion on (or off) while the page is open. */
+ const setReduced = (r: boolean) => {
+ reduced = r;
+ listeners.motion.forEach((f) => f());
+ };
+ return { env, card, intersect, scrolled, setHidden, setReduced, setSaveData, 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. */
@@ -291,18 +298,44 @@ describe("preview playback store", () => {
});
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);
- 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"]);
+ const fake = fakeEnv({ reduced: true });
+ const store = createPlaybackStore(fake.env);
+ watchGrid(store, fake, 1, 2);
+ fake.advance(SCROLL_SETTLE);
+ expect(store.playing()).toEqual([]);
+ store.play("r0c0");
+ fake.advance(HOVER_INTENT);
+ expect(store.playing()).toEqual(["r0c0"]);
expect(store.reducedMotion()).toBe(true);
});
+ it("follows reduced motion turned on or off while the page is open", () => {
+ const fake = fakeEnv({ hover: true });
+ const store = createPlaybackStore(fake.env);
+ const off = store.subscribe(() => {});
+ expect(fake.listeners.motion.size).toBe(1);
+ watchGrid(store, fake, 1, 3);
+ fake.advance(SCROLL_SETTLE);
+ expect(store.playing()).toEqual(["r0c0", "r0c1", "r0c2"]);
+ // Turned on: what plays by itself stops at once, and a scroll doesn't start it again.
+ fake.setReduced(true);
+ expect(store.playing()).toEqual([]);
+ fake.scrolled();
+ fake.advance(SCROLL_SETTLE);
+ expect(store.playing()).toEqual([]);
+ // A hover still plays one.
+ store.play("r0c1");
+ fake.advance(HOVER_INTENT);
+ expect(store.playing()).toEqual(["r0c1"]);
+ store.stop("r0c1");
+ // Turned off: the cards in view play again once the page is still.
+ fake.setReduced(false);
+ fake.advance(SCROLL_SETTLE);
+ expect(store.playing()).toEqual(["r0c0", "r0c1", "r0c2"]);
+ off();
+ expect(fake.listeners.motion.size).toBe(0);
+ });
+
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);
@@ -315,6 +348,18 @@ describe("preview playback store", () => {
expect(store.playing()).toEqual(["a"]);
});
+ it("stops what plays by itself at the next pick once the connection turns to Save-Data or 2G", () => {
+ const fake = fakeEnv();
+ const store = createPlaybackStore(fake.env);
+ watchGrid(store, fake, 1, 2);
+ fake.advance(SCROLL_SETTLE);
+ expect(store.playing()).toEqual(["r0c0", "r0c1"]);
+ fake.setSaveData(true);
+ fake.scrolled();
+ fake.advance(SCROLL_SETTLE);
+ expect(store.playing()).toEqual([]);
+ });
+
it("reads Save-Data and the connection type from the browser", () => {
const saveData = (connection?: object) => {
vi.stubGlobal("navigator", { connection });
@@ -346,6 +391,7 @@ describe("preview playback store", () => {
const store = createPlaybackStore(env);
const off = store.subscribe(() => {});
expect(listeners.visibilitychange.size).toBe(1);
+ expect(listeners.motion.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);
@@ -366,6 +412,7 @@ describe("preview playback store", () => {
expect(timers.size).toBe(0);
off();
expect(listeners.visibilitychange.size).toBe(0);
+ expect(listeners.motion.size).toBe(0);
});
it("does nothing without IntersectionObserver", () => {