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: the Audio tile plays the Clean up voice demo, noise on and off
Adarsh76be440d46e2
diff --git a/package.json b/package.jsonindex 0e0a7804..625dec1f 100644--- a/package.json+++ b/package.json@@ -18,6 +18,7 @@"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:home-voice": "node tests/e2e/home-voice.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/public/previews/home/voice-quiet-1024.avif b/public/previews/home/voice-quiet-1024.avifnew file mode 100644index 00000000..849573c1Binary files /dev/null and b/public/previews/home/voice-quiet-1024.avif differdiff --git a/public/previews/home/voice-quiet-1024.jpg b/public/previews/home/voice-quiet-1024.jpgnew file mode 100644index 00000000..9266ac9aBinary files /dev/null and b/public/previews/home/voice-quiet-1024.jpg differdiff --git a/public/previews/home/voice-quiet-480.avif b/public/previews/home/voice-quiet-480.avifnew file mode 100644index 00000000..468efa03Binary files /dev/null and b/public/previews/home/voice-quiet-480.avif differdiff --git a/public/previews/home/voice-quiet-768.avif b/public/previews/home/voice-quiet-768.avifnew file mode 100644index 00000000..bdd6d674Binary files /dev/null and b/public/previews/home/voice-quiet-768.avif differdiff --git a/public/previews/home/voice-room-1024.avif b/public/previews/home/voice-room-1024.avifnew file mode 100644index 00000000..6b0b073aBinary files /dev/null and b/public/previews/home/voice-room-1024.avif differdiff --git a/public/previews/home/voice-room-1024.jpg b/public/previews/home/voice-room-1024.jpgnew file mode 100644index 00000000..20706fc7Binary files /dev/null and b/public/previews/home/voice-room-1024.jpg differdiff --git a/public/previews/home/voice-room-480.avif b/public/previews/home/voice-room-480.avifnew file mode 100644index 00000000..4b6e2bacBinary files /dev/null and b/public/previews/home/voice-room-480.avif differdiff --git a/public/previews/home/voice-room-768.avif b/public/previews/home/voice-room-768.avifnew file mode 100644index 00000000..50dcf5e4Binary files /dev/null and b/public/previews/home/voice-room-768.avif differdiff --git a/scripts/gen-home-bento.mjs b/scripts/gen-home-bento.mjsindex 7d26f576..c33ff852 100644--- a/scripts/gen-home-bento.mjs+++ b/scripts/gen-home-bento.mjs@@ -1,8 +1,8 @@#!/usr/bin/env node/*** Media and data for Home's first screen (src/components/home/home-bento.tsx): the video tile's reel of clips and its- * poster, the 3D tile's clip and its poster, each in several widths, AVIF copies of pictures the site already- * publishes, and the Audio tile's waveform, read from the Audio studio's own sample. Nothing is rendered: every file is a+ * poster, the 3D tile's clip and its poster, each in several widths, and AVIF copies of pictures the site already+ * publishes (the Audio tile's two photos among them, from Clean up voice's demo). Nothing is rendered: every file is a* copy of a published picture or of the full-size render a published clip was cut from, so the tiles show exactly what* the studios show, only sharper.*@@ -13,6 +13,9 @@* rotation-{640,1024,1536,2048}.{mp4,avif} the turning gown (the 3D tile) at four widths, and each one's first frame* reel-sand-storm-1024.jpg, rotation-1024.jpg the 1024 px clips' first frames, for a browser without AVIF* image-4-{480,768}.avif the Image studio's example 4+ * voice-{room,quiet}-{480,768,1024}.avif Clean up voice's demo photos (public/samples/clean-voice/): the restaurant,+ * and the same photo softened around her, which the Audio tile shows once the+ * noise is off; voice-{room,quiet}-1024.jpg for a browser without AVIF* genjutsu-<name>-{640,768,1024}.mp4 each clip of the Genjutsu tile's reel (WIPES): a swap shown as it happens, the* original clip and the swapped one under a divider that sweeps across them* genjutsu-couple-{640,768,1024}.avif the reel's first clip's first frame at each width: the tile's poster@@ -22,7 +25,7 @@* board-{photo,film}.webp the Canvas board's photo and a frame of its film, 168 px squares* and src/lib/home-bento.generated.ts: each file's content version, the reel (its clips in order, each one's length and* framing, and where set how long it holds its last frame and fades out), the Genjutsu reel (each clip's labels and- * where its divider is on every frame), each poster's mean colour, and the waveform.+ * where its divider is on every frame), and each poster's mean colour.** The reel: the video tile plays these clips one after another, each once, and crossfades into the next (after the* last, back to the first). Each is a stretch of its preset's full-size render: `from` (its first frame in the render)@@ -47,10 +50,6 @@* Without it those files are kept as they are (and versioned; a reel clip in the widths it has), the posters are made* again from the clips kept, and so is the rest.*- * The waveform: the Clean up voice sample decoded to 8 kHz mono, its loudness (RMS) in WAVE_BARS equal slices, scaled- * so the loudest is 1, with a floor of WAVE_FLOOR so a pause still shows a bar. It is keyed by the sample's own- * version, so a new sample needs a new run (tests/home-bento.test.ts checks it).- ** Run: node scripts/gen-home-bento.mjs make every file and the generated module* node scripts/gen-home-bento.mjs --dry-run make and measure, write nothing* Needs ffmpeg on PATH (or FUOBE_FFMPEG).@@ -71,10 +70,6 @@ const DRY = process.argv.includes("--dry-run");const argAt = process.argv.indexOf("--masters");const MASTERS = argAt > 0 ? process.argv[argAt + 1] : process.env.FUOBE_HOME_MASTERS;-export const WAVE_BARS = 48;-export const WAVE_FLOOR = 0.12;-const WAVE_SOURCE = "/samples/clean-voice/clean.m4a";-/*** The video tile's reel, in the order it plays: each clip's preset, the name of its copies here, the stretch of its* render it plays (`from`, its first frame; `frames`, at CLIP_FPS), where the tile anchors it (its object-position:@@ -206,10 +201,26 @@ const BOARD_THUMBS = [{ name: "board-photo.webp", from: "/examples/effect-pearl-earring/1/in-image.jpg" },{ name: "board-film.webp", from: "/previews/presets/peak/effect-pearl-earring.jpg" },];-/** Each copy: its name under previews/home, the published file it comes from, its width, and a crop where it has one. */+/**+ * The Audio tile's photos (BENTO_VOICE in src/lib/home-bento.ts): Clean up voice's demo photos, in the widths the tile+ * shows them at (up to a 3x phone's full row), and as a JPEG at FALLBACK_WIDTH.+ */+const VOICE = [+ { name: "voice-room", from: "/samples/clean-voice/room.webp" },+ { name: "voice-quiet", from: "/samples/clean-voice/quiet.webp" },+];+const VOICE_WIDTHS = [480, 768, 1024];+/**+ * Each copy: its name under previews/home (an AVIF, or a JPEG where it ends in .jpg), the published file it comes from,+ * its width, and a crop where it has one.+ */const STILLS = [{ name: "image-4-480.avif", from: "/examples/image/4/out.jpg", width: 480 },{ name: "image-4-768.avif", from: "/examples/image/4/out.jpg", width: 768 },+ ...VOICE.flatMap((v) => [+ ...VOICE_WIDTHS.map((width) => ({ name: `${v.name}-${width}.avif`, from: v.from, width })),+ { name: `${v.name}-${FALLBACK_WIDTH}.jpg`, from: v.from, width: FALLBACK_WIDTH },+ ]),];/** AVIF quality: the copies sit under a dark shade, and each tile takes one at least as wide as it shows. */const QUALITY = 55;@@ -282,24 +293,6 @@ function frameAt(file, n) {/** A clip's first frame as a PNG, decoded from the encoded file as a browser shows it. */const firstFrame = (file) => frameAt(file, 0);-/** The sample's loudness in `bars` slices, 0..1, the loudest 1, none under `floor`. */-export function waveform(samples, bars = WAVE_BARS, floor = WAVE_FLOOR) {- const per = Math.floor(samples.length / bars);- const rms = Array.from({ length: bars }, (_, i) => {- let sum = 0;- for (let j = i * per; j < (i + 1) * per; j++) sum += samples[j] * samples[j];- return Math.sqrt(sum / per);- });- const max = Math.max(...rms) || 1;- return rms.map((r) => Math.max(floor, Math.round((r / max) * 1000) / 1000));-}--function readWave() {- const raw = ffmpeg(["-v", "error", "-i", path.join(PUBLIC, WAVE_SOURCE), "-ac", "1", "-ar", "8000", "-f", "s16le", "-"]);- const samples = new Int16Array(raw.buffer, raw.byteOffset, Math.floor(raw.length / 2));- return { wave: waveform(Array.from(samples, (s) => s / 32768)), seconds: samples.length / 8000 };-}-/*** A reel clip as the generated list holds it (and src/lib/home-reel.ts ReelClip reads it): `hold` and `fade` only where set.* @param {{ id: string; name: string; frames: number; position: string; hold?: number; fade?: number }} c@@ -384,7 +377,8 @@ async function main() {...s,make: () => {const img = sharp(path.join(PUBLIC, s.from));- return (s.crop ? img.extract(s.crop) : img).resize(s.width).avif({ quality: QUALITY, effort: 6 }).toBuffer();+ const sized = (s.crop ? img.extract(s.crop) : img).resize(s.width);+ return (s.name.endsWith(".jpg") ? sized.jpeg({ quality: 85, mozjpeg: true }) : sized.avif({ quality: QUALITY, effort: 6 })).toBuffer();},})),...BOARD_THUMBS.map((s) => ({ ...s, make: () => sharp(path.join(PUBLIC, s.from)).resize(THUMB, THUMB, { fit: "cover", position: "attention" }).webp({ quality: 72 }).toBuffer() })),@@ -405,14 +399,12 @@ async function main() {const { channels } = await sharp(path.join(OUT_DIR, `${c.name}-${FALLBACK_WIDTH}.jpg`)).stats();tints[c.name] = `#${channels.slice(0, 3).map((ch) => Math.round(ch.mean).toString(16).padStart(2, "0")).join("")}`;}- const { wave, seconds } = readWave();- console.log(`stills ${(total / 1024).toFixed(1)} KB (clips aside) · waveform ${wave.length} bars over ${seconds.toFixed(2)} s`);+ console.log(`stills ${(total / 1024).toFixed(1)} KB (clips aside)`);if (DRY) return;- const source = contentVersion([path.join(PUBLIC, WAVE_SOURCE)]);const body = `/*** Home's first screen (src/components/home/home-bento.tsx): the content version of each file made for it, the video- * tile's reel, and the Audio tile's waveform, read from the Clean up voice sample (its version is \`wave.source\`). Generated by- * scripts/gen-home-bento.mjs: run it again rather than editing.+ * tile's reel and the Genjutsu tile's, and each poster's mean colour. Generated by scripts/gen-home-bento.mjs: run it+ * again rather than editing.*/export const HOME_BENTO_MEDIA: Record<string, string> = ${JSON.stringify(versions, null, 2)};@@ -442,12 +434,6 @@ export const HOME_BENTO_GENJUTSU = ${JSON.stringify(/** Each poster's mean colour (by its clip's name): the tile shows it until the poster is in. */export const HOME_BENTO_TINT: Record<string, string> = ${JSON.stringify(tints, null, 2)};-export const HOME_BENTO_WAVE = {- src: ${JSON.stringify(WAVE_SOURCE)},- source: ${JSON.stringify(source)},- seconds: ${Math.round(seconds * 100) / 100},- bars: ${JSON.stringify(wave)},-};`;fs.writeFileSync(OUT_TS, body);console.log(`wrote ${path.relative(ROOT, OUT_TS)}`);diff --git a/src/components/audio-tools/clean-voice-demo.tsx b/src/components/audio-tools/clean-voice-demo.tsxindex 8b54eff0..bc605f62 100644--- a/src/components/audio-tools/clean-voice-demo.tsx+++ b/src/components/audio-tools/clean-voice-demo.tsx@@ -1,20 +1,10 @@"use client";import { Pause, Play } from "lucide-react";-import { useCallback, useEffect, useId, useReducer, useRef, useState } from "react";-import {- createDemoAudio,- DEMO_MEDIA,- DEMO_START,- demoReducer,- FLASH_MS,- isRunning,- playLabel,- switchDue,- type DemoAudio,- type DemoState,-} from "@/lib/av/clean-voice-demo";+import { useId } from "react";+import { DEMO_MEDIA, isRunning, playLabel, stateLabel } from "@/lib/av/clean-voice-demo";import { cn } from "@/lib/utils";+import { useCleanVoiceDemo } from "./use-clean-voice-demo";/*** Clean up voice's demo, for anyone who hasn't cleaned a file of their own yet: a photo of a woman talking in a noisy@@ -23,29 +13,6 @@ import { cn } from "@/lib/utils";* softens with the sound. What happens when is decided in src/lib/av/clean-voice-demo.ts.*/-type Win = Window & { webkitAudioContext?: typeof AudioContext };-type Nav = Navigator & { audioSession?: { type: string } };--/** A clip that hasn't arrived by then counts as not loaded (the button offers to try again). */-const FETCH_TIMEOUT_MS = 15_000;--const decode = (ctx: AudioContext, bytes: ArrayBuffer) => new Promise<AudioBuffer>((ok, no) => ctx.decodeAudioData(bytes, ok, no));--/** iPhone: play like a video does, with the ringer switch on silent too (asked before the sound starts). */-function playThroughSilentSwitch() {- try {- const session = (navigator as Nav).audioSession;- if (session) session.type = "playback";- } catch {}-}--async function fetchBytes(url: string): Promise<ArrayBuffer> {- const signal = typeof AbortSignal.timeout === "function" ? AbortSignal.timeout(FETCH_TIMEOUT_MS) : undefined;- const r = await fetch(url, { signal });- if (!r.ok) throw new Error(`${url}: ${r.status}`);- return r.arrayBuffer();-}-export function CleanVoiceDemo({name = "Clean up voice",ready = true,@@ -56,158 +23,9 @@ export function CleanVoiceDemo({ready?: boolean;className?: string;}) {- const [state, dispatch] = useReducer(demoReducer, DEMO_START);- // The last automatic switch whose "Noise removed" has gone again.- const [shown, setShown] = useState(0);- const toast = state.flash > shown;+ // The demo's sound (use-clean-voice-demo.ts, shared with Home's Audio tile): its clips are fetched as soon as it shows.+ const { state, toast, tap, choose, barRef } = useCleanVoiceDemo({ prefetch: ready });const headingId = useId();- const stateRef = useRef<DemoState>(state);- const ctxRef = useRef<AudioContext | null>(null);- const bytesRef = useRef<Promise<ArrayBuffer[]> | null>(null);- const audioRef = useRef<DemoAudio | null>(null);- const barRef = useRef<HTMLElement>(null);-- useEffect(() => {- stateRef.current = state;- }, [state]);-- /** Both clips' bytes, fetched once (again after a failure). */- const bytes = useCallback(() => {- bytesRef.current ??= Promise.all([fetchBytes(DEMO_MEDIA.noisy), fetchBytes(DEMO_MEDIA.clean)]).catch((e) => {- bytesRef.current = null;- throw e;- });- return bytesRef.current;- }, []);-- // Fetch the clips as soon as the demo shows, so the first tap plays at once.- useEffect(() => {- if (ready) bytes().catch(() => {});- }, [ready, bytes]);-- /** The AudioContext, made and resumed inside the tap (a phone only lets a tap start sound). */- const context = () => {- if (!ctxRef.current) {- const AC = window.AudioContext ?? (window as Win).webkitAudioContext;- if (!AC) return null;- playThroughSilentSwitch();- let ctx: AudioContext;- try {- ctx = new AC();- } catch {- return null;- }- // A call, the lock screen or another app can stop the sound: show it as paused, so one tap resumes it.- ctx.onstatechange = () => {- if (ctx.state !== "running") dispatch({ type: "interrupted" });- };- ctxRef.current = ctx;- }- ctxRef.current.resume().catch(() => {});- return ctxRef.current;- };-- // A new run: both clips from the top, at the gains of the mode it starts in.- useEffect(() => {- // Only a start asks for one (the page coming back into view runs this again with nothing to start).- if (!state.run || stateRef.current.phase !== "loading") return;- let cancelled = false;- (async () => {- const ctx = ctxRef.current;- if (!ctx) throw new Error("No sound");- if (!audioRef.current) {- const raw = await bytes();- // decodeAudioData takes its buffer over: decode copies, so a later decode still has the bytes.- const buffers = await Promise.all(raw.map((b) => decode(ctx, b.slice(0))));- if (cancelled || ctxRef.current !== ctx) return;- audioRef.current = createDemoAudio(ctx, buffers);- }- if (cancelled) return;- audioRef.current.start(stateRef.current.clean, () => dispatch({ type: "ended" }));- dispatch({ type: "started" });- })().catch(() => {- if (!cancelled) dispatch({ type: "failed" });- });- return () => {- cancelled = true;- };- }, [state.run, bytes]);-- // A switch: both gains ramp at once, so the voice carries on where it was.- useEffect(() => {- audioRef.current?.switchTo(state.clean, state.ramp);- }, [state.clean, state.ramp]);-- // The progress line and the automatic switch follow the clips' own clock (it stops while paused).- useEffect(() => {- if (state.phase !== "playing") {- if (barRef.current && state.phase !== "paused") barRef.current.style.width = state.phase === "done" ? "100%" : "0%";- return;- }- let raf = 0;- const step = () => {- const audio = audioRef.current;- if (!audio) return;- const t = audio.elapsed();- if (barRef.current) barRef.current.style.width = `${Math.min(100, (t / audio.length) * 100)}%`;- if (switchDue(stateRef.current, t)) dispatch({ type: "time", t });- raf = requestAnimationFrame(step);- };- raf = requestAnimationFrame(step);- return () => cancelAnimationFrame(raf);- }, [state.phase]);-- // "Noise removed", for a moment, when the noise goes by itself.- useEffect(() => {- if (!state.flash) return;- const flash = state.flash;- const t = setTimeout(() => setShown(flash), FLASH_MS);- return () => clearTimeout(t);- }, [state.flash]);-- // A hidden tab pauses the demo (a phone would otherwise keep playing it in the background).- useEffect(() => {- const onHide = () => {- if (!document.hidden || stateRef.current.phase !== "playing") return;- ctxRef.current?.suspend().catch(() => {});- dispatch({ type: "interrupted" });- };- document.addEventListener("visibilitychange", onHide);- return () => document.removeEventListener("visibilitychange", onHide);- }, []);-- // Leaving the page (or the page being kept aside for a quick way back) stops the sound and starts the demo over.- useEffect(- () => () => {- audioRef.current?.stop();- audioRef.current = null;- const ctx = ctxRef.current;- ctxRef.current = null;- if (ctx) {- ctx.onstatechange = null;- ctx.close().catch(() => {});- }- setShown(stateRef.current.flash);- dispatch({ type: "reset" });- },- [],- );-- const tap = () => {- const s = stateRef.current;- if (s.phase === "loading") return;- const ctx = ctxRef.current;- // Stopped from outside while it looked like it was playing: this tap brings the sound back.- if (s.phase === "playing" && ctx && ctx.state !== "running") return void ctx.resume().catch(() => {});- if (s.phase === "playing") ctx?.suspend().catch(() => {});- else if (s.phase === "paused") ctx?.resume().catch(() => {});- else if (!context()) return void dispatch({ type: "failed", unsupported: true });- dispatch({ type: "tap" });- };- const choose = (clean: boolean) => {- if (!isRunning(stateRef.current) && !context()) return void dispatch({ type: "failed", unsupported: true });- dispatch({ type: "choose", clean });- };const playing = state.phase === "playing";const moving = isRunning(state) || state.phase === "done";@@ -267,7 +85,7 @@ export function CleanVoiceDemo({aria-live="polite"><span className={cn("size-2 rounded-full motion-reduce:animate-none", state.clean ? "bg-[#7ee2b8]" : "bg-[#ffb347]", playing && !state.clean && "animate-live-dot")} />- <span data-demo-state>{state.clean ? "Voice only" : "Noisy restaurant"}</span>+ <span data-demo-state>{stateLabel(state.clean)}</span></span><spandiff --git a/src/components/audio-tools/use-clean-voice-demo.ts b/src/components/audio-tools/use-clean-voice-demo.tsnew file mode 100644index 00000000..8ff5a0f0--- /dev/null+++ b/src/components/audio-tools/use-clean-voice-demo.ts@@ -0,0 +1,262 @@+"use client";++import { useCallback, useEffect, useId, useReducer, useRef, useState, type RefObject } from "react";+import {+ createDemoAudio,+ DEMO_MEDIA,+ DEMO_START,+ demoReducer,+ FLASH_MS,+ isRunning,+ switchDue,+ type DemoAudio,+ type DemoState,+} from "@/lib/av/clean-voice-demo";+import { claimSound, onOtherSound } from "@/lib/av/one-sound";++/**+ * The Clean up voice demo's sound, shared by the studio's demo (clean-voice-demo.tsx) and Home's Audio tile+ * (home/bento-voice.tsx): both takes (the room as recorded, her voice alone) start together through Web Audio, one+ * AudioContext with a gain each, so a switch happens at the same moment in her speech. What happens when is decided in+ * src/lib/av/clean-voice-demo.ts; this hook plays it. The context is made and resumed inside the visitor's tap (a phone+ * only lets a tap start sound), so nothing ever plays by itself.+ *+ * It keeps to one sound on the page (src/lib/av/one-sound.ts), and pauses when the tab is hidden, when the sound stops+ * from outside (a call, the lock screen) and, given `view`, when its box leaves the screen: shown as paused, one tap+ * resumes it.+ */++type Win = Window & { webkitAudioContext?: typeof AudioContext };+type Nav = Navigator & { audioSession?: { type: string } };++/** A clip that hasn't arrived by then counts as not loaded (the button offers to try again). */+const FETCH_TIMEOUT_MS = 15_000;+/** With `view`: under this share of the box on screen, the sound pauses. */+export const VIEW_SHARE = 0.25;++const decode = (ctx: AudioContext, bytes: ArrayBuffer) => new Promise<AudioBuffer>((ok, no) => ctx.decodeAudioData(bytes, ok, no));++/** iPhone: play like a video does, with the ringer switch on silent too (asked before the sound starts). */+function playThroughSilentSwitch() {+ try {+ const session = (navigator as Nav).audioSession;+ if (session) session.type = "playback";+ } catch {}+}++async function fetchBytes(url: string): Promise<ArrayBuffer> {+ const signal = typeof AbortSignal.timeout === "function" ? AbortSignal.timeout(FETCH_TIMEOUT_MS) : undefined;+ const r = await fetch(url, { signal });+ if (!r.ok) throw new Error(`${url}: ${r.status}`);+ return r.arrayBuffer();+}++export interface CleanVoiceDemoOptions {+ /**+ * Fetch both clips as soon as this is true, so the first tap plays at once (the studio, where the demo is the page).+ * Left out, nothing is fetched until the first tap (Home, where most visitors never play it).+ */+ prefetch?: boolean;+ /** The demo's box: once less than VIEW_SHARE of it is on screen, the sound pauses. */+ view?: RefObject<Element | null>;+}++export interface CleanVoiceDemoPlayer {+ state: DemoState;+ /** "Noise removed" is showing: the noise has just gone by itself. */+ toast: boolean;+ /** The play button (and the photo): play, pause, resume or play again. */+ tap(): void;+ /** Noise on (false) or Noise off (true): switches at once while it plays, or starts it in that mode. */+ choose(clean: boolean): void;+ /** The progress line: its width follows the clips' clock. */+ barRef: RefObject<HTMLElement | null>;+}++export function useCleanVoiceDemo({ prefetch = false, view }: CleanVoiceDemoOptions = {}): CleanVoiceDemoPlayer {+ const [state, dispatch] = useReducer(demoReducer, DEMO_START);+ // The last automatic switch whose "Noise removed" has gone again.+ const [shown, setShown] = useState(0);+ const id = useId();+ const stateRef = useRef<DemoState>(state);+ const ctxRef = useRef<AudioContext | null>(null);+ const bytesRef = useRef<Promise<ArrayBuffer[]> | null>(null);+ const audioRef = useRef<DemoAudio | null>(null);+ const barRef = useRef<HTMLElement>(null);++ useEffect(() => {+ stateRef.current = state;+ }, [state]);++ /** Both clips' bytes, fetched once (again after a failure). */+ const bytes = useCallback(() => {+ bytesRef.current ??= Promise.all([fetchBytes(DEMO_MEDIA.noisy), fetchBytes(DEMO_MEDIA.clean)]).catch((e) => {+ bytesRef.current = null;+ throw e;+ });+ return bytesRef.current;+ }, []);++ useEffect(() => {+ if (prefetch) bytes().catch(() => {});+ }, [prefetch, bytes]);++ /** The AudioContext, made and resumed inside the tap (a phone only lets a tap start sound). */+ const context = () => {+ if (!ctxRef.current) {+ const AC = window.AudioContext ?? (window as Win).webkitAudioContext;+ if (!AC) return null;+ playThroughSilentSwitch();+ let ctx: AudioContext;+ try {+ ctx = new AC();+ } catch {+ return null;+ }+ // A call, the lock screen or another app can stop the sound: show it as paused, so one tap resumes it.+ ctx.onstatechange = () => {+ if (ctx.state !== "running") dispatch({ type: "interrupted" });+ };+ ctxRef.current = ctx;+ }+ ctxRef.current.resume().catch(() => {});+ return ctxRef.current;+ };++ /** Pauses the sound from outside (the tab hidden, the box off screen, another sound): one tap resumes it. */+ const pause = useCallback(() => {+ if (stateRef.current.phase !== "playing") return;+ ctxRef.current?.suspend().catch(() => {});+ dispatch({ type: "interrupted" });+ }, []);++ // A new run: both clips from the top, at the gains of the mode it starts in.+ useEffect(() => {+ // Only a start asks for one (the page coming back into view runs this again with nothing to start).+ if (!state.run || stateRef.current.phase !== "loading") return;+ let cancelled = false;+ (async () => {+ const ctx = ctxRef.current;+ if (!ctx) throw new Error("No sound");+ if (!audioRef.current) {+ const raw = await bytes();+ // decodeAudioData takes its buffer over: decode copies, so a later decode still has the bytes.+ const buffers = await Promise.all(raw.map((b) => decode(ctx, b.slice(0))));+ if (cancelled || ctxRef.current !== ctx) return;+ audioRef.current = createDemoAudio(ctx, buffers);+ }+ if (cancelled) return;+ audioRef.current.start(stateRef.current.clean, () => dispatch({ type: "ended" }));+ dispatch({ type: "started" });+ })().catch(() => {+ if (!cancelled) dispatch({ type: "failed" });+ });+ return () => {+ cancelled = true;+ };+ }, [state.run, bytes]);++ // A switch: both gains ramp at once, so the voice carries on where it was.+ useEffect(() => {+ audioRef.current?.switchTo(state.clean, state.ramp);+ }, [state.clean, state.ramp]);++ // The progress line and the automatic switch follow the clips' own clock (it stops while paused).+ useEffect(() => {+ if (state.phase !== "playing") {+ if (barRef.current && state.phase !== "paused") barRef.current.style.width = state.phase === "done" ? "100%" : "0%";+ return;+ }+ let raf = 0;+ const step = () => {+ const audio = audioRef.current;+ if (!audio) return;+ const t = audio.elapsed();+ if (barRef.current) barRef.current.style.width = `${Math.min(100, (t / audio.length) * 100)}%`;+ if (switchDue(stateRef.current, t)) dispatch({ type: "time", t });+ raf = requestAnimationFrame(step);+ };+ raf = requestAnimationFrame(step);+ return () => cancelAnimationFrame(raf);+ }, [state.phase]);++ // "Noise removed", for a moment, when the noise goes by itself.+ useEffect(() => {+ if (!state.flash) return;+ const flash = state.flash;+ const t = setTimeout(() => setShown(flash), FLASH_MS);+ return () => clearTimeout(t);+ }, [state.flash]);++ // One sound on the page: playing, it stops every other, and pauses when another starts.+ useEffect(() => {+ if (state.phase !== "playing") return;+ claimSound(id, document, window);+ return onOtherSound(id, pause, document, window);+ }, [state.phase, id, pause]);++ // A hidden tab pauses the demo (a phone would otherwise keep playing it in the background).+ useEffect(() => {+ const onHide = () => {+ if (document.hidden) pause();+ };+ document.addEventListener("visibilitychange", onHide);+ return () => document.removeEventListener("visibilitychange", onHide);+ }, [pause]);++ // Its box leaving the screen pauses it too (while it plays: nothing is watched before then).+ const playing = state.phase === "playing";+ useEffect(() => {+ const el = view?.current;+ if (!playing || !el || typeof IntersectionObserver === "undefined") return;+ const io = new IntersectionObserver(+ ([e]) => {+ if (!e.isIntersecting || e.intersectionRatio < VIEW_SHARE) pause();+ },+ { threshold: [0, VIEW_SHARE] },+ );+ io.observe(el);+ return () => io.disconnect();+ }, [playing, view, pause]);++ // Leaving the page (or the page being kept aside for a quick way back) stops the sound and starts the demo over.+ useEffect(+ () => () => {+ audioRef.current?.stop();+ audioRef.current = null;+ const ctx = ctxRef.current;+ ctxRef.current = null;+ if (ctx) {+ ctx.onstatechange = null;+ ctx.close().catch(() => {});+ }+ setShown(stateRef.current.flash);+ dispatch({ type: "reset" });+ },+ [],+ );++ const tap = () => {+ const s = stateRef.current;+ if (s.phase === "loading") return;+ const ctx = ctxRef.current;+ // Stopped from outside while it looked like it was playing: this tap brings the sound back.+ if (s.phase === "playing" && ctx && ctx.state !== "running") return void ctx.resume().catch(() => {});+ if (s.phase === "playing") ctx?.suspend().catch(() => {});+ else if (s.phase === "paused") ctx?.resume().catch(() => {});+ else if (!context()) return void dispatch({ type: "failed", unsupported: true });+ dispatch({ type: "tap" });+ };+ const choose = (clean: boolean) => {+ const s = stateRef.current;+ if (!isRunning(s) && !context()) return void dispatch({ type: "failed", unsupported: true });+ // Paused (from outside, or by a tap): a choice switches and plays on from there.+ if (s.phase === "paused") {+ ctxRef.current?.resume().catch(() => {});+ dispatch({ type: "tap" });+ }+ dispatch({ type: "choose", clean });+ };++ return { state, toast: state.flash > shown, tap, choose, barRef };+}diff --git a/src/components/home/bento-voice.tsx b/src/components/home/bento-voice.tsxnew file mode 100644index 00000000..aa27a095--- /dev/null+++ b/src/components/home/bento-voice.tsx@@ -0,0 +1,121 @@+"use client";++import { ArrowRight, Loader2, Pause, Play, RotateCcw, Volume2 } from "lucide-react";+import { useRef, useState } from "react";+import { useCleanVoiceDemo } from "@/components/audio-tools/use-clean-voice-demo";+import { IntentLink } from "@/components/intent-link";+import { isRunning, stateLabel, type DemoState } from "@/lib/av/clean-voice-demo";+import type { BentoTile } from "@/lib/home-bento";+import { cn } from "@/lib/utils";+import { s } from "./home-bento-classes";++/** The play button's words and icon in the tile, for each moment of the demo. */+export function voiceButton(st: DemoState): { label: string; Icon: typeof Play; spin?: boolean } {+ switch (st.phase) {+ case "loading":+ return { label: "Loading…", Icon: Loader2, spin: true };+ case "playing":+ return { label: "Pause", Icon: Pause };+ case "paused":+ return { label: "Resume", Icon: Play };+ case "done":+ return { label: "Play again", Icon: RotateCcw };+ case "failed":+ return { label: "Try again", Icon: RotateCcw };+ default:+ return { label: "Tap to listen", Icon: Volume2 };+ }+}++/**+ * Home's Audio tile: Clean up voice's own demo, to hear on the spot. A woman talks in a noisy restaurant; one tap plays+ * the room as recorded, and a few seconds in the noise goes by itself while she keeps talking (the photo softens with+ * it). Noise on / Noise off switch between the two takes at the same moment in her speech. The sound is the studio's+ * own (use-clean-voice-demo.ts): nothing plays or downloads until the first tap, one sound plays on the page at a time,+ * and it pauses when the tile leaves the screen or the tab is hidden.+ *+ * Unlike the other tiles the whole tile isn't a link, as it holds the demo's buttons: its words are the link to the+ * studio, and a tap on the photo plays or pauses. `room`: the restaurant photo (from the server, on the first paint);+ * `quiet`: the same photo softened around her, added once the visitor reaches for the tile.+ */+export function BentoVoice({ tile, area, room, quiet }: { tile: BentoTile; area: string; room: React.ReactNode; quiet: React.ReactNode }) {+ const box = useRef<HTMLDivElement>(null);+ const { state, tap, choose, barRef } = useCleanVoiceDemo({ view: box });+ // The softened photo is asked for once the visitor reaches for the tile (a pointer over it, a touch, the keyboard).+ const [armed, setArmed] = useState(false);+ const arm = () => setArmed(true);+ const playing = state.phase === "playing";+ const button = voiceButton(state);+ return (+ <div+ ref={box}+ role="group"+ aria-label="Clean up voice: a woman talking in a noisy restaurant"+ data-tile={tile.key}+ data-phase={state.phase}+ data-clean={state.clean || undefined}+ className={cn(s.tile, area, s.voice)}+ onPointerEnter={arm}+ onTouchStart={arm}+ onFocus={arm}+ // The photo plays and pauses too (its buttons and its link do their own).+ onClick={(e) => {+ if (!(e.target as Element).closest("a, button")) tap();+ }}+ >+ <span aria-hidden className={cn(s.voicePics, (isRunning(state) || state.phase === "done") && s.voiceNear)}>+ {room}+ <span className={s.voiceQuiet} data-on={state.clean || undefined}>+ {(armed || state.run > 0) && quiet}+ </span>+ </span>+ <span aria-hidden className={s.shade} />++ <div className={s.voiceUi}>+ <span className={s.voiceChip} aria-live="polite">+ <i aria-hidden className={s.voiceDot} data-live={(playing && !state.clean) || undefined} />+ <span data-demo-state>{stateLabel(state.clean)}</span>+ </span>++ <span role="group" aria-label="Noise" className={s.voiceSwitch}>+ {[+ { clean: false, label: "Noise on" },+ { clean: true, label: "Noise off" },+ ].map((o) => (+ <button key={o.label} type="button" aria-pressed={state.clean === o.clean} onClick={() => choose(o.clean)}>+ <span>{o.label}</span>+ </button>+ ))}+ </span>++ <button type="button" className={s.voicePlay} onClick={tap} aria-busy={state.phase === "loading" || undefined}>+ <button.Icon aria-hidden className={cn("size-4 shrink-0", button.spin && "animate-spin motion-reduce:animate-none", playing && "fill-current")} />+ <span>{button.label}</span>+ </button>++ <IntentLink href={tile.href} aria-label={tile.label} className={s.voiceLink}>+ <span aria-hidden className={s.voiceCopy}>+ <span className={s.meta}>{tile.meta}</span>+ <span className={s.title}>+ {/* "Studio-clean" stays whole when the title wraps. */}+ {tile.title.split(" ").map((w, i) => (+ <span key={i}>+ {i > 0 && " "}+ {w.includes("-") ? <span className="whitespace-nowrap">{w}</span> : w}+ </span>+ ))}+ <ArrowRight className={s.voiceGo} />+ </span>+ <span className={s.cta}>+ {tile.cta} <ArrowRight className="size-3.5" />+ </span>+ </span>+ </IntentLink>+ </div>++ <span aria-hidden className={s.voiceBar}>+ <i ref={barRef} />+ </span>+ </div>+ );+}diff --git a/src/components/home/home-bento-classes.ts b/src/components/home/home-bento-classes.tsindex 34b752de..60254393 100644--- a/src/components/home/home-bento-classes.ts+++ b/src/components/home/home-bento-classes.ts@@ -3,6 +3,6 @@* stylesheet in this app is (next.config.ts runs each .css file through Tailwind as plain CSS), so the prefix keeps its* names to itself.*/-const NAMES = ["accent","aside","audio","badge","bento","big","board","box","canvas","caret","clip","copy","corner","cta","edges","end","figures","fill","filmMark","foot","frame","genjutsu","grid","h1","head","image","kenburns","l2b","line1","line2","live","meta","node","nodeLabel","numbers","numbersFoot","numbersLine","out","pic","pill","playhead","progress","shade","step","three","tile","title","tsx","typed","video","wave","wipe","wipeAfter","wipeBefore"] as const;+const NAMES = ["accent","aside","audio","badge","bento","big","board","box","canvas","caret","clip","copy","corner","cta","edges","end","figures","fill","filmMark","foot","frame","genjutsu","grid","h1","head","image","kenburns","l2b","line1","line2","live","meta","node","nodeLabel","numbers","numbersFoot","numbersLine","out","pic","pill","progress","shade","step","three","tile","title","tsx","typed","video","voice","voiceBar","voiceChip","voiceCopy","voiceDot","voiceGo","voiceLink","voiceNear","voicePics","voicePlay","voiceQuiet","voiceSwitch","voiceUi","wipe","wipeAfter","wipeBefore"] as const;export const s = Object.fromEntries(NAMES.map((n) => [n, `hb-${n.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase())}`])) as Record<(typeof NAMES)[number], string>;diff --git a/src/components/home/home-bento.css b/src/components/home/home-bento.cssindex 49048808..c9e5b5d0 100644--- a/src/components/home/home-bento.css+++ b/src/components/home/home-bento.css@@ -228,6 +228,7 @@* The reel leads; Live edit, the highlight, and Genjutsu, whose swaps need room to be seen, are the next biggest, the* same size, right by it (right under it on a phone). From lg the grid is fourteen narrow columns, so the top two rows* (the reel, Live edit, Genjutsu) and the bottom row (image, 3D, audio, the numbers, canvas) each split it their own way.+ * The audio tile, which holds a demo to play, takes four of the bottom row's columns.*/.hb-grid {display: grid;@@ -258,8 +259,9 @@.hb-three {aspect-ratio: 1;}+ /* The demo: room for its switch over the photo and its words under her; a little smaller than Genjutsu. */.hb-audio {- aspect-ratio: 5 / 2;+ aspect-ratio: 5 / 3;}.hb-canvas {aspect-ratio: 16 / 9;@@ -286,7 +288,7 @@grid-template-areas:"video video video video video video live live live live genjutsu genjutsu genjutsu genjutsu""video video video video video video live live live live genjutsu genjutsu genjutsu genjutsu"- "image image three three audio audio audio numbers numbers numbers canvas canvas canvas canvas";+ "image image three three audio audio audio audio numbers numbers numbers canvas canvas canvas";}}.hb-video {@@ -601,101 +603,355 @@}}-/* ---------------------------------------------------------------- audio: the sample's own loudness */+/* ---------------------------------------------------------------- audio: Clean up voice's demo, to hear */-.hb-audio {- background:- radial-gradient(ellipse 85% 60% at 50% 32%, var(--bento-glow), transparent 72%),- var(--media);+/*+ * The tile holds the demo (bento-voice.tsx): the restaurant photo, and over it a layer laid out as a grid, so each part+ * keeps to its own corner whatever size the tile is: the chip saying what is heard (top left), the Noise on / Noise off+ * switch (top right), the tile's words, which are the link to the studio (bottom left), and the play button (bottom+ * right), which keeps one width whatever it says. On a narrow tile (a tablet's column, 1024 px screens) the button goes+ * top right, its icon alone, and the switch over the words, clear of her face. Every part sits in the tile's own box,+ * so nothing moves the grid.+ */+.hb-voice {+ cursor: pointer;+ touch-action: manipulation;}-.hb-wave {+/* Her face sits about a third down the photo, in the middle: a tile wider than the photo keeps it in view. */+.hb-voice-pics {position: absolute;- left: 14px;- right: 14px;- top: 14%;- height: 40%;- display: flex;- align-items: center;- gap: 2px;+ inset: 0;+ transform-origin: 50% 32%;+ transition: transform 9s cubic-bezier(0.2, 0.6, 0.3, 1);}-@container (min-width: 220px) {- .hb-wave {- left: 18px;- right: 18px;- top: 12%;- }+.hb-voice-pics .hb-fill {+ object-position: 50% 28%;}-.hb-wave > i {- flex: 1 1 0;- min-width: 1px;- height: calc(var(--h) * 100%);- border-radius: 2px;- background: var(--bento-accent);- opacity: 0.7;+/* While it plays, the photo draws in a little, as the studio's demo does. */+.hb-voice-near {+ transform: scale(1.045);}-.dark .hb-wave > i {- background: color-mix(in oklch, var(--bento-accent) 70%, white);+/* The same photo softened around her: it shows while the noise is off. */+.hb-voice-quiet {+ position: absolute;+ inset: 0;+ opacity: 0;+ transition: opacity 1s ease-in-out;}-.hb-bento[data-play] .hb-wave > i {- opacity: 0.45;- animation: bento-bar var(--wave-s, 8s) linear infinite;- animation-delay: var(--d);- animation-play-state: paused;+.hb-voice-quiet[data-on] {+ opacity: 1;}-.hb-bento[data-play="1"] .hb-wave > i {- animation-play-state: running;+.hb-voice .hb-shade {+ height: 70%;}-@keyframes bento-bar {- 0% {- opacity: 1;- transform: scaleY(1.06);- }- 3% {- opacity: 1;- transform: scaleY(0.94);++.hb-voice-ui {+ position: absolute;+ inset: 0;+ z-index: 1;+ display: grid;+ grid-template-columns: minmax(0, 1fr) auto;+ grid-template-rows: auto minmax(0, 1fr) auto;+ grid-template-areas:+ "chip switch"+ ". ."+ "copy play";+ gap: 8px;+ padding: 10px 10px 12px;+}++.hb-voice-chip,+.hb-voice-switch {+ display: inline-flex;+ align-items: center;+ align-self: start;+ border-radius: 999px;+ background: rgb(10 8 6 / 62%);+ -webkit-backdrop-filter: blur(10px);+ backdrop-filter: blur(10px);+}+.hb-voice-chip {+ grid-area: chip;+ justify-self: start;+ gap: 7px;+ height: 28px;+ padding: 0 11px 0 9px;+ font-size: 12px;+ font-weight: 500;+ white-space: nowrap;+ pointer-events: none;+}+.hb-voice-dot {+ flex: none;+ width: 8px;+ height: 8px;+ border-radius: 999px;+ background: #ffb347;+}+.hb-voice[data-clean] .hb-voice-dot {+ background: #7ee2b8;+}+.hb-voice-dot[data-live] {+ animation: hb-voice-pulse 1.1s ease-out infinite;+}+@keyframes hb-voice-pulse {+ from {+ box-shadow: 0 0 0 0 rgb(255 179 71 / 60%);}- 7% {- opacity: 1;- transform: scaleY(1.04);+ to {+ box-shadow: 0 0 0 7px rgb(255 179 71 / 0%);}- 14%,- 100% {- opacity: 0.45;- transform: scaleY(1);+}++/* The switch: each half a button as tall as the switch, the pressed one a white pill inside it. */+.hb-voice-switch {+ grid-area: switch;+ justify-self: end;+ padding: 0 2px;+}+.hb-voice-switch > button {+ min-height: 28px;+ padding: 2px 1px;+ border: 0;+ border-radius: 999px;+ background: none;+ color: rgb(255 255 255 / 78%);+ font: inherit;+ font-size: 12px;+ font-weight: 500;+ line-height: 1;+ white-space: nowrap;+ cursor: pointer;+ touch-action: manipulation;+ outline: none;+}+.hb-voice-switch > button > span {+ display: block;+ padding: 6px 10px;+ border-radius: 999px;+ transition:+ background-color 0.25s ease,+ color 0.25s ease;+}+.hb-voice-switch > button:hover {+ color: #fff;+}+.hb-voice-switch > button[aria-pressed="true"] > span {+ background: #fff;+ color: #141210;+}+.hb-voice-switch > button:focus-visible > span {+ outline: 2px solid #fff;+ outline-offset: 1px;+}++/* The play button: one width whatever it says (Tap to listen, Loading…, Pause, Resume, Play again). */+.hb-voice-play {+ grid-area: play;+ align-self: end;+ justify-self: end;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 7px;+ width: 132px;+ height: 34px;+ margin: 0 2px 0 0;+ padding: 0 12px;+ border: 0;+ border-radius: 999px;+ background: rgb(255 255 255 / 94%);+ color: #141210;+ font: inherit;+ font-size: 13px;+ font-weight: 600;+ line-height: 1;+ white-space: nowrap;+ cursor: pointer;+ touch-action: manipulation;+ box-shadow: 0 8px 24px rgb(0 0 0 / 35%);+ outline: none;+ transition:+ background-color 0.2s ease,+ transform 0.2s ease;+}+.hb-voice-play:hover {+ background: #fff;+}+.hb-voice-play:active {+ transform: scale(0.97);+}+.hb-voice-play:focus-visible {+ outline: 2px solid #fff;+ outline-offset: 3px;+}++/* The tile's words, the link to the studio. */+.hb-voice-link {+ grid-area: copy;+ align-self: end;+ min-width: 0;+ margin: 0 0 0 4px;+ color: inherit;+ text-decoration: none;+ outline: none;+ -webkit-tap-highlight-color: transparent;+}+.hb-voice-copy {+ display: block;+ text-shadow: 0 1px 2px rgb(0 0 0 / 35%);+}+/* The small line keeps to one line: it may run on over the play button's column, above the button. */+.hb-voice .hb-meta {+ white-space: nowrap;+}+/* The link's words only where they fit on one line beside the button (a phone's full row); elsewhere the arrow. */+@container (max-width: 339.98px) {+ .hb-voice .hb-cta {+ display: none;}}-.hb-playhead {+/* The link's focus shows as every tile's does: the ring round the tile. */+.hb-voice:has(.hb-voice-link:focus-visible) {+ box-shadow:+ 0 0 0 2px var(--background),+ 0 0 0 4px var(--ring);+}+.hb-voice-link:hover .hb-cta,+.hb-voice-link:focus-visible .hb-cta {+ color: #fff;+}+.hb-voice-link:hover .hb-cta svg,+.hb-voice-link:focus-visible .hb-cta svg {+ transform: translateX(2px);+}+/* Where the tile has no room for the link's own words (a short or narrow tile), an arrow after the title says it opens. */+.hb-voice-go {+ display: inline-block;+ width: 0.8em;+ height: 0.8em;+ margin-left: 0.25em;+ vertical-align: -0.06em;+ transition: transform 0.2s ease;+}+.hb-voice-link:hover .hb-voice-go,+.hb-voice-link:focus-visible .hb-voice-go {+ transform: translateX(2px);+}++/* The line along the bottom follows the clips (its width set as they play). */+.hb-voice-bar {position: absolute;- inset: -8% 0;+ inset: auto 0 0;+ z-index: 2;+ height: 3px;+ background: rgb(255 255 255 / 14%);pointer-events: none;- transform: translateX(-100%);- opacity: 0;}-.hb-playhead::after {- content: "";- position: absolute;- top: 0;- bottom: 0;- right: 0;- width: 2px;- border-radius: 2px;+.hb-voice-bar > i {+ display: block;+ width: 0;+ height: 100%;background: #fff;- box-shadow: 0 0 10px var(--bento-glow);}-.hb-bento[data-play] .hb-playhead {- opacity: 1;- animation: bento-sweep var(--wave-s, 8s) linear infinite;- animation-play-state: paused;++@container (min-width: 220px) {+ .hb-voice-ui {+ padding-bottom: 16px;+ }+ .hb-voice-link {+ margin-left: 8px;+ }}-.hb-bento[data-play="1"] .hb-playhead {- animation-play-state: running;+@container (min-width: 340px) {+ .hb-voice-go {+ display: none;+ }}-@keyframes bento-sweep {- from {- transform: translateX(-100%);+@container (min-width: 460px) {+ .hb-voice-ui {+ padding: 14px 14px 18px;}- to {- transform: translateX(0);+ .hb-voice-link {+ margin-left: 12px;+ }+}+/* (Height is measured from lg, where the grid fixes every tile's box: the bottom row is short up to 1080 px screens.) */+@container (max-height: 200px) {+ .hb-voice .hb-cta {+ display: none;+ }+ .hb-voice-go {+ display: inline-block;+ }+}+/*+ * A narrow tile: the chip and the play button (its icon alone; its words stay its name) on top, the switch over the+ * title, and no small line or link words (the arrow after the title).+ */+@container (max-width: 299.98px) {+ .hb-voice-ui {+ grid-template-rows: auto minmax(0, 1fr) auto auto;+ grid-template-areas:+ "chip play"+ ". ."+ "switch switch"+ "copy copy";+ }+ .hb-voice-switch {+ justify-self: start;+ }+ .hb-voice-play {+ align-self: start;+ width: 34px;+ padding: 0;+ }+ .hb-voice-play > span {+ position: absolute;+ width: 1px;+ height: 1px;+ overflow: hidden;+ clip-path: inset(50%);+ white-space: nowrap;+ }+ .hb-voice .hb-meta {+ display: none;+ }+}+/* A phone or a tablet: every button at least 44 px to tap. */+@media (pointer: coarse) {+ .hb-voice-switch > button {+ min-height: 44px;+ padding: 4px 1px;+ }+ .hb-voice-switch > button > span {+ padding: 9px 12px;+ font-size: 13px;+ }+ .hb-voice-play {+ width: 148px;+ height: 44px;+ font-size: 14px;+ }+ @container (max-width: 299.98px) {+ .hb-voice-play {+ width: 44px;+ }+ }+}+@media (prefers-reduced-motion: reduce) {+ .hb-voice-pics,+ .hb-voice-quiet,+ .hb-voice-switch > button > span,+ .hb-voice-play,+ .hb-voice-go {+ transition: none;+ }+ .hb-voice-near {+ transform: none;+ }+ .hb-voice-dot[data-live] {+ animation: none;}}@@ -1167,8 +1423,6 @@transform: none;}.hb-bento .hb-kenburns,- .hb-bento .hb-wave > i,- .hb-bento .hb-playhead,.hb-bento .hb-caret,.hb-bento .hb-edges path {animation: none !important;diff --git a/src/components/home/home-bento.tsx b/src/components/home/home-bento.tsxindex 4b51bc60..fdeda396 100644--- a/src/components/home/home-bento.tsx+++ b/src/components/home/home-bento.tsx@@ -1,6 +1,7 @@import { ArrowRight, ArrowUpRight, Play, Sparkles, Video } from "lucide-react";import { preload } from "react-dom";import { BentoClip, BentoMotion, BentoReel, LiveTyping, NumbersLink } from "@/components/home/bento-islands";+import { BentoVoice } from "@/components/home/bento-voice";import { PausePreviews } from "@/components/home/home-islands";import { IntentLink } from "@/components/intent-link";import { CountUp } from "@/components/ui/count-up";@@ -27,6 +28,11 @@ const SIZES = {* times 4/3: up to 560 px on a 1920 x 1080 screen); two columns on a tablet; the full row on a phone.*/genjutsu: "(min-width: 1024px) 560px, (min-width: 768px) 470px, calc(100vw - 32px)",+ /**+ * The Audio tile: from lg four of the fourteen columns and a third of the grid tall (wider than 4:3, so its width:+ * up to 320 px), a column on a tablet (230 px, squarer: its height times 4/3), the full row on a phone.+ */+ voice: "(min-width: 1024px) 320px, (min-width: 768px) 290px, calc(100vw - 32px)",};/**@@ -93,7 +99,10 @@ function Copy({ tile, bigMeta }: { tile: BentoTile; bigMeta?: boolean }) {);}-/** One tile: the whole of it is one link, named by its kind, title and where it goes. */+/**+ * One tile: the whole of it is one link, named by its kind, title and where it goes. (The Audio tile holds a demo's+ * buttons, so only its words are its link: bento-voice.tsx.)+ */function Tile({ tile, area, children, bigMeta }: { tile: BentoTile; area: string; children?: React.ReactNode; bigMeta?: boolean }) {return (<IntentLink href={tile.href} aria-label={tile.label} data-tile={tile.key} className={cn(s.tile, area)}>@@ -163,7 +172,8 @@ function CanvasBoard({ board }: { board: Bento["canvas"] }) {* Home's first screen: the page's headline over a grid of tiles, one per kind of media Fuobe makes, each a real* picture, clip or sound from the studio it opens. A server component: the words, numbers, links and stills are all* in the HTML; the clips, the typing, the motion switch and the numbers tile's launcher are small islands- * (bento-islands.tsx). Nothing in it depends on who is looking.+ * (bento-islands.tsx), and so is the Audio tile, Clean up voice's demo to play (bento-voice.tsx). Nothing in it depends+ * on who is looking.*/export function HomeBento({ bento }: { bento: Bento }) {const { tiles } = bento;@@ -230,14 +240,13 @@ export function HomeBento({ bento }: { bento: Bento }) {<BentoClip id={bento.threeD.id} clips={bento.threeD.clips} /></Tile>- <Tile tile={tiles.audio} area={s.audio}>- <span aria-hidden className={s.wave} style={{ "--wave-s": `${bento.wave.seconds}s` } as React.CSSProperties}>- {bento.wave.bars.map((h, i) => (- <i key={i} style={{ "--h": h, "--d": `${((i / bento.wave.bars.length) * bento.wave.seconds).toFixed(3)}s` } as React.CSSProperties} />- ))}- <span className={s.playhead} />- </span>- </Tile>+ {/* Clean up voice's demo, to hear right here: its words open the studio (bento-voice.tsx). */}+ <BentoVoice+ tile={tiles.audio}+ area={s.audio}+ room={<Pic pic={bento.voice.room} sizes={SIZES.voice} fetchPriority="low" />}+ quiet={<Pic pic={bento.voice.quiet} sizes={SIZES.voice} fetchPriority="low" />}+ /><NumbersLink href={tiles.numbers.href} aria-label={tiles.numbers.label} aria-haspopup="dialog" data-tile="numbers" className={cn(s.tile, s.numbers)}><dl aria-hidden className={s.figures}>diff --git a/src/lib/av/clean-voice-demo.ts b/src/lib/av/clean-voice-demo.tsindex f9a23762..e9187597 100644--- a/src/lib/av/clean-voice-demo.ts+++ b/src/lib/av/clean-voice-demo.ts@@ -68,6 +68,9 @@ export const HINTS = {unsupported: "This browser can't play the demo's sound.",} as const;+/** The chip over the photo: what is heard now (the studio's demo and Home's Audio tile say the same). */+export const stateLabel = (clean: boolean) => (clean ? "Voice only" : "Noisy restaurant");+export const DEMO_START: DemoState = { phase: "idle", clean: false, auto: true, ramp: 0, run: 0, flash: 0, hint: HINTS.ready };/** Playing or paused: both clips exist and keep their place. */diff --git a/src/lib/av/one-sound.ts b/src/lib/av/one-sound.tsnew file mode 100644index 00000000..6ed6148e--- /dev/null+++ b/src/lib/av/one-sound.ts@@ -0,0 +1,65 @@+/**+ * One sound at a time on a page. A sound player (the Clean up voice demo, on its studio page and on Home's Audio tile)+ * claims the page's sound when it starts: every other sound stops (a video or audio element playing with its sound on+ * is paused; another player hears the claim and pauses itself). While it plays it also listens: when an element on the+ * page starts to play with its sound on, or a playing one is unmuted, the player pauses. Muted previews (Home's clips)+ * are never touched and never pause anything.+ *+ * The page's window and document are passed in, so the rules can be checked without a browser (tests/one-sound.test.ts).+ */++/** The event a player sends on the window when it claims the page's sound; `detail` is its own id. */+export const SOUND_EVENT = "fuobe:sound";++/** The parts of a media element the rules use. */+export type MediaLike = Pick<HTMLMediaElement, "paused" | "ended" | "muted" | "volume" | "pause">;++/** The parts of a document the rules use: its media elements, and its events (play and volumechange don't bubble). */+export interface SoundDocument {+ querySelectorAll(selector: string): ArrayLike<unknown>;+ addEventListener(type: string, listener: (e: Event) => void, capture: boolean): void;+ removeEventListener(type: string, listener: (e: Event) => void, capture: boolean): void;+}+export type SoundWindow = Pick<EventTarget, "addEventListener" | "removeEventListener" | "dispatchEvent">;++const isMedia = (t: unknown): t is MediaLike =>+ !!t && typeof t === "object" && "paused" in t && "muted" in t && "volume" in t && typeof (t as MediaLike).pause === "function";++/** A media element that can be heard now: playing, with its sound on. */+export const audible = (m: unknown): boolean => isMedia(m) && !m.paused && !m.ended && !m.muted && m.volume > 0;++/**+ * Claims the page's sound for player `id`: pauses every media element that can be heard and tells the other players.+ * Returns how many elements it paused.+ */+export function claimSound(id: string, doc: SoundDocument, win: SoundWindow): number {+ let paused = 0;+ for (const m of Array.from(doc.querySelectorAll("audio, video"))) {+ if (!audible(m)) continue;+ (m as MediaLike).pause();+ paused++;+ }+ win.dispatchEvent(new CustomEvent(SOUND_EVENT, { detail: id }));+ return paused;+}++/**+ * Calls `stop` whenever another sound starts on the page: another player's claim, an element starting to play with+ * its sound on, or a playing element being unmuted. Returns the function that stops listening.+ */+export function onOtherSound(id: string, stop: () => void, doc: SoundDocument, win: SoundWindow): () => void {+ const claim = (e: Event) => {+ if ((e as CustomEvent).detail !== id) stop();+ };+ const media = (e: Event) => {+ if (audible(e.target)) stop();+ };+ win.addEventListener(SOUND_EVENT, claim);+ doc.addEventListener("play", media, true);+ doc.addEventListener("volumechange", media, true);+ return () => {+ win.removeEventListener(SOUND_EVENT, claim);+ doc.removeEventListener("play", media, true);+ doc.removeEventListener("volumechange", media, true);+ };+}diff --git a/src/lib/home-bento.generated.ts b/src/lib/home-bento.generated.tsindex d3c85b6c..6da7715a 100644--- a/src/lib/home-bento.generated.ts+++ b/src/lib/home-bento.generated.ts@@ -1,7 +1,7 @@/*** Home's first screen (src/components/home/home-bento.tsx): the content version of each file made for it, the video- * tile's reel, and the Audio tile's waveform, read from the Clean up voice sample (its version is `wave.source`). Generated by- * scripts/gen-home-bento.mjs: run it again rather than editing.+ * tile's reel and the Genjutsu tile's, and each poster's mean colour. Generated by scripts/gen-home-bento.mjs: run it+ * again rather than editing.*/export const HOME_BENTO_MEDIA: Record<string, string> = {"/previews/home/reel-sand-storm-640.mp4": "41410091",@@ -35,6 +35,14 @@ export const HOME_BENTO_MEDIA: Record<string, string> = {"/previews/home/genjutsu-couple-1024.jpg": "5b931a56","/previews/home/image-4-480.avif": "5a6d07a1","/previews/home/image-4-768.avif": "ef9d1b4d",+ "/previews/home/voice-room-480.avif": "e6981604",+ "/previews/home/voice-room-768.avif": "8c6ccbc8",+ "/previews/home/voice-room-1024.avif": "a919de1e",+ "/previews/home/voice-room-1024.jpg": "53823a28",+ "/previews/home/voice-quiet-480.avif": "26d4ec3a",+ "/previews/home/voice-quiet-768.avif": "71315903",+ "/previews/home/voice-quiet-1024.avif": "11f81723",+ "/previews/home/voice-quiet-1024.jpg": "17251953","/previews/home/board-photo.webp": "47432641","/previews/home/board-film.webp": "db007869"};@@ -72,10 +80,3 @@ export const HOME_BENTO_TINT: Record<string, string> = {"rotation": "#bfbeb6","genjutsu-couple": "#9f8a6b"};--export const HOME_BENTO_WAVE = {- src: "/samples/clean-voice/clean.m4a",- source: "8a1e9cfc",- seconds: 8,- bars: [0.442,0.504,0.279,0.12,0.141,0.64,0.655,0.757,0.12,1,0.441,0.189,0.903,0.725,0.549,0.147,0.336,0.482,0.415,0.58,0.711,0.12,0.12,0.702,0.451,0.439,0.201,0.12,0.12,0.805,0.555,0.738,0.777,0.759,0.339,0.429,0.524,0.488,0.634,0.973,0.931,0.329,0.737,0.718,0.61,0.388,0.491,0.527],-};diff --git a/src/lib/home-bento.ts b/src/lib/home-bento.tsindex fc0409b2..9124c7aa 100644--- a/src/lib/home-bento.ts+++ b/src/lib/home-bento.ts@@ -11,7 +11,7 @@ import { getTemplate } from "@/lib/catalog/canvas";import { runsOn } from "@/lib/catalog/engines";import type { ModelDef } from "@/lib/catalog/types";import { EXAMPLE_MEDIA } from "@/lib/examples/media.generated";-import { HOME_BENTO_GENJUTSU, HOME_BENTO_MEDIA, HOME_BENTO_REEL, HOME_BENTO_TINT, HOME_BENTO_WAVE } from "@/lib/home-bento.generated";+import { HOME_BENTO_GENJUTSU, HOME_BENTO_MEDIA, HOME_BENTO_REEL, HOME_BENTO_TINT } from "@/lib/home-bento.generated";import type { ReelClip, ReelWipe } from "@/lib/home-reel";import type { Demo } from "@/lib/live/demo";import { presetCover } from "@/lib/preset-covers";@@ -46,6 +46,13 @@ export const BENTO_GENJUTSU = { id: "home-genjutsu", cover: "genjutsu-group-swapexport const BENTO_GENJUTSU_WIDTHS = [640, 768, 1024] as const;/** The Canvas board the canvas tile draws: the same film as /canvas's "What's a canvas?". */export const BENTO_BOARD = "effect-chain-pearl-earring";+/**+ * The Audio tile: Clean up voice's own demo, played in the tile (src/components/home/bento-voice.tsx, with the studio's+ * sound: src/components/audio-tools/use-clean-voice-demo.ts). Its photos are copies of the demo's, made by+ * scripts/gen-home-bento.mjs in these widths: `room` as it is, and `quiet`, the room softened around her, which shows+ * once the noise is off.+ */+export const BENTO_VOICE = { room: "voice-room", quiet: "voice-quiet", widths: [480, 768, 1024] } as const;/** The Live edit steps the live tile plays: the session's first three changes (Home's Live edit section plays them all). */export const BENTO_LIVE_STEPS = ["s0", "s1", "s2", "s3"];@@ -53,7 +60,7 @@ export const BENTO_LIVE_STEPS = ["s0", "s1", "s2", "s3"];export const BENTO_HREFS = {video: "/cinema",image: `/image?example=${BENTO_IMAGE_EXAMPLE.id}`,- audio: "/audio",+ audio: "/audio/clean",threeD: "/image-to-3d",genjutsu: "/genjutsu",numbers: "#home-studios",@@ -243,6 +250,11 @@ export async function homeBento(f: BentoFacts) {},clips: widths.map((w) => ({ src: made(`/previews/home/${name}-${w}.mp4`), w })),});+ // The Audio tile's photos, each in its widths, and a JPEG at 1024 px for a browser without AVIF.+ const voicePic = (name: string): BentoPicture => ({+ avif: BENTO_VOICE.widths.map((w) => ({ src: made(`/previews/home/${name}-${w}.avif`), w })),+ fallback: made(`/previews/home/${name}-${BENTO_CLIP_FALLBACK}.jpg`),+ });const tile = (key: BentoKey, kind: string, meta: string, title: string, cta: string): BentoTile => ({key,meta,@@ -256,7 +268,7 @@ export async function homeBento(f: BentoFacts) {tiles: {video: tile("video", "Video", `${f.videoModels} video models · ${f.motions} camera moves`, "Films, ads and shorts", "Open Cinema Studio"),image: tile("image", "Image", `Image · ${f.imageModels} models`, "Portraits and campaigns", "Open Image"),- audio: tile("audio", "Audio", `Audio · ${f.soundTools} sound tools`, "Voice, music, sound effects", "Open Audio"),+ audio: tile("audio", "Audio", `Audio · ${f.soundTools} sound tools`, "Studio-clean voice", "Open Clean up voice"),threeD: tile("threeD", "3D", `3D · ${f.models3d} models`, "Spin it in 3D", "Open Image to 3D"),genjutsu: tile("genjutsu", "Genjutsu", "Genjutsu", "Swap anyone in a clip", "Open Genjutsu"),numbers: {@@ -274,7 +286,7 @@ export async function homeBento(f: BentoFacts) {} satisfies BentoPicture,threeD: moving(BENTO_CLIPS.threeD, BENTO_CLIP_FILES.threeD),genjutsu: genjutsu(),- wave: { bars: HOME_BENTO_WAVE.bars, seconds: HOME_BENTO_WAVE.seconds },+ voice: { room: voicePic(BENTO_VOICE.room), quiet: voicePic(BENTO_VOICE.quiet) },live: { frames: BENTO_LIVE_STEPS.map(frame), phrases: livePhrases(demo) },canvas: board(),numbers: [diff --git a/tests/clean-voice-demo.test.ts b/tests/clean-voice-demo.test.tsindex 8ee97b44..fb3bd9b2 100644--- a/tests/clean-voice-demo.test.ts+++ b/tests/clean-voice-demo.test.ts@@ -16,6 +16,7 @@ import {HINTS,isRunning,playLabel,+ stateLabel,SWITCH_RAMP,switchDue,type DemoAudioContext,@@ -130,6 +131,12 @@ describe("the demo's story", () => {expect(switchDue(run(tap, started, at(AUTO_AT)), AUTO_AT + 1)).toBe(false);expect(switchDue(run(tap, started, { type: "choose", clean: false }), AUTO_AT + 1)).toBe(false);});++ it("says what is heard on the chip, the same on the studio's demo and on Home's Audio tile", () => {+ expect(stateLabel(DEMO_START.clean)).toBe("Noisy restaurant");+ expect(stateLabel(run(tap, started, at(AUTO_AT)).clean)).toBe("Voice only");+ expect(stateLabel(run(tap, started, at(AUTO_AT), { type: "choose", clean: false }).clean)).toBe("Noisy restaurant");+ });});/** A stand-in for an AudioContext that records what the demo asks of it. */diff --git a/tests/e2e/home-bento.mjs b/tests/e2e/home-bento.mjsindex 5f389f89..cdaae180 100644--- a/tests/e2e/home-bento.mjs+++ b/tests/e2e/home-bento.mjs@@ -41,7 +41,8 @@// 2.5 s late, and with the HTML in two parts (cut after the second line's first words, 1.5 s apart, by a proxy) and// the fonts 1.5 s late, no layout shift moves anything in the h1, the cut line stays unseen until whole, and once all// is in, the headline looks as on a quick load (its picture within 1 level in 255 on average).-// 3. Every tile's link answers 200, and the numbers tile opens every studio (the launcher; a phone's sheet).+// 3. Every tile's link answers 200 (the Audio tile's is its words: the tile holds Clean up voice's demo, checked on its+// own by tests/e2e/home-voice.mjs), and the numbers tile opens every studio (the launcher; a phone's sheet).// 4. Reduced motion and Save-Data: no clip is fetched or played, nothing moves by itself (the headline is still, the// live words stay), and the tiles keep their stills.// 5. Pause previews stops the reel and freezes every animation; pressed again, they go on.@@ -49,7 +50,8 @@// stills stay under 420 KB (the clips' posters are encoded close to their clips' first frames, and a 3x phone or a// 2x laptop gets the video tile's widest still). The clips are reported on their own.// 7. The composer: /?new=1 brings it into view with the focus; a plain visit stays at the top (no autofocus jump).-// 8. Every tile is a named link, and Tab reaches them in the grid's reading order with a visible ring.+// 8. Every tile is a named link (the Audio tile: its words), and Tab reaches them in the grid's reading order (through+// the Audio tile's buttons) with a visible ring.import assert from "node:assert/strict";import fs from "node:fs";import path from "node:path";@@ -984,7 +986,8 @@ if (run("3")) {const ctx = await browser.newContext(DESKTOP);const page = await ctx.newPage();await open(page);- const hrefs = await page.$$eval("#home-bento [data-tile]", (as) => as.map((a) => [a.dataset.tile, a.getAttribute("href")]));+ // Each tile's link: the tile itself, or (the Audio tile) the link inside it.+ const hrefs = await page.$$eval("#home-bento [data-tile]", (els) => els.map((el) => [el.dataset.tile, (el.matches("a") ? el : el.querySelector("a[href]"))?.getAttribute("href") ?? ""]));check("eight tiles, in the grid's reading order", hrefs.map((h) => h[0]).join() === TILES.join(), hrefs.map((h) => h[0]).join());for (const [tile, href] of hrefs) {if (href.startsWith("#")) {@@ -1186,10 +1189,12 @@ if (run("8")) {const names = await page.$$eval("#home-bento a", (as) => as.map((a) => a.getAttribute("aria-label") ?? a.textContent.trim()));check("every link on the first screen has a name", names.length === 8 && names.every((n) => n && n.length > 5), names.join(" | "));await page.locator("#home-bento h1").click();+ // The tile each Tab lands in, once per tile (the Audio tile's switch, play button and link are all in it).const order = [];- for (let i = 0; i < 8; i++) {+ for (let i = 0; i < 16 && order.length < TILES.length; i++) {await page.keyboard.press("Tab");- order.push(await page.evaluate(() => document.activeElement?.dataset?.tile ?? document.activeElement?.tagName));+ const at = await page.evaluate(() => document.activeElement?.closest("[data-tile]")?.dataset.tile ?? document.activeElement?.tagName);+ if (order.at(-1) !== at) order.push(at);}check("Tab reaches the tiles in reading order", order.join() === TILES.join(), order.join());await page.keyboard.press("Shift+Tab");diff --git a/tests/e2e/home-voice.mjs b/tests/e2e/home-voice.mjsnew file mode 100644index 00000000..0cfab022--- /dev/null+++ b/tests/e2e/home-voice.mjs@@ -0,0 +1,407 @@+// Home's Audio tile in a real browser: Clean up voice's demo, played on Home (src/components/home/bento-voice.tsx, its+// sound in src/components/audio-tools/use-clean-voice-demo.ts). Run it on a production server (`next build`, then+// `next start -p <port>`).+//+// Usage: node tests/e2e/home-voice.mjs [appUrl] [--shots <dir>] (E2E_BROWSER=webkit or firefox: that engine)+//+// The page's Web Audio is watched from inside (an init script records each AudioContext, gain and source it makes):+// 1. At rest, 1440 x 900 and 390 x 844: no sound, no AudioContext and no clip fetched; the chip says Noisy restaurant,+// Noise on is pressed, the play button says Tap to listen; on a phone every button is at least 44 px to tap.+// 2. A tap (a click at 1440, a touch at 390): the context runs, both takes start on the same sample, the room heard and+// her voice silent, each clip fetched once; a few seconds in the noise goes by itself (the gains cross to her voice,+// the chip says Voice only, the softened photo shows). Noise on and Noise off cross the gains back and forth.+// Nothing on the first screen shifts while it plays (Chromium).+// 3. Out of view it pauses (the context suspended), and one tap resumes it; a hidden tab pauses it too.+// 4. One sound at a time: a song starting on the page pauses the demo, and the demo resumed pauses the song.+// 5. The keyboard alone: Tab reaches Noise on, Noise off and the play button, each says what it does, Space and Enter+// work, and the chip's live region says what is heard.+// 6. Reduced motion: it plays, and the photo doesn't move.+import fs from "node:fs";+import path from "node:path";+import { DESKTOP, ENGINE, launch, PHONE } 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 failures = [];+const notes = [];+const check = (name, ok, detail = "") => {+ console.log(`${ok ? "ok " : "FAIL"} ${name}${detail ? ` (${detail})` : ""}`);+ if (!ok) failures.push(`${name} ${detail}`);+};++/** Records the page's Web Audio: each context, gain and buffer source it makes, and when each source starts. */+const watchAudio = () => {+ const AC = window.AudioContext || window.webkitAudioContext;+ window.__audio = { contexts: [], gains: [], sources: [] };+ if (!AC) return;+ const createGain = AC.prototype.createGain;+ AC.prototype.createGain = function () {+ const g = createGain.call(this);+ window.__audio.gains.push(g);+ return g;+ };+ const createBufferSource = AC.prototype.createBufferSource;+ AC.prototype.createBufferSource = function () {+ const src = createBufferSource.call(this);+ const rec = { at: null, stopped: false, duration: 0 };+ const start = src.start.bind(src);+ src.start = (when = 0, ...rest) => {+ rec.at = when;+ rec.duration = src.buffer?.duration ?? 0;+ return start(when, ...rest);+ };+ const stop = src.stop.bind(src);+ src.stop = (...a) => {+ rec.stopped = true;+ return stop(...a);+ };+ window.__audio.sources.push(rec);+ return src;+ };+ function Watched(...a) {+ const ctx = new AC(...a);+ window.__audio.contexts.push(ctx);+ return ctx;+ }+ Watched.prototype = AC.prototype;+ window.AudioContext = Watched;+ if (window.webkitAudioContext) window.webkitAudioContext = Watched;+ // Layout shifts, for the check that nothing moves while it plays.+ window.__shifts = [];+ try {+ new PerformanceObserver((list) => {+ for (const e of list.getEntries()) if (!e.hadRecentInput) window.__shifts.push({ v: e.value, at: Math.round(e.startTime) });+ }).observe({ type: "layout-shift", buffered: true });+ } catch {}+};++/** What the page's sound is doing now: the context, the last two gains (room, voice) and the two latest sources. */+const audioNow = (page) =>+ page.evaluate(() => {+ const a = window.__audio;+ const ctx = a.contexts.at(-1);+ return {+ contexts: a.contexts.length,+ state: ctx?.state ?? null,+ time: ctx?.currentTime ?? 0,+ gains: a.gains.slice(-2).map((g) => Math.round(g.gain.value * 100) / 100),+ sources: a.sources.slice(-2).map((s) => ({ at: s.at, stopped: s.stopped, duration: s.duration })),+ started: a.sources.length,+ };+ });++const tile = (page) => page.locator('#home-bento [data-tile="audio"]');+const phase = (page) => tile(page).getAttribute("data-phase");+const chip = (page) => tile(page).locator("[data-demo-state]").innerText();+const pressed = (page, name) => tile(page).getByRole("button", { name, exact: true }).getAttribute("aria-pressed");+const waitPhase = (page, want, timeout = 20_000) =>+ page+ .waitForFunction((w) => document.querySelector('#home-bento [data-tile="audio"]')?.dataset.phase === w, want, { timeout })+ .then(() => true)+ .catch(() => false);+/** Waits until both gains have settled at `want` (room, voice). */+const waitGains = (page, want, timeout = 6000) =>+ page+ .waitForFunction(+ (w) => {+ const g = window.__audio.gains.slice(-2).map((x) => x.gain.value);+ return g.length === 2 && g.every((v, i) => Math.abs(v - w[i]) < 0.02);+ },+ want,+ { timeout },+ )+ .then(() => true)+ .catch(() => false);++async function open(ctx) {+ await ctx.addInitScript(watchAudio);+ const page = await ctx.newPage();+ page.on("pageerror", (e) => check(`no page error (${String(e.message).slice(0, 140)})`, false));+ const clips = [];+ page.on("request", (r) => /\/samples\/clean-voice\/.*\.m4a/.test(r.url()) && clips.push(new URL(r.url()).pathname));+ await page.goto(app + "/", { waitUntil: "load", timeout: 90_000 });+ await tile(page).waitFor({ timeout: 20_000 });+ return { page, clips };+}++const shot = async (page, name) => {+ if (!shotsDir) return;+ const b = await tile(page).boundingBox();+ if (b)+ await page.screenshot({+ path: path.join(shotsDir, `${name}.png`),+ clip: { x: Math.max(0, b.x - 10), y: Math.max(0, b.y - 10), width: b.width + 20, height: b.height + 20 },+ });+};++const browser = await launch();+try {+ // ---------------------------------------------------------------------------------- 1, 2, 3, 4: at rest, then played+ for (const [label, device] of [+ ["1440", DESKTOP],+ ["390", PHONE],+ ]) {+ for (const scheme of ["light", "dark"]) {+ const tag = `${label} ${scheme}`;+ const ctx = await browser.newContext({ ...device, colorScheme: scheme, deviceScaleFactor: label === "390" ? 3 : 2 });+ const { page, clips } = await open(ctx);+ await tile(page).scrollIntoViewIfNeeded();+ await page.waitForTimeout(1200);+ const rest = await audioNow(page);+ check(`${tag}: at rest, no sound and nothing fetched`, rest.contexts === 0 && clips.length === 0, JSON.stringify({ contexts: rest.contexts, clips }));+ check(+ `${tag}: at rest, Noisy restaurant, Noise on pressed, Tap to listen`,+ (await chip(page)) === "Noisy restaurant" &&+ (await pressed(page, "Noise on")) === "true" &&+ (await pressed(page, "Noise off")) === "false" &&+ (await phase(page)) === "idle",+ );+ check(`${tag}: the play button is named`, (await tile(page).getByRole("button", { name: "Tap to listen" }).count()) === 1);+ if (label === "390") {+ const sizes = await tile(page)+ .locator("button")+ .evaluateAll((bs) =>+ bs.map((b) => [b.textContent.trim(), Math.round(b.getBoundingClientRect().width), Math.round(b.getBoundingClientRect().height)]),+ );+ check(+ `${tag}: every button at least 44 px to tap`,+ sizes.every(([, w, h]) => w >= 44 && h >= 44),+ JSON.stringify(sizes),+ );+ const box = await tile(page).boundingBox();+ check(`${tag}: the tile is the full row`, Math.round(box.width) === 358, String(box.width));+ }+ await shot(page, `${tag}-rest`);++ // A browser without Web Audio (Playwright's WebKit for Windows has none; Safari itself has it): a tap says it+ // can't, and nothing else on the page breaks.+ if (!(await page.evaluate(() => !!(window.AudioContext || window.webkitAudioContext)))) {+ await tile(page).getByRole("button", { name: "Tap to listen" }).click();+ check(+ `${tag}: without Web Audio, a tap offers to try again`,+ (await waitPhase(page, "failed", 4000)) && (await tile(page).getByRole("button", { name: "Try again" }).count()) === 1,+ );+ if (!notes.some((n) => n.includes("Web Audio"))) notes.push(`skipped under ${ENGINE}: the sound checks (this build has no Web Audio)`);+ await ctx.close();+ continue;+ }++ // A tap: both takes, the room first.+ const play = tile(page).getByRole("button", { name: "Tap to listen" });+ if (label === "390") await play.tap();+ else await play.click();+ const started = await waitPhase(page, "playing");+ const a = await audioNow(page);+ check(`${tag}: one tap plays it`, started && a.state === "running", JSON.stringify({ phase: await phase(page), state: a.state }));+ check(+ `${tag}: both takes start on the same sample`,+ a.sources.length === 2 && a.sources[0].at !== null && a.sources[0].at === a.sources[1].at && a.sources.every((s) => s.duration > 7),+ JSON.stringify(a.sources),+ );+ check(`${tag}: the room first, her voice silent`, a.gains.join() === "1,0", a.gains.join());+ check(`${tag}: each clip fetched once, on the tap`, clips.length === 2 && new Set(clips).size === 2, clips.join(" "));+ await page.waitForTimeout(700);+ const later = await audioNow(page);+ check(`${tag}: the sound's clock runs`, later.time > a.time + 0.4, `${a.time.toFixed(2)} -> ${later.time.toFixed(2)}`);+ await shot(page, `${tag}-playing`);++ // A few seconds in, the noise goes by itself.+ const quietNow = await page+ .waitForFunction(() => document.querySelector('#home-bento [data-tile="audio"] [data-demo-state]')?.textContent === "Voice only", null, {+ timeout: 8000,+ })+ .then(() => true)+ .catch(() => false);+ check(`${tag}: the noise goes by itself, the chip says Voice only`, quietNow);+ check(`${tag}: the gains cross to her voice`, await waitGains(page, [0, 1]), (await audioNow(page)).gains.join());+ check(`${tag}: Noise off is pressed`, (await pressed(page, "Noise off")) === "true");+ await page.waitForTimeout(1100);+ const soft = await tile(page).evaluate((el) => Number(getComputedStyle(el.querySelector(".hb-voice-quiet")).opacity));+ check(`${tag}: the softened photo shows`, soft > 0.95, String(soft));+ await shot(page, `${tag}-voice-only`);++ // Noise on, Noise off: the switch crosses the gains at once.+ await tile(page).getByRole("button", { name: "Noise on", exact: true }).click();+ check(+ `${tag}: Noise on brings the room back`,+ (await waitGains(page, [1, 0], 2000)) && (await chip(page)) === "Noisy restaurant" && (await pressed(page, "Noise on")) === "true",+ (await audioNow(page)).gains.join(),+ );+ await tile(page).getByRole("button", { name: "Noise off", exact: true }).click();+ check(`${tag}: Noise off takes it away again`, (await waitGains(page, [0, 1], 2000)) && (await chip(page)) === "Voice only");+ check(`${tag}: still one take of each, still playing`, (await audioNow(page)).started === 2 && (await phase(page)) === "playing");++ if (ENGINE === "chromium") {+ const shifts = await page.evaluate(() => window.__shifts.reduce((s, e) => s + e.v, 0));+ check(`${tag}: nothing shifts while it plays`, shifts < 0.001, String(shifts));+ }++ // 3. Out of view it pauses; a tap resumes it.+ await page.evaluate(() => window.scrollTo(0, document.documentElement.scrollHeight));+ const pausedOut = await waitPhase(page, "paused", 4000);+ const out = await audioNow(page);+ check(`${tag}: scrolled away, it pauses`, pausedOut && out.state === "suspended", JSON.stringify({ phase: await phase(page), state: out.state }));+ await tile(page).scrollIntoViewIfNeeded();+ await page.waitForTimeout(500);+ check(`${tag}: back in view it stays paused until asked`, (await phase(page)) === "paused");+ const resume = tile(page).getByRole("button", { name: "Resume" });+ if (label === "390") await resume.tap();+ else await resume.click();+ const back = await waitPhase(page, "playing", 4000);+ // (The context resumes a moment after the tap: its promise.)+ const running = await page+ .waitForFunction(() => window.__audio.contexts.at(-1)?.state === "running", null, { timeout: 3000 })+ .then(() => true)+ .catch(() => false);+ const resumed = await audioNow(page);+ check(`${tag}: one tap resumes it`, back && running, JSON.stringify({ back, phase: await phase(page), state: resumed.state, time: resumed.time }));++ // A hidden tab pauses it.+ await page.evaluate(() => {+ Object.defineProperty(document, "hidden", { value: true, configurable: true });+ Object.defineProperty(document, "visibilityState", { value: "hidden", configurable: true });+ document.dispatchEvent(new Event("visibilitychange"));+ });+ check(`${tag}: a hidden tab pauses it`, await waitPhase(page, "paused", 3000));+ await page.evaluate(() => {+ delete document.hidden;+ delete document.visibilityState;+ document.dispatchEvent(new Event("visibilitychange"));+ });++ // 4. One sound at a time.+ if (label === "1440" && scheme === "light") {+ await tile(page).getByRole("button", { name: "Resume" }).click();+ await waitPhase(page, "playing", 4000);+ const songPlays = await page.evaluate(async () => {+ // Two seconds of a quiet tone, as a WAV, playing with its sound on.+ const rate = 8000;+ const n = rate * 2;+ const buf = new ArrayBuffer(44 + n * 2);+ const v = new DataView(buf);+ const str = (o, s) => [...s].forEach((c, i) => v.setUint8(o + i, c.charCodeAt(0)));+ str(0, "RIFF");+ v.setUint32(4, 36 + n * 2, true);+ str(8, "WAVEfmt ");+ v.setUint32(16, 16, true);+ v.setUint16(20, 1, true);+ v.setUint16(22, 1, true);+ v.setUint32(24, rate, true);+ v.setUint32(28, rate * 2, true);+ v.setUint16(32, 2, true);+ v.setUint16(34, 16, true);+ str(36, "data");+ v.setUint32(40, n * 2, true);+ for (let i = 0; i < n; i++) v.setInt16(44 + i * 2, Math.round(Math.sin(i / 8) * 200), true);+ const song = new Audio(URL.createObjectURL(new Blob([buf], { type: "audio/wav" })));+ song.loop = true;+ song.id = "e2e-song";+ document.body.append(song);+ try {+ await song.play();+ return true;+ } catch (e) {+ return String(e);+ }+ });+ if (songPlays === true) {+ check("a song starting on the page pauses the demo", await waitPhase(page, "paused", 3000));+ await tile(page).getByRole("button", { name: "Resume" }).click();+ await waitPhase(page, "playing", 4000);+ await page.waitForTimeout(300);+ check("the demo resumed pauses the song", await page.evaluate(() => document.getElementById("e2e-song").paused));+ // Home's own previews play muted: they never stop it.+ await page.waitForTimeout(1500);+ check("the muted previews never stop it", (await phase(page)) === "playing" || (await phase(page)) === "done", await phase(page));+ } else notes.push(`one sound at a time: skipped, this ${ENGINE} build wouldn't play the test song (${songPlays})`);+ }+ await ctx.close();+ }+ }++ /** Set when the browser has no Web Audio (above): only the checks that need no sound run. */+ const noWebAudio = notes.some((n) => n.includes("Web Audio"));++ // ---------------------------------------------------------------------------------- 5. the keyboard alone+ {+ const ctx = await browser.newContext(DESKTOP);+ const { page } = await open(ctx);+ await page.locator("#home-bento h1").click();+ const stops = [];+ for (let i = 0; i < 16; i++) {+ await page.keyboard.press("Tab");+ const at = await page.evaluate(() => {+ const el = document.activeElement;+ return el?.closest('[data-tile="audio"]') ? `${el.tagName.toLowerCase()}:${el.getAttribute("aria-label") ?? el.textContent.trim()}` : null;+ });+ if (at) stops.push(at);+ else if (stops.length) break;+ }+ // (WebKit's Tab moves between form controls only, not links, unless the viewer turns that on.)+ const wantStops = [+ "button:Noise on",+ "button:Noise off",+ "button:Tap to listen",+ ...(ENGINE === "webkit" ? [] : ["a:Audio: Studio-clean voice. Open Clean up voice"]),+ ];+ check(+ "keyboard: Tab reaches Noise on, Noise off, the play button and the link, in that order",+ stops.join(" | ") === wantStops.join(" | "),+ stops.join(" | "),+ );+ // Back to Noise off: Space starts it with the noise off.+ for (let i = 0; i < wantStops.length - 1; i++) await page.keyboard.press("Shift+Tab");+ const focused = await page.evaluate(() => document.activeElement?.textContent.trim());+ check("keyboard: Shift+Tab goes back to Noise off", focused === "Noise off", focused);+ if (noWebAudio) {+ await ctx.close();+ } else {+ await page.keyboard.press("Space");+ const keyed = await waitPhase(page, "playing");+ check(+ "keyboard: Space on Noise off plays it with her voice alone",+ keyed && (await waitGains(page, [0, 1], 3000)) && (await pressed(page, "Noise off")) === "true",+ (await audioNow(page)).gains.join(),+ );+ const live = await tile(page).locator("[aria-live=polite]").innerText();+ check("keyboard: the live region says what is heard", live.trim() === "Voice only", live);+ await page.keyboard.press("Shift+Tab");+ await page.keyboard.press("Enter");+ check("keyboard: Enter on Noise on brings the room back", (await waitGains(page, [1, 0], 3000)) && (await pressed(page, "Noise on")) === "true");+ await page.keyboard.press("Tab");+ await page.keyboard.press("Tab");+ const pauseName = await page.evaluate(() => document.activeElement?.textContent.trim());+ await page.keyboard.press("Enter");+ check(+ "keyboard: the play button says Pause while it plays, and Enter pauses it",+ pauseName === "Pause" && (await waitPhase(page, "paused", 3000)),+ pauseName,+ );+ await ctx.close();+ }+ }++ // ---------------------------------------------------------------------------------- 6. reduced motion+ if (!noWebAudio) {+ const ctx = await browser.newContext({ ...DESKTOP, reducedMotion: "reduce" });+ const { page } = await open(ctx);+ await tile(page).getByRole("button", { name: "Tap to listen" }).click();+ const ok = await waitPhase(page, "playing");+ await page.waitForTimeout(800);+ const t = await tile(page).evaluate((el) => getComputedStyle(el.querySelector(".hb-voice-pics")).transform);+ check("reduced motion: it plays, and the photo doesn't move", ok && (t === "none" || t === "matrix(1, 0, 0, 1, 0, 0)"), t);+ await ctx.close();+ }+} finally {+ await browser.close();+}++if (notes.length) console.log("\n" + notes.join("\n"));+if (failures.length) {+ console.log(`\n${failures.length} failed:\n- ${failures.join("\n- ")}`);+ process.exit(1);+}+console.log(`\nall passed (${ENGINE})`);diff --git a/tests/home-bento.test.ts b/tests/home-bento.test.tsindex 1ca40d41..fcc54666 100644--- a/tests/home-bento.test.ts+++ b/tests/home-bento.test.ts@@ -1,4 +1,3 @@-import { spawnSync } from "node:child_process";import fs from "node:fs";import path from "node:path";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";@@ -10,11 +9,12 @@ import { getTemplate } from "@/lib/catalog/canvas";import { FORBIDDEN_WORDS } from "@/lib/examples/catalog";import { HUB_MODES } from "@/lib/hubs";import { studioCount } from "@/lib/nav-model";-import { HOME_BENTO_MEDIA, HOME_BENTO_WAVE } from "@/lib/home-bento.generated";+import { HOME_BENTO_MEDIA } from "@/lib/home-bento.generated";import { contentVersion } from "../scripts/eval/lib/covers.mjs";import { WIPES, lineAt } from "../scripts/gen-home-bento.mjs";import sharp from "sharp";import type { BentoPicture } from "@/lib/home-bento";+import { DEMO_MEDIA, DEMO_START, demoReducer } from "@/lib/av/clean-voice-demo";import { coverWidth, pickWidth } from "@/lib/media-pick";import { mp4Seconds, mp4Size } from "./helpers/mp4-length";@@ -31,10 +31,11 @@ vi.mock("next/navigation", () => ({useSearchParams: () => new URLSearchParams(),}));-const { BENTO_BOARD, BENTO_CLIPS, BENTO_CLIP_WIDTHS, BENTO_GENJUTSU, BENTO_GENJUTSU_WIDTHS, BENTO_HREFS, BENTO_IMAGE_EXAMPLE, BENTO_REEL, BENTO_REEL_ID, livePhrases, openModelsOf } =+const { BENTO_BOARD, BENTO_CLIPS, BENTO_CLIP_WIDTHS, BENTO_GENJUTSU, BENTO_GENJUTSU_WIDTHS, BENTO_HREFS, BENTO_IMAGE_EXAMPLE, BENTO_REEL, BENTO_REEL_ID, BENTO_VOICE, livePhrases, openModelsOf } =await import("@/lib/home-bento");const { HOME_BEFORE_AFTER, HOME_EFFECTS, HOME_MOTIONS, HOME_REVEALS, HOME_STUDIOS, homeShowcase, navLabel } = await import("@/lib/home-showcase");const { HomeBento } = await import("@/components/home/home-bento");+const { voiceButton } = await import("@/components/home/bento-voice");const root = process.cwd();const file = (url: string) => path.join(root, "public", url.split("?")[0]);@@ -165,7 +166,7 @@ describe("Home's first screen", () => {});it("lists every picture at its real width", async () => {- const pictures: BentoPicture[] = [bento.video.poster, bento.threeD.poster, bento.image, bento.genjutsu.poster, bento.genjutsu.still, ...bento.live.frames];+ const pictures: BentoPicture[] = [bento.video.poster, bento.threeD.poster, bento.image, bento.genjutsu.poster, bento.genjutsu.still, bento.voice.room, bento.voice.quiet, ...bento.live.frames];for (const p of pictures)for (const a of p.avif) {const m = await sharp(file(a.src)).metadata();@@ -211,6 +212,10 @@ describe("Home's first screen", () => {it("opens a real page from every tile, named by the navigation or the catalog", () => {const route = (href: string) => {const seg = href.split(/[?#]/)[0].replace(/^\//, "");+ const [hub, mode] = seg.split("/");+ // A hub's mode on its own page (/audio/clean): the hub's [mode] page, for a mode it has.+ if (mode && hub in HUB_MODES)+ return HUB_MODES[hub as keyof typeof HUB_MODES].some((m) => m.id === mode) && fs.existsSync(path.join(root, "src", "app", "(studio)", hub, "[mode]", "page.tsx"));return fs.existsSync(path.join(root, "src", "app", "(studio)", seg, "page.tsx"));};for (const href of [BENTO_HREFS.video, BENTO_HREFS.image, BENTO_HREFS.audio, BENTO_HREFS.threeD, BENTO_HREFS.genjutsu, BENTO_HREFS.live, BENTO_HREFS.canvas])@@ -223,7 +228,9 @@ describe("Home's first screen", () => {const t = bento.tiles;expect(t.video.cta).toBe(`Open ${navLabel("/cinema")}`);expect(t.image.cta).toBe(`Open ${navLabel("/image")}`);- expect(t.audio.cta).toBe(`Open ${navLabel("/audio")}`);+ // The Audio tile plays Clean up voice's demo, and opens that mode's own page.+ expect(BENTO_HREFS.audio).toBe("/audio/clean");+ expect(t.audio.cta).toBe(`Open ${HUB_MODES.audio.find((m) => m.id === "clean")!.label}`);expect(t.threeD.cta).toBe(`Open ${navLabel("/image-to-3d")}`);expect(t.live.cta).toBe(`Open ${navLabel("/live-edit")}`);expect(t.canvas.cta).toBe(`Open ${navLabel("/canvas")}`);@@ -233,8 +240,13 @@ describe("Home's first screen", () => {it("makes every tile one link with a name, in the grid's reading order", () => {const links = [...html.matchAll(/<a [^>]*>/g)].map((m) => m[0]);const tiles = links.filter((a) => a.includes("data-tile="));- expect(tiles.map((a) => /data-tile="([^"]+)"/.exec(a)![1])).toEqual(["video", "live", "genjutsu", "image", "threeD", "audio", "numbers", "canvas"]);- for (const a of tiles) {+ // Every tile is its link but the Audio tile, which holds the demo's buttons: its words are its link.+ expect([...html.matchAll(/<(?:a|div) [^>]*data-tile="([^"]+)"/g)].map((m) => m[1])).toEqual(["video", "live", "genjutsu", "image", "threeD", "audio", "numbers", "canvas"]);+ expect(tiles.map((a) => /data-tile="([^"]+)"/.exec(a)![1])).toEqual(["video", "live", "genjutsu", "image", "threeD", "numbers", "canvas"]);+ const audioLink = links.find((a) => a.includes(`href="${BENTO_HREFS.audio}"`));+ expect(audioLink).toBeTruthy();+ expect(links).toHaveLength(8);+ for (const a of [...tiles, audioLink!]) {const label = /aria-label="([^"]+)"/.exec(a)?.[1];expect(label, a).toBeTruthy();expect(label!.length).toBeGreaterThan(10);@@ -247,8 +259,8 @@ describe("Home's first screen", () => {// The numbers tile opens the studios list in place, and says so.expect(bento.tiles.numbers.label).toBe(`${bento.numbers[0].value} studios, ${bento.numbers[1].value} apps, ${bento.numbers[2].value} effects and camera moves. Opens all studios`);expect(tiles.find((a) => a.includes('data-tile="numbers"'))).toContain('aria-haspopup="dialog"');- // No link or button inside a tile: the whole tile is the one target.- for (const chunk of html.split("data-tile=").slice(1)) expect(chunk.split("</a>")[0]).not.toMatch(/<(a|button)\b/);+ // No link or button inside a tile: the whole tile is the one target (the Audio tile is a group of its own).+ for (const chunk of html.split("data-tile=").slice(1).filter((c) => !c.startsWith('"audio"'))) expect(chunk.split("</a>")[0]).not.toMatch(/<(a|button)\b/);// The page's only h1: the headline, in its own words; "finished film," and "one place." never break apart.expect(html.match(/<h1\b/g)).toHaveLength(1);const h1 = /<h1\b[^>]*>([\s\S]*?)<\/h1>/.exec(html)![1].replace(/<[^>]+>/g, "");@@ -316,20 +328,51 @@ describe("Home's first screen", () => {expect(home).not.toHaveProperty("wall");});- it("draws the Audio tile from the sample's own loudness", () => {- expect(bento.wave.bars).toHaveLength(48);- for (const b of bento.wave.bars) {- expect(b).toBeGreaterThanOrEqual(0.12);- expect(b).toBeLessThanOrEqual(1);- }- expect(Math.max(...bento.wave.bars)).toBe(1);- // Made from the sample as it is now: a new sample needs node scripts/gen-home-bento.mjs again.- expect(contentVersion([file(HOME_BENTO_WAVE.src)])).toBe(HOME_BENTO_WAVE.source);- const ffmpeg = spawnSync("ffmpeg", ["-v", "error", "-i", file(HOME_BENTO_WAVE.src), "-ac", "1", "-ar", "8000", "-f", "s16le", "-"], { maxBuffer: 64 << 20 });- if (ffmpeg.status === 0) {- const samples = new Int16Array(ffmpeg.stdout.buffer, ffmpeg.stdout.byteOffset, Math.floor(ffmpeg.stdout.length / 2));- expect(samples.length / 8000).toBeCloseTo(HOME_BENTO_WAVE.seconds, 1);+ it("plays Clean up voice's demo in the Audio tile: tap to listen, Noise on / Noise off, and its words open the studio", () => {+ const tile = /<div [^>]*data-tile="audio"[\s\S]*?<\/a>/.exec(html)![0];+ // A named group: the demo's buttons, then the link to the studio, named as every tile's link is.+ expect(tile).toMatch(/^<div role="group" aria-label="Clean up voice: a woman talking in a noisy restaurant"/);+ expect(tile).toContain('data-phase="idle"');+ const buttons = [...tile.matchAll(/<button\b[^>]*>([\s\S]*?)<\/button>/g)].map((m) => [m[0], m[1].replace(/<[^>]+>/g, "")] as const);+ expect(buttons.map(([, text]) => text)).toEqual(["Noise on", "Noise off", "Tap to listen"]);+ expect(buttons.every(([b]) => b.includes('type="button"'))).toBe(true);+ // Noise on is pressed before anything plays; the chip says what is heard, in a live region.+ expect(buttons[0][0]).toContain('aria-pressed="true"');+ expect(buttons[1][0]).toContain('aria-pressed="false"');+ expect(tile).toMatch(/<span [^>]*aria-live="polite"[^>]*>[\s\S]*?<span data-demo-state="true">Noisy restaurant<\/span>/);+ expect(tile).toContain(`href="${BENTO_HREFS.audio}"`);+ expect(tile).toContain(`aria-label="${bento.tiles.audio.label}"`);+ expect(bento.tiles.audio.label).toBe("Audio: Studio-clean voice. Open Clean up voice");+ // Nothing plays or downloads before a tap: no sound in the HTML, and the softened photo only once reached for.+ for (const f of [DEMO_MEDIA.noisy, DEMO_MEDIA.clean]) expect(html).not.toContain(f);+ expect(html).not.toMatch(/<audio\b/);+ expect(tile).toContain(`/previews/home/${BENTO_VOICE.room}-480.avif?v=`);+ expect(tile).not.toContain(`/previews/home/${BENTO_VOICE.quiet}-`);+ // Its photos: the demo's own, in three widths, and a JPEG for a browser without AVIF.+ for (const [pic, name] of [+ [bento.voice.room, BENTO_VOICE.room],+ [bento.voice.quiet, BENTO_VOICE.quiet],+ ] as const) {+ expect(pic.avif.map((a) => a.w)).toEqual([...BENTO_VOICE.widths]);+ for (const a of pic.avif) expect(a.src).toMatch(new RegExp(`^/previews/home/${name}-${a.w}\\.avif\\?v=`));+ expect(pic.fallback).toMatch(new RegExp(`^/previews/home/${name}-1024\\.jpg\\?v=`));}+ // A 3x phone's full row (358 px) gets the widest copy; a 2x laptop's tile (320 px wide) the 768.+ expect(pickWidth(bento.voice.room.avif, 358 * 3).w).toBe(1024);+ expect(pickWidth(bento.voice.room.avif, coverWidth(319, 148, 4 / 3, 2)).w).toBe(768);+ });++ it("names the Audio tile's play button for each moment of the demo", () => {+ const tap = { type: "tap" } as const;+ const loading = demoReducer(DEMO_START, tap);+ const playing = demoReducer(loading, { type: "started" });+ const paused = demoReducer(playing, tap);+ const done = demoReducer(playing, { type: "ended" });+ const failed = demoReducer(loading, { type: "failed" });+ expect([DEMO_START, loading, playing, paused, done, failed].map((st) => voiceButton(st).label)).toEqual(["Tap to listen", "Loading…", "Pause", "Resume", "Play again", "Try again"]);+ // Only loading shows the spinner.+ expect(voiceButton(loading).spin).toBe(true);+ expect([DEMO_START, playing, paused].some((st) => voiceButton(st).spin)).toBe(false);});it("types the Live edit session's own words before the pictures they made", () => {diff --git a/tests/one-sound.test.ts b/tests/one-sound.test.tsnew file mode 100644index 00000000..1eafbe4f--- /dev/null+++ b/tests/one-sound.test.ts@@ -0,0 +1,126 @@+import { describe, expect, it } from "vitest";+import { audible, claimSound, onOtherSound, SOUND_EVENT, type SoundDocument } from "@/lib/av/one-sound";++/*+ * One sound at a time on a page (src/lib/av/one-sound.ts): a player that starts stops every other sound, and pauses+ * when another starts; muted previews are never touched and never count.+ */++/** A stand-in media element: an event target with the parts the rules read. */+class Media extends EventTarget {+ paused: boolean;+ ended = false;+ muted: boolean;+ volume = 1;+ pauses = 0;+ constructor({ playing = false, muted = false } = {}) {+ super();+ this.paused = !playing;+ this.muted = muted;+ }+ pause() {+ this.paused = true;+ this.pauses++;+ }+ /** Starts playing, firing "play" as a browser does (it doesn't bubble: the page listens in its capture phase). */+ play(doc: FakeDocument) {+ this.paused = false;+ doc.fire("play", this);+ }+}++/** A stand-in document: its media elements, and capture-phase listeners that see each media event. */+class FakeDocument implements SoundDocument {+ media: Media[] = [];+ private listeners = new Map<string, Set<(e: Event) => void>>();+ querySelectorAll() {+ return this.media;+ }+ addEventListener(type: string, listener: (e: Event) => void, capture: boolean) {+ expect(capture).toBe(true);+ if (!this.listeners.has(type)) this.listeners.set(type, new Set());+ this.listeners.get(type)!.add(listener);+ }+ removeEventListener(type: string, listener: (e: Event) => void) {+ this.listeners.get(type)?.delete(listener);+ }+ fire(type: string, target: Media) {+ const e = new Event(type);+ Object.defineProperty(e, "target", { value: target });+ for (const l of this.listeners.get(type) ?? []) l(e);+ }+}++describe("one sound at a time", () => {+ it("counts only what can be heard: playing, sound on", () => {+ expect(audible(new Media({ playing: true }))).toBe(true);+ expect(audible(new Media({ playing: true, muted: true }))).toBe(false);+ expect(audible(new Media())).toBe(false);+ const quiet = new Media({ playing: true });+ quiet.volume = 0;+ expect(audible(quiet)).toBe(false);+ const over = new Media({ playing: true });+ over.ended = true;+ expect(audible(over)).toBe(false);+ expect(audible(null)).toBe(false);+ expect(audible({ paused: false })).toBe(false);+ });++ it("stops every sound on the page when a player starts, and leaves the muted previews playing", () => {+ const doc = new FakeDocument();+ const win = new EventTarget();+ const loud = new Media({ playing: true });+ const preview = new Media({ playing: true, muted: true });+ const still = new Media();+ doc.media = [loud, preview, still];+ const heard: string[] = [];+ win.addEventListener(SOUND_EVENT, (e) => heard.push((e as CustomEvent).detail));+ expect(claimSound("a", doc, win)).toBe(1);+ expect(loud.paused).toBe(true);+ expect([preview.pauses, still.pauses]).toEqual([0, 0]);+ expect(preview.paused).toBe(false);+ expect(heard).toEqual(["a"]);+ });++ it("pauses a player when another claims the sound, but not on its own claim", () => {+ const doc = new FakeDocument();+ const win = new EventTarget();+ let stopsA = 0;+ let stopsB = 0;+ const offA = onOtherSound("a", () => stopsA++, doc, win);+ const offB = onOtherSound("b", () => stopsB++, doc, win);+ claimSound("a", doc, win);+ expect([stopsA, stopsB]).toEqual([0, 1]);+ claimSound("b", doc, win);+ expect([stopsA, stopsB]).toEqual([1, 1]);+ offA();+ offB();+ claimSound("c", doc, win);+ expect([stopsA, stopsB]).toEqual([1, 1]);+ });++ it("pauses a player when a video or a song on the page starts with its sound on, or is unmuted", () => {+ const doc = new FakeDocument();+ const win = new EventTarget();+ let stops = 0;+ const off = onOtherSound("a", () => stops++, doc, win);+ // Home's previews play muted all the time: they never stop the demo.+ const preview = new Media({ muted: true });+ preview.play(doc);+ expect(stops).toBe(0);+ // A clip with its sound on does.+ new Media().play(doc);+ expect(stops).toBe(1);+ // So does a playing preview being unmuted (a volume change on something that can now be heard).+ preview.muted = false;+ doc.fire("volumechange", preview);+ expect(stops).toBe(2);+ // Muting it again is no reason to stop.+ preview.muted = true;+ doc.fire("volumechange", preview);+ expect(stops).toBe(2);+ off();+ new Media().play(doc);+ expect(stops).toBe(2);+ });+});